/*!
 * Copyright (c) 2012 - 2018, Anaconda, Inc., and Bokeh Contributors
 * 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 Anaconda nor the names of any 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.
 */
(function(root, factory) {
//  if(typeof exports === 'object' && typeof module === 'object')
//    module.exports = factory();
//  else if(typeof define === 'function' && define.amd)
//    define("Bokeh", [], factory);
//  else if(typeof exports === 'object')
//    exports["Bokeh"] = factory();
//  else
    root["Bokeh"] = factory();
})(this, function() {
  var define;
  return (function(modules, aliases, entry, parent_require) {
    var cache = {};

    var require = function(name) {
      var id = aliases[name] != null ? aliases[name] : name;

      if (!cache[id]) {
        if (!modules[id]) {
          if (parent_require)
            return parent_require(id)

          var err = new Error("Cannot find module '" + name + "'");
          err.code = 'MODULE_NOT_FOUND';
          throw err;
        }

        var module = cache[id] = {exports: {}};
        modules[id].call(module.exports, require, module, module.exports);
      }

      return cache[id].exports;
    }

    var main = require(entry);
    main.require = require;

    main.register_plugin = function(plugin_modules, plugin_aliases, plugin_entry) {
      for (var name in plugin_modules) {
        modules[name] = plugin_modules[name];
      }

      for (var name in plugin_aliases) {
        aliases[name] = plugin_aliases[name];
      }

      var plugin = require(plugin_entry);

      for (var name in plugin) {
        main[name] = plugin[name];
      }

      return plugin;
    }

    return main;
  })
([
/* compile */ function _(require, module, exports) {
    const fs = require("fs");
    const path = require("path");
    const ts = require(367) /* typescript */;
    const coffee = require(77) /* coffeescript */;
    const less = require(164) /* less */;
    const yargs_1 = require(379) /* yargs */;
    const dependencies_1 = require(1) /* ./dependencies */;
    const mkCoffeescriptError = (error, file) => {
        const message = error.message;
        if (error.location == null) {
            const text = [file || "<string>", message].join(":");
            return { message, text };
        }
        else {
            const location = error.location;
            const line = location.first_line + 1;
            const column = location.first_column + 1;
            const text = [file || "<string>", line, column, message].join(":");
            let markerLen = 2;
            if (location.first_line === location.last_line)
                markerLen += location.last_column - location.first_column;
            const extract = error.code.split('\n')[line - 1];
            const annotated = [
                text,
                "  " + extract,
                "  " + Array(column).join(' ') + Array(markerLen).join('^'),
            ].join('\n');
            return { message, line, column, text, extract, annotated };
        }
    };
    const mkLessError = (error, file) => {
        const message = error.message;
        const line = error.line;
        const column = error.column + 1;
        const text = [file || "<string>", line, column, message].join(":");
        const extract = error.extract[line];
        const annotated = [text, "  " + extract].join("\n");
        return { message, line, column, text, extract, annotated };
    };
    const mkTypeScriptError = (diagnostic) => {
        let { line, character: column } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
        line += 1;
        column += 1;
        const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
        const text = [diagnostic.file.fileName, line, column, message].join(":");
        return { message, line, column, text };
    };
    const reply = (data) => {
        process.stdout.write(JSON.stringify(data));
        process.stdout.write("\n");
    };
    const compile_and_resolve_deps = (input) => {
        let code;
        switch (input.lang) {
            case "coffeescript":
                try {
                    code = coffee.compile(input.code, { bare: true, shiftLine: true });
                }
                catch (error) {
                    return reply({ error: mkCoffeescriptError(error, input.file) });
                }
                break;
            case "javascript":
            case "typescript":
                code = input.code;
                break;
            case "less":
                const options = {
                    paths: [path.dirname(input.file)],
                    compress: true,
                    ieCompat: false,
                };
                less.render(input.code, options, (error, output) => {
                    if (error != null)
                        reply({ error: mkLessError(error, input.file) });
                    else
                        reply({ code: output.css });
                });
                return;
            default:
                throw new Error(`unsupported input type: ${input.lang}`);
        }
        const result = ts.transpileModule(code, {
            fileName: input.file,
            reportDiagnostics: true,
            compilerOptions: {
                noEmitOnError: false,
                noImplicitAny: false,
                target: ts.ScriptTarget.ES5,
                module: ts.ModuleKind.CommonJS,
            },
        });
        if (result.diagnostics != null && result.diagnostics.length > 0) {
            const diagnostic = result.diagnostics[0];
            return reply({ error: mkTypeScriptError(diagnostic) });
        }
        code = result.outputText;
        const source = ts.createSourceFile(input.file, code, ts.ScriptTarget.ES5, true, ts.ScriptKind.JS);
        const deps = dependencies_1.collect_deps(source);
        return reply({ code, deps });
    };
    if (yargs_1.argv.file != null) {
        const input = {
            code: fs.readFileSync(yargs_1.argv.file, "utf-8"),
            lang: yargs_1.argv.lang || "coffeescript",
            file: yargs_1.argv.file,
        };
        compile_and_resolve_deps(input);
    }
    else {
        const stdin = process.stdin;
        stdin.resume();
        stdin.setEncoding("utf-8");
        let data = "";
        stdin.on("data", (chunk) => data += chunk);
        stdin.on("end", () => compile_and_resolve_deps(JSON.parse(data)));
    }
}
,
/* dependencies */ function _(require, module, exports) {
    const ts = require(367) /* typescript */;
    function kind_of(node, kind) {
        return node.kind === kind;
    }
    function is_CallExpression(node) {
        return kind_of(node, ts.SyntaxKind.CallExpression);
    }
    function is_Identifier(node) {
        return kind_of(node, ts.SyntaxKind.Identifier);
    }
    function is_StringLiteral(node) {
        return kind_of(node, ts.SyntaxKind.StringLiteral);
    }
    function is_require(node) {
        return is_CallExpression(node) &&
            is_Identifier(node.expression) &&
            node.expression.text === "require" &&
            node.arguments.length === 1;
    }
    function collect_deps(source) {
        function traverse(node) {
            if (is_require(node)) {
                const [arg] = node.arguments;
                if (is_StringLiteral(arg) && arg.text.length > 0)
                    deps.push(arg.text);
            }
            ts.forEachChild(node, traverse);
        }
        const deps = [];
        traverse(source);
        return deps;
    }
    exports.collect_deps = collect_deps;
}
,
/* ajv/lib/$data */ function _(require, module, exports) {
    var KEYWORDS = [
        'multipleOf',
        'maximum',
        'exclusiveMaximum',
        'minimum',
        'exclusiveMinimum',
        'maxLength',
        'minLength',
        'pattern',
        'additionalItems',
        'maxItems',
        'minItems',
        'uniqueItems',
        'maxProperties',
        'minProperties',
        'required',
        'additionalProperties',
        'enum',
        'format',
        'const'
    ];
    module.exports = function (metaSchema, keywordsJsonPointers) {
        for (var i = 0; i < keywordsJsonPointers.length; i++) {
            metaSchema = JSON.parse(JSON.stringify(metaSchema));
            var segments = keywordsJsonPointers[i].split('/');
            var keywords = metaSchema;
            var j;
            for (j = 1; j < segments.length; j++)
                keywords = keywords[segments[j]];
            for (j = 0; j < KEYWORDS.length; j++) {
                var key = KEYWORDS[j];
                var schema = keywords[key];
                if (schema) {
                    keywords[key] = {
                        anyOf: [
                            schema,
                            { $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }
                        ]
                    };
                }
            }
        }
        return metaSchema;
    };
}
,
/* ajv/lib/ajv */ function _(require, module, exports) {
    var compileSchema = require(9) /* ./compile */, resolve = require(10) /* ./compile/resolve */, Cache = require(4) /* ./cache */, SchemaObject = require(12) /* ./compile/schema_obj */, stableStringify = require(109) /* fast-json-stable-stringify */, formats = require(8) /* ./compile/formats */, rules = require(11) /* ./compile/rules */, $dataMetaSchema = require(2) /* ./$data */, patternGroups = require(39) /* ./patternGroups */, util = require(14) /* ./compile/util */, co = require(74) /* co */;
    module.exports = Ajv;
    Ajv.prototype.validate = validate;
    Ajv.prototype.compile = compile;
    Ajv.prototype.addSchema = addSchema;
    Ajv.prototype.addMetaSchema = addMetaSchema;
    Ajv.prototype.validateSchema = validateSchema;
    Ajv.prototype.getSchema = getSchema;
    Ajv.prototype.removeSchema = removeSchema;
    Ajv.prototype.addFormat = addFormat;
    Ajv.prototype.errorsText = errorsText;
    Ajv.prototype._addSchema = _addSchema;
    Ajv.prototype._compile = _compile;
    Ajv.prototype.compileAsync = require(6) /* ./compile/async */;
    var customKeyword = require(38) /* ./keyword */;
    Ajv.prototype.addKeyword = customKeyword.add;
    Ajv.prototype.getKeyword = customKeyword.get;
    Ajv.prototype.removeKeyword = customKeyword.remove;
    var errorClasses = require(7) /* ./compile/error_classes */;
    Ajv.ValidationError = errorClasses.Validation;
    Ajv.MissingRefError = errorClasses.MissingRef;
    Ajv.$dataMetaSchema = $dataMetaSchema;
    var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema';
    var META_IGNORE_OPTIONS = ['removeAdditional', 'useDefaults', 'coerceTypes'];
    var META_SUPPORT_DATA = ['/properties'];
    /**
     * Creates validator instance.
     * Usage: `Ajv(opts)`
     * @param {Object} opts optional options
     * @return {Object} ajv instance
     */
    function Ajv(opts) {
        if (!(this instanceof Ajv))
            return new Ajv(opts);
        opts = this._opts = util.copy(opts) || {};
        setLogger(this);
        this._schemas = {};
        this._refs = {};
        this._fragments = {};
        this._formats = formats(opts.format);
        var schemaUriFormat = this._schemaUriFormat = this._formats['uri-reference'];
        this._schemaUriFormatFunc = function (str) { return schemaUriFormat.test(str); };
        this._cache = opts.cache || new Cache;
        this._loadingSchemas = {};
        this._compilations = [];
        this.RULES = rules();
        this._getId = chooseGetId(opts);
        opts.loopRequired = opts.loopRequired || Infinity;
        if (opts.errorDataPath == 'property')
            opts._errorDataPathProperty = true;
        if (opts.serialize === undefined)
            opts.serialize = stableStringify;
        this._metaOpts = getMetaSchemaOptions(this);
        if (opts.formats)
            addInitialFormats(this);
        addDraft6MetaSchema(this);
        if (typeof opts.meta == 'object')
            this.addMetaSchema(opts.meta);
        addInitialSchemas(this);
        if (opts.patternGroups)
            patternGroups(this);
    }
    /**
     * Validate data using schema
     * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
     * @this   Ajv
     * @param  {String|Object} schemaKeyRef key, ref or schema object
     * @param  {Any} data to be validated
     * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
     */
    function validate(schemaKeyRef, data) {
        var v;
        if (typeof schemaKeyRef == 'string') {
            v = this.getSchema(schemaKeyRef);
            if (!v)
                throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
        }
        else {
            var schemaObj = this._addSchema(schemaKeyRef);
            v = schemaObj.validate || this._compile(schemaObj);
        }
        var valid = v(data);
        if (v.$async === true)
            return this._opts.async == '*' ? co(valid) : valid;
        this.errors = v.errors;
        return valid;
    }
    /**
     * Create validating function for passed schema.
     * @this   Ajv
     * @param  {Object} schema schema object
     * @param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
     * @return {Function} validating function
     */
    function compile(schema, _meta) {
        var schemaObj = this._addSchema(schema, undefined, _meta);
        return schemaObj.validate || this._compile(schemaObj);
    }
    /**
     * Adds schema to the instance.
     * @this   Ajv
     * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
     * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
     * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
     * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
     * @return {Ajv} this for method chaining
     */
    function addSchema(schema, key, _skipValidation, _meta) {
        if (Array.isArray(schema)) {
            for (var i = 0; i < schema.length; i++)
                this.addSchema(schema[i], undefined, _skipValidation, _meta);
            return this;
        }
        var id = this._getId(schema);
        if (id !== undefined && typeof id != 'string')
            throw new Error('schema id must be string');
        key = resolve.normalizeId(key || id);
        checkUnique(this, key);
        this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
        return this;
    }
    /**
     * Add schema that will be used to validate other schemas
     * options in META_IGNORE_OPTIONS are alway set to false
     * @this   Ajv
     * @param {Object} schema schema object
     * @param {String} key optional schema key
     * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
     * @return {Ajv} this for method chaining
     */
    function addMetaSchema(schema, key, skipValidation) {
        this.addSchema(schema, key, skipValidation, true);
        return this;
    }
    /**
     * Validate schema
     * @this   Ajv
     * @param {Object} schema schema to validate
     * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
     * @return {Boolean} true if schema is valid
     */
    function validateSchema(schema, throwOrLogError) {
        var $schema = schema.$schema;
        if ($schema !== undefined && typeof $schema != 'string')
            throw new Error('$schema must be a string');
        $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
        if (!$schema) {
            this.logger.warn('meta-schema not available');
            this.errors = null;
            return true;
        }
        var currentUriFormat = this._formats.uri;
        this._formats.uri = typeof currentUriFormat == 'function'
            ? this._schemaUriFormatFunc
            : this._schemaUriFormat;
        var valid;
        try {
            valid = this.validate($schema, schema);
        }
        finally {
            this._formats.uri = currentUriFormat;
        }
        if (!valid && throwOrLogError) {
            var message = 'schema is invalid: ' + this.errorsText();
            if (this._opts.validateSchema == 'log')
                this.logger.error(message);
            else
                throw new Error(message);
        }
        return valid;
    }
    function defaultMeta(self) {
        var meta = self._opts.meta;
        self._opts.defaultMeta = typeof meta == 'object'
            ? self._getId(meta) || meta
            : self.getSchema(META_SCHEMA_ID)
                ? META_SCHEMA_ID
                : undefined;
        return self._opts.defaultMeta;
    }
    /**
     * Get compiled schema from the instance by `key` or `ref`.
     * @this   Ajv
     * @param  {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
     * @return {Function} schema validating function (with property `schema`).
     */
    function getSchema(keyRef) {
        var schemaObj = _getSchemaObj(this, keyRef);
        switch (typeof schemaObj) {
            case 'object': return schemaObj.validate || this._compile(schemaObj);
            case 'string': return this.getSchema(schemaObj);
            case 'undefined': return _getSchemaFragment(this, keyRef);
        }
    }
    function _getSchemaFragment(self, ref) {
        var res = resolve.schema.call(self, { schema: {} }, ref);
        if (res) {
            var schema = res.schema, root = res.root, baseId = res.baseId;
            var v = compileSchema.call(self, schema, root, undefined, baseId);
            self._fragments[ref] = new SchemaObject({
                ref: ref,
                fragment: true,
                schema: schema,
                root: root,
                baseId: baseId,
                validate: v
            });
            return v;
        }
    }
    function _getSchemaObj(self, keyRef) {
        keyRef = resolve.normalizeId(keyRef);
        return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
    }
    /**
     * Remove cached schema(s).
     * If no parameter is passed all schemas but meta-schemas are removed.
     * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
     * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
     * @this   Ajv
     * @param  {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
     * @return {Ajv} this for method chaining
     */
    function removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
            _removeAllSchemas(this, this._schemas, schemaKeyRef);
            _removeAllSchemas(this, this._refs, schemaKeyRef);
            return this;
        }
        switch (typeof schemaKeyRef) {
            case 'undefined':
                _removeAllSchemas(this, this._schemas);
                _removeAllSchemas(this, this._refs);
                this._cache.clear();
                return this;
            case 'string':
                var schemaObj = _getSchemaObj(this, schemaKeyRef);
                if (schemaObj)
                    this._cache.del(schemaObj.cacheKey);
                delete this._schemas[schemaKeyRef];
                delete this._refs[schemaKeyRef];
                return this;
            case 'object':
                var serialize = this._opts.serialize;
                var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
                this._cache.del(cacheKey);
                var id = this._getId(schemaKeyRef);
                if (id) {
                    id = resolve.normalizeId(id);
                    delete this._schemas[id];
                    delete this._refs[id];
                }
        }
        return this;
    }
    function _removeAllSchemas(self, schemas, regex) {
        for (var keyRef in schemas) {
            var schemaObj = schemas[keyRef];
            if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
                self._cache.del(schemaObj.cacheKey);
                delete schemas[keyRef];
            }
        }
    }
    /* @this   Ajv */
    function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
        if (typeof schema != 'object' && typeof schema != 'boolean')
            throw new Error('schema should be object or boolean');
        var serialize = this._opts.serialize;
        var cacheKey = serialize ? serialize(schema) : schema;
        var cached = this._cache.get(cacheKey);
        if (cached)
            return cached;
        shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
        var id = resolve.normalizeId(this._getId(schema));
        if (id && shouldAddSchema)
            checkUnique(this, id);
        var willValidate = this._opts.validateSchema !== false && !skipValidation;
        var recursiveMeta;
        if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
            this.validateSchema(schema, true);
        var localRefs = resolve.ids.call(this, schema);
        var schemaObj = new SchemaObject({
            id: id,
            schema: schema,
            localRefs: localRefs,
            cacheKey: cacheKey,
            meta: meta
        });
        if (id[0] != '#' && shouldAddSchema)
            this._refs[id] = schemaObj;
        this._cache.put(cacheKey, schemaObj);
        if (willValidate && recursiveMeta)
            this.validateSchema(schema, true);
        return schemaObj;
    }
    /* @this   Ajv */
    function _compile(schemaObj, root) {
        if (schemaObj.compiling) {
            schemaObj.validate = callValidate;
            callValidate.schema = schemaObj.schema;
            callValidate.errors = null;
            callValidate.root = root ? root : callValidate;
            if (schemaObj.schema.$async === true)
                callValidate.$async = true;
            return callValidate;
        }
        schemaObj.compiling = true;
        var currentOpts;
        if (schemaObj.meta) {
            currentOpts = this._opts;
            this._opts = this._metaOpts;
        }
        var v;
        try {
            v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs);
        }
        finally {
            schemaObj.compiling = false;
            if (schemaObj.meta)
                this._opts = currentOpts;
        }
        schemaObj.validate = v;
        schemaObj.refs = v.refs;
        schemaObj.refVal = v.refVal;
        schemaObj.root = v.root;
        return v;
        function callValidate() {
            var _validate = schemaObj.validate;
            var result = _validate.apply(null, arguments);
            callValidate.errors = _validate.errors;
            return result;
        }
    }
    function chooseGetId(opts) {
        switch (opts.schemaId) {
            case '$id': return _get$Id;
            case 'id': return _getId;
            default: return _get$IdOrId;
        }
    }
    /* @this   Ajv */
    function _getId(schema) {
        if (schema.$id)
            this.logger.warn('schema $id ignored', schema.$id);
        return schema.id;
    }
    /* @this   Ajv */
    function _get$Id(schema) {
        if (schema.id)
            this.logger.warn('schema id ignored', schema.id);
        return schema.$id;
    }
    function _get$IdOrId(schema) {
        if (schema.$id && schema.id && schema.$id != schema.id)
            throw new Error('schema $id is different from id');
        return schema.$id || schema.id;
    }
    /**
     * Convert array of error message objects to string
     * @this   Ajv
     * @param  {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
     * @param  {Object} options optional options with properties `separator` and `dataVar`.
     * @return {String} human readable string with all errors descriptions
     */
    function errorsText(errors, options) {
        errors = errors || this.errors;
        if (!errors)
            return 'No errors';
        options = options || {};
        var separator = options.separator === undefined ? ', ' : options.separator;
        var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
        var text = '';
        for (var i = 0; i < errors.length; i++) {
            var e = errors[i];
            if (e)
                text += dataVar + e.dataPath + ' ' + e.message + separator;
        }
        return text.slice(0, -separator.length);
    }
    /**
     * Add custom format
     * @this   Ajv
     * @param {String} name format name
     * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
     * @return {Ajv} this for method chaining
     */
    function addFormat(name, format) {
        if (typeof format == 'string')
            format = new RegExp(format);
        this._formats[name] = format;
        return this;
    }
    function addDraft6MetaSchema(self) {
        var $dataSchema;
        if (self._opts.$data) {
            $dataSchema = require(40) /* ./refs/$data.json */;
            self.addMetaSchema($dataSchema, $dataSchema.$id, true);
        }
        if (self._opts.meta === false)
            return;
        var metaSchema = require(41) /* ./refs/json-schema-draft-06.json */;
        if (self._opts.$data)
            metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
        self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
        self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
    }
    function addInitialSchemas(self) {
        var optsSchemas = self._opts.schemas;
        if (!optsSchemas)
            return;
        if (Array.isArray(optsSchemas))
            self.addSchema(optsSchemas);
        else
            for (var key in optsSchemas)
                self.addSchema(optsSchemas[key], key);
    }
    function addInitialFormats(self) {
        for (var name in self._opts.formats) {
            var format = self._opts.formats[name];
            self.addFormat(name, format);
        }
    }
    function checkUnique(self, id) {
        if (self._schemas[id] || self._refs[id])
            throw new Error('schema with key or id "' + id + '" already exists');
    }
    function getMetaSchemaOptions(self) {
        var metaOpts = util.copy(self._opts);
        for (var i = 0; i < META_IGNORE_OPTIONS.length; i++)
            delete metaOpts[META_IGNORE_OPTIONS[i]];
        return metaOpts;
    }
    function setLogger(self) {
        var logger = self._opts.logger;
        if (logger === false) {
            self.logger = { log: noop, warn: noop, error: noop };
        }
        else {
            if (logger === undefined)
                logger = console;
            if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
                throw new Error('logger must implement log, warn and error methods');
            self.logger = logger;
        }
    }
    function noop() { }
}
,
/* ajv/lib/cache */ function _(require, module, exports) {
    var Cache = module.exports = function Cache() {
        this._cache = {};
    };
    Cache.prototype.put = function Cache_put(key, value) {
        this._cache[key] = value;
    };
    Cache.prototype.get = function Cache_get(key) {
        return this._cache[key];
    };
    Cache.prototype.del = function Cache_del(key) {
        delete this._cache[key];
    };
    Cache.prototype.clear = function Cache_clear() {
        this._cache = {};
    };
}
,
/* ajv/lib/compile/_rules */ function _(require, module, exports) {
    //all requires must be explicit because browserify won't work with dynamic requires
    module.exports = {
        '$ref': require(34) /* ../dotjs/ref */,
        allOf: require(19) /* ../dotjs/allOf */,
        anyOf: require(20) /* ../dotjs/anyOf */,
        const: require(21) /* ../dotjs/const */,
        contains: require(22) /* ../dotjs/contains */,
        dependencies: require(24) /* ../dotjs/dependencies */,
        'enum': require(25) /* ../dotjs/enum */,
        format: require(26) /* ../dotjs/format */,
        items: require(27) /* ../dotjs/items */,
        maximum: require(15) /* ../dotjs/_limit */,
        minimum: require(15) /* ../dotjs/_limit */,
        maxItems: require(16) /* ../dotjs/_limitItems */,
        minItems: require(16) /* ../dotjs/_limitItems */,
        maxLength: require(17) /* ../dotjs/_limitLength */,
        minLength: require(17) /* ../dotjs/_limitLength */,
        maxProperties: require(18) /* ../dotjs/_limitProperties */,
        minProperties: require(18) /* ../dotjs/_limitProperties */,
        multipleOf: require(28) /* ../dotjs/multipleOf */,
        not: require(29) /* ../dotjs/not */,
        oneOf: require(30) /* ../dotjs/oneOf */,
        pattern: require(31) /* ../dotjs/pattern */,
        properties: require(32) /* ../dotjs/properties */,
        propertyNames: require(33) /* ../dotjs/propertyNames */,
        required: require(35) /* ../dotjs/required */,
        uniqueItems: require(36) /* ../dotjs/uniqueItems */,
        validate: require(37) /* ../dotjs/validate */
    };
}
,
/* ajv/lib/compile/async */ function _(require, module, exports) {
    var MissingRefError = require(7) /* ./error_classes */.MissingRef;
    module.exports = compileAsync;
    /**
     * Creates validating function for passed schema with asynchronous loading of missing schemas.
     * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
     * @this  Ajv
     * @param {Object}   schema schema object
     * @param {Boolean}  meta optional true to compile meta-schema; this parameter can be skipped
     * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
     * @return {Promise} promise that resolves with a validating function.
     */
    function compileAsync(schema, meta, callback) {
        /* eslint no-shadow: 0 */
        /* global Promise */
        /* jshint validthis: true */
        var self = this;
        if (typeof this._opts.loadSchema != 'function')
            throw new Error('options.loadSchema should be a function');
        if (typeof meta == 'function') {
            callback = meta;
            meta = undefined;
        }
        var p = loadMetaSchemaOf(schema).then(function () {
            var schemaObj = self._addSchema(schema, undefined, meta);
            return schemaObj.validate || _compileAsync(schemaObj);
        });
        if (callback) {
            p.then(function (v) { callback(null, v); }, callback);
        }
        return p;
        function loadMetaSchemaOf(sch) {
            var $schema = sch.$schema;
            return $schema && !self.getSchema($schema)
                ? compileAsync.call(self, { $ref: $schema }, true)
                : Promise.resolve();
        }
        function _compileAsync(schemaObj) {
            try {
                return self._compile(schemaObj);
            }
            catch (e) {
                if (e instanceof MissingRefError)
                    return loadMissingSchema(e);
                throw e;
            }
            function loadMissingSchema(e) {
                var ref = e.missingSchema;
                if (added(ref))
                    throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
                var schemaPromise = self._loadingSchemas[ref];
                if (!schemaPromise) {
                    schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
                    schemaPromise.then(removePromise, removePromise);
                }
                return schemaPromise.then(function (sch) {
                    if (!added(ref)) {
                        return loadMetaSchemaOf(sch).then(function () {
                            if (!added(ref))
                                self.addSchema(sch, ref, undefined, meta);
                        });
                    }
                }).then(function () {
                    return _compileAsync(schemaObj);
                });
                function removePromise() {
                    delete self._loadingSchemas[ref];
                }
                function added(ref) {
                    return self._refs[ref] || self._schemas[ref];
                }
            }
        }
    }
}
,
/* ajv/lib/compile/error_classes */ function _(require, module, exports) {
    var resolve = require(10) /* ./resolve */;
    module.exports = {
        Validation: errorSubclass(ValidationError),
        MissingRef: errorSubclass(MissingRefError)
    };
    function ValidationError(errors) {
        this.message = 'validation failed';
        this.errors = errors;
        this.ajv = this.validation = true;
    }
    MissingRefError.message = function (baseId, ref) {
        return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
    };
    function MissingRefError(baseId, ref, message) {
        this.message = message || MissingRefError.message(baseId, ref);
        this.missingRef = resolve.url(baseId, ref);
        this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
    }
    function errorSubclass(Subclass) {
        Subclass.prototype = Object.create(Error.prototype);
        Subclass.prototype.constructor = Subclass;
        return Subclass;
    }
}
,
/* ajv/lib/compile/formats */ function _(require, module, exports) {
    var util = require(14) /* ./util */;
    var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/;
    var DAYS = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
    var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
    var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
    var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
    // uri-template: https://tools.ietf.org/html/rfc6570
    var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
    // For the source: https://gist.github.com/dperini/729294
    // For test cases: https://mathiasbynens.be/demo/url-regex
    // @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
    // var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
    var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
    var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
    var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$|^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
    var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
    module.exports = formats;
    function formats(mode) {
        mode = mode == 'full' ? 'full' : 'fast';
        return util.copy(formats[mode]);
    }
    formats.fast = {
        // date: http://tools.ietf.org/html/rfc3339#section-5.6
        date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
        // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
        time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
        'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
        // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
        uri: /^(?:[a-z][a-z0-9+-.]*)(?::|\/)\/?[^\s]*$/i,
        'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i,
        'uri-template': URITEMPLATE,
        url: URL,
        // email (sources from jsen validator):
        // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
        // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
        email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
        hostname: HOSTNAME,
        // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
        ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
        // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
        ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
        regex: regex,
        // uuid: http://tools.ietf.org/html/rfc4122
        uuid: UUID,
        // JSON-pointer: https://tools.ietf.org/html/rfc6901
        // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
        'json-pointer': JSON_POINTER,
        // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
        'relative-json-pointer': RELATIVE_JSON_POINTER
    };
    formats.full = {
        date: date,
        time: time,
        'date-time': date_time,
        uri: uri,
        'uri-reference': URIREF,
        'uri-template': URITEMPLATE,
        url: URL,
        email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
        hostname: hostname,
        ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
        ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
        regex: regex,
        uuid: UUID,
        'json-pointer': JSON_POINTER,
        'relative-json-pointer': RELATIVE_JSON_POINTER
    };
    function date(str) {
        // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
        var matches = str.match(DATE);
        if (!matches)
            return false;
        var month = +matches[1];
        var day = +matches[2];
        return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month];
    }
    function time(str, full) {
        var matches = str.match(TIME);
        if (!matches)
            return false;
        var hour = matches[1];
        var minute = matches[2];
        var second = matches[3];
        var timeZone = matches[5];
        return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone);
    }
    var DATE_TIME_SEPARATOR = /t|\s/i;
    function date_time(str) {
        // http://tools.ietf.org/html/rfc3339#section-5.6
        var dateTime = str.split(DATE_TIME_SEPARATOR);
        return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
    }
    function hostname(str) {
        // https://tools.ietf.org/html/rfc1034#section-3.5
        // https://tools.ietf.org/html/rfc1123#section-2
        return str.length <= 255 && HOSTNAME.test(str);
    }
    var NOT_URI_FRAGMENT = /\/|:/;
    function uri(str) {
        // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
        return NOT_URI_FRAGMENT.test(str) && URI.test(str);
    }
    var Z_ANCHOR = /[^\\]\\Z/;
    function regex(str) {
        if (Z_ANCHOR.test(str))
            return false;
        try {
            new RegExp(str);
            return true;
        }
        catch (e) {
            return false;
        }
    }
}
,
/* ajv/lib/compile/index */ function _(require, module, exports) {
    var resolve = require(10) /* ./resolve */, util = require(14) /* ./util */, errorClasses = require(7) /* ./error_classes */, stableStringify = require(109) /* fast-json-stable-stringify */;
    var validateGenerator = require(37) /* ../dotjs/validate */;
    /**
     * Functions below are used inside compiled validations function
     */
    var co = require(74) /* co */;
    var ucs2length = util.ucs2length;
    var equal = require(108) /* fast-deep-equal */;
    // this error is thrown by async schemas to return validation errors via exception
    var ValidationError = errorClasses.Validation;
    module.exports = compile;
    /**
     * Compiles schema to validation function
     * @this   Ajv
     * @param  {Object} schema schema object
     * @param  {Object} root object with information about the root schema for this schema
     * @param  {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
     * @param  {String} baseId base ID for IDs in the schema
     * @return {Function} validation function
     */
    function compile(schema, root, localRefs, baseId) {
        /* jshint validthis: true, evil: true */
        /* eslint no-shadow: 0 */
        var self = this, opts = this._opts, refVal = [undefined], refs = {}, patterns = [], patternsHash = {}, defaults = [], defaultsHash = {}, customRules = [];
        root = root || { schema: schema, refVal: refVal, refs: refs };
        var c = checkCompiling.call(this, schema, root, baseId);
        var compilation = this._compilations[c.index];
        if (c.compiling)
            return (compilation.callValidate = callValidate);
        var formats = this._formats;
        var RULES = this.RULES;
        try {
            var v = localCompile(schema, root, localRefs, baseId);
            compilation.validate = v;
            var cv = compilation.callValidate;
            if (cv) {
                cv.schema = v.schema;
                cv.errors = null;
                cv.refs = v.refs;
                cv.refVal = v.refVal;
                cv.root = v.root;
                cv.$async = v.$async;
                if (opts.sourceCode)
                    cv.source = v.source;
            }
            return v;
        }
        finally {
            endCompiling.call(this, schema, root, baseId);
        }
        function callValidate() {
            var validate = compilation.validate;
            var result = validate.apply(null, arguments);
            callValidate.errors = validate.errors;
            return result;
        }
        function localCompile(_schema, _root, localRefs, baseId) {
            var isRoot = !_root || (_root && _root.schema == _schema);
            if (_root.schema != root.schema)
                return compile.call(self, _schema, _root, localRefs, baseId);
            var $async = _schema.$async === true;
            var sourceCode = validateGenerator({
                isTop: true,
                schema: _schema,
                isRoot: isRoot,
                baseId: baseId,
                root: _root,
                schemaPath: '',
                errSchemaPath: '#',
                errorPath: '""',
                MissingRefError: errorClasses.MissingRef,
                RULES: RULES,
                validate: validateGenerator,
                util: util,
                resolve: resolve,
                resolveRef: resolveRef,
                usePattern: usePattern,
                useDefault: useDefault,
                useCustomRule: useCustomRule,
                opts: opts,
                formats: formats,
                logger: self.logger,
                self: self
            });
            sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
                + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
                + sourceCode;
            if (opts.processCode)
                sourceCode = opts.processCode(sourceCode);
            // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
            var validate;
            try {
                var makeValidate = new Function('self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'co', 'equal', 'ucs2length', 'ValidationError', sourceCode);
                validate = makeValidate(self, RULES, formats, root, refVal, defaults, customRules, co, equal, ucs2length, ValidationError);
                refVal[0] = validate;
            }
            catch (e) {
                self.logger.error('Error compiling schema, function code:', sourceCode);
                throw e;
            }
            validate.schema = _schema;
            validate.errors = null;
            validate.refs = refs;
            validate.refVal = refVal;
            validate.root = isRoot ? validate : _root;
            if ($async)
                validate.$async = true;
            if (opts.sourceCode === true) {
                validate.source = {
                    code: sourceCode,
                    patterns: patterns,
                    defaults: defaults
                };
            }
            return validate;
        }
        function resolveRef(baseId, ref, isRoot) {
            ref = resolve.url(baseId, ref);
            var refIndex = refs[ref];
            var _refVal, refCode;
            if (refIndex !== undefined) {
                _refVal = refVal[refIndex];
                refCode = 'refVal[' + refIndex + ']';
                return resolvedRef(_refVal, refCode);
            }
            if (!isRoot && root.refs) {
                var rootRefId = root.refs[ref];
                if (rootRefId !== undefined) {
                    _refVal = root.refVal[rootRefId];
                    refCode = addLocalRef(ref, _refVal);
                    return resolvedRef(_refVal, refCode);
                }
            }
            refCode = addLocalRef(ref);
            var v = resolve.call(self, localCompile, root, ref);
            if (v === undefined) {
                var localSchema = localRefs && localRefs[ref];
                if (localSchema) {
                    v = resolve.inlineRef(localSchema, opts.inlineRefs)
                        ? localSchema
                        : compile.call(self, localSchema, root, localRefs, baseId);
                }
            }
            if (v === undefined) {
                removeLocalRef(ref);
            }
            else {
                replaceLocalRef(ref, v);
                return resolvedRef(v, refCode);
            }
        }
        function addLocalRef(ref, v) {
            var refId = refVal.length;
            refVal[refId] = v;
            refs[ref] = refId;
            return 'refVal' + refId;
        }
        function removeLocalRef(ref) {
            delete refs[ref];
        }
        function replaceLocalRef(ref, v) {
            var refId = refs[ref];
            refVal[refId] = v;
        }
        function resolvedRef(refVal, code) {
            return typeof refVal == 'object' || typeof refVal == 'boolean'
                ? { code: code, schema: refVal, inline: true }
                : { code: code, $async: refVal && refVal.$async };
        }
        function usePattern(regexStr) {
            var index = patternsHash[regexStr];
            if (index === undefined) {
                index = patternsHash[regexStr] = patterns.length;
                patterns[index] = regexStr;
            }
            return 'pattern' + index;
        }
        function useDefault(value) {
            switch (typeof value) {
                case 'boolean':
                case 'number':
                    return '' + value;
                case 'string':
                    return util.toQuotedString(value);
                case 'object':
                    if (value === null)
                        return 'null';
                    var valueStr = stableStringify(value);
                    var index = defaultsHash[valueStr];
                    if (index === undefined) {
                        index = defaultsHash[valueStr] = defaults.length;
                        defaults[index] = value;
                    }
                    return 'default' + index;
            }
        }
        function useCustomRule(rule, schema, parentSchema, it) {
            var validateSchema = rule.definition.validateSchema;
            if (validateSchema && self._opts.validateSchema !== false) {
                var valid = validateSchema(schema);
                if (!valid) {
                    var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
                    if (self._opts.validateSchema == 'log')
                        self.logger.error(message);
                    else
                        throw new Error(message);
                }
            }
            var compile = rule.definition.compile, inline = rule.definition.inline, macro = rule.definition.macro;
            var validate;
            if (compile) {
                validate = compile.call(self, schema, parentSchema, it);
            }
            else if (macro) {
                validate = macro.call(self, schema, parentSchema, it);
                if (opts.validateSchema !== false)
                    self.validateSchema(validate, true);
            }
            else if (inline) {
                validate = inline.call(self, it, rule.keyword, schema, parentSchema);
            }
            else {
                validate = rule.definition.validate;
                if (!validate)
                    return;
            }
            if (validate === undefined)
                throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
            var index = customRules.length;
            customRules[index] = validate;
            return {
                code: 'customRule' + index,
                validate: validate
            };
        }
    }
    /**
     * Checks if the schema is currently compiled
     * @this   Ajv
     * @param  {Object} schema schema to compile
     * @param  {Object} root root object
     * @param  {String} baseId base schema ID
     * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
     */
    function checkCompiling(schema, root, baseId) {
        /* jshint validthis: true */
        var index = compIndex.call(this, schema, root, baseId);
        if (index >= 0)
            return { index: index, compiling: true };
        index = this._compilations.length;
        this._compilations[index] = {
            schema: schema,
            root: root,
            baseId: baseId
        };
        return { index: index, compiling: false };
    }
    /**
     * Removes the schema from the currently compiled list
     * @this   Ajv
     * @param  {Object} schema schema to compile
     * @param  {Object} root root object
     * @param  {String} baseId base schema ID
     */
    function endCompiling(schema, root, baseId) {
        /* jshint validthis: true */
        var i = compIndex.call(this, schema, root, baseId);
        if (i >= 0)
            this._compilations.splice(i, 1);
    }
    /**
     * Index of schema compilation in the currently compiled list
     * @this   Ajv
     * @param  {Object} schema schema to compile
     * @param  {Object} root root object
     * @param  {String} baseId base schema ID
     * @return {Integer} compilation index
     */
    function compIndex(schema, root, baseId) {
        /* jshint validthis: true */
        for (var i = 0; i < this._compilations.length; i++) {
            var c = this._compilations[i];
            if (c.schema == schema && c.root == root && c.baseId == baseId)
                return i;
        }
        return -1;
    }
    function patternCode(i, patterns) {
        return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
    }
    function defaultCode(i) {
        return 'var default' + i + ' = defaults[' + i + '];';
    }
    function refValCode(i, refVal) {
        return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
    }
    function customRuleCode(i) {
        return 'var customRule' + i + ' = customRules[' + i + '];';
    }
    function vars(arr, statement) {
        if (!arr.length)
            return '';
        var code = '';
        for (var i = 0; i < arr.length; i++)
            code += statement(i, arr);
        return code;
    }
}
,
/* ajv/lib/compile/resolve */ function _(require, module, exports) {
    var url = require('url'), equal = require(108) /* fast-deep-equal */, util = require(14) /* ./util */, SchemaObject = require(12) /* ./schema_obj */, traverse = require(156) /* json-schema-traverse */;
    module.exports = resolve;
    resolve.normalizeId = normalizeId;
    resolve.fullPath = getFullPath;
    resolve.url = resolveUrl;
    resolve.ids = resolveIds;
    resolve.inlineRef = inlineRef;
    resolve.schema = resolveSchema;
    /**
     * [resolve and compile the references ($ref)]
     * @this   Ajv
     * @param  {Function} compile reference to schema compilation funciton (localCompile)
     * @param  {Object} root object with information about the root schema for the current schema
     * @param  {String} ref reference to resolve
     * @return {Object|Function} schema object (if the schema can be inlined) or validation function
     */
    function resolve(compile, root, ref) {
        /* jshint validthis: true */
        var refVal = this._refs[ref];
        if (typeof refVal == 'string') {
            if (this._refs[refVal])
                refVal = this._refs[refVal];
            else
                return resolve.call(this, compile, root, refVal);
        }
        refVal = refVal || this._schemas[ref];
        if (refVal instanceof SchemaObject) {
            return inlineRef(refVal.schema, this._opts.inlineRefs)
                ? refVal.schema
                : refVal.validate || this._compile(refVal);
        }
        var res = resolveSchema.call(this, root, ref);
        var schema, v, baseId;
        if (res) {
            schema = res.schema;
            root = res.root;
            baseId = res.baseId;
        }
        if (schema instanceof SchemaObject) {
            v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
        }
        else if (schema !== undefined) {
            v = inlineRef(schema, this._opts.inlineRefs)
                ? schema
                : compile.call(this, schema, root, undefined, baseId);
        }
        return v;
    }
    /**
     * Resolve schema, its root and baseId
     * @this Ajv
     * @param  {Object} root root object with properties schema, refVal, refs
     * @param  {String} ref  reference to resolve
     * @return {Object} object with properties schema, root, baseId
     */
    function resolveSchema(root, ref) {
        /* jshint validthis: true */
        var p = url.parse(ref, false, true), refPath = _getFullPath(p), baseId = getFullPath(this._getId(root.schema));
        if (refPath !== baseId) {
            var id = normalizeId(refPath);
            var refVal = this._refs[id];
            if (typeof refVal == 'string') {
                return resolveRecursive.call(this, root, refVal, p);
            }
            else if (refVal instanceof SchemaObject) {
                if (!refVal.validate)
                    this._compile(refVal);
                root = refVal;
            }
            else {
                refVal = this._schemas[id];
                if (refVal instanceof SchemaObject) {
                    if (!refVal.validate)
                        this._compile(refVal);
                    if (id == normalizeId(ref))
                        return { schema: refVal, root: root, baseId: baseId };
                    root = refVal;
                }
                else {
                    return;
                }
            }
            if (!root.schema)
                return;
            baseId = getFullPath(this._getId(root.schema));
        }
        return getJsonPointer.call(this, p, baseId, root.schema, root);
    }
    /* @this Ajv */
    function resolveRecursive(root, ref, parsedRef) {
        /* jshint validthis: true */
        var res = resolveSchema.call(this, root, ref);
        if (res) {
            var schema = res.schema;
            var baseId = res.baseId;
            root = res.root;
            var id = this._getId(schema);
            if (id)
                baseId = resolveUrl(baseId, id);
            return getJsonPointer.call(this, parsedRef, baseId, schema, root);
        }
    }
    var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
    /* @this Ajv */
    function getJsonPointer(parsedRef, baseId, schema, root) {
        /* jshint validthis: true */
        parsedRef.hash = parsedRef.hash || '';
        if (parsedRef.hash.slice(0, 2) != '#/')
            return;
        var parts = parsedRef.hash.split('/');
        for (var i = 1; i < parts.length; i++) {
            var part = parts[i];
            if (part) {
                part = util.unescapeFragment(part);
                schema = schema[part];
                if (schema === undefined)
                    break;
                var id;
                if (!PREVENT_SCOPE_CHANGE[part]) {
                    id = this._getId(schema);
                    if (id)
                        baseId = resolveUrl(baseId, id);
                    if (schema.$ref) {
                        var $ref = resolveUrl(baseId, schema.$ref);
                        var res = resolveSchema.call(this, root, $ref);
                        if (res) {
                            schema = res.schema;
                            root = res.root;
                            baseId = res.baseId;
                        }
                    }
                }
            }
        }
        if (schema !== undefined && schema !== root.schema)
            return { schema: schema, root: root, baseId: baseId };
    }
    var SIMPLE_INLINED = util.toHash([
        'type', 'format', 'pattern',
        'maxLength', 'minLength',
        'maxProperties', 'minProperties',
        'maxItems', 'minItems',
        'maximum', 'minimum',
        'uniqueItems', 'multipleOf',
        'required', 'enum'
    ]);
    function inlineRef(schema, limit) {
        if (limit === false)
            return false;
        if (limit === undefined || limit === true)
            return checkNoRef(schema);
        else if (limit)
            return countKeys(schema) <= limit;
    }
    function checkNoRef(schema) {
        var item;
        if (Array.isArray(schema)) {
            for (var i = 0; i < schema.length; i++) {
                item = schema[i];
                if (typeof item == 'object' && !checkNoRef(item))
                    return false;
            }
        }
        else {
            for (var key in schema) {
                if (key == '$ref')
                    return false;
                item = schema[key];
                if (typeof item == 'object' && !checkNoRef(item))
                    return false;
            }
        }
        return true;
    }
    function countKeys(schema) {
        var count = 0, item;
        if (Array.isArray(schema)) {
            for (var i = 0; i < schema.length; i++) {
                item = schema[i];
                if (typeof item == 'object')
                    count += countKeys(item);
                if (count == Infinity)
                    return Infinity;
            }
        }
        else {
            for (var key in schema) {
                if (key == '$ref')
                    return Infinity;
                if (SIMPLE_INLINED[key]) {
                    count++;
                }
                else {
                    item = schema[key];
                    if (typeof item == 'object')
                        count += countKeys(item) + 1;
                    if (count == Infinity)
                        return Infinity;
                }
            }
        }
        return count;
    }
    function getFullPath(id, normalize) {
        if (normalize !== false)
            id = normalizeId(id);
        var p = url.parse(id, false, true);
        return _getFullPath(p);
    }
    function _getFullPath(p) {
        var protocolSeparator = p.protocol || p.href.slice(0, 2) == '//' ? '//' : '';
        return (p.protocol || '') + protocolSeparator + (p.host || '') + (p.path || '') + '#';
    }
    var TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id) {
        return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
    }
    function resolveUrl(baseId, id) {
        id = normalizeId(id);
        return url.resolve(baseId, id);
    }
    /* @this Ajv */
    function resolveIds(schema) {
        var schemaId = normalizeId(this._getId(schema));
        var baseIds = { '': schemaId };
        var fullPaths = { '': getFullPath(schemaId, false) };
        var localRefs = {};
        var self = this;
        traverse(schema, { allKeys: true }, function (sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
            if (jsonPtr === '')
                return;
            var id = self._getId(sch);
            var baseId = baseIds[parentJsonPtr];
            var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
            if (keyIndex !== undefined)
                fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
            if (typeof id == 'string') {
                id = baseId = normalizeId(baseId ? url.resolve(baseId, id) : id);
                var refVal = self._refs[id];
                if (typeof refVal == 'string')
                    refVal = self._refs[refVal];
                if (refVal && refVal.schema) {
                    if (!equal(sch, refVal.schema))
                        throw new Error('id "' + id + '" resolves to more than one schema');
                }
                else if (id != normalizeId(fullPath)) {
                    if (id[0] == '#') {
                        if (localRefs[id] && !equal(sch, localRefs[id]))
                            throw new Error('id "' + id + '" resolves to more than one schema');
                        localRefs[id] = sch;
                    }
                    else {
                        self._refs[id] = fullPath;
                    }
                }
            }
            baseIds[jsonPtr] = baseId;
            fullPaths[jsonPtr] = fullPath;
        });
        return localRefs;
    }
}
,
/* ajv/lib/compile/rules */ function _(require, module, exports) {
    var ruleModules = require(5) /* ./_rules */, toHash = require(14) /* ./util */.toHash;
    module.exports = function rules() {
        var RULES = [
            { type: 'number',
                rules: [{ 'maximum': ['exclusiveMaximum'] },
                    { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
            { type: 'string',
                rules: ['maxLength', 'minLength', 'pattern', 'format'] },
            { type: 'array',
                rules: ['maxItems', 'minItems', 'uniqueItems', 'contains', 'items'] },
            { type: 'object',
                rules: ['maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
                    { 'properties': ['additionalProperties', 'patternProperties'] }] },
            { rules: ['$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf'] }
        ];
        var ALL = ['type'];
        var KEYWORDS = [
            'additionalItems', '$schema', '$id', 'id', 'title',
            'description', 'default', 'definitions'
        ];
        var TYPES = ['number', 'integer', 'string', 'array', 'object', 'boolean', 'null'];
        RULES.all = toHash(ALL);
        RULES.types = toHash(TYPES);
        RULES.forEach(function (group) {
            group.rules = group.rules.map(function (keyword) {
                var implKeywords;
                if (typeof keyword == 'object') {
                    var key = Object.keys(keyword)[0];
                    implKeywords = keyword[key];
                    keyword = key;
                    implKeywords.forEach(function (k) {
                        ALL.push(k);
                        RULES.all[k] = true;
                    });
                }
                ALL.push(keyword);
                var rule = RULES.all[keyword] = {
                    keyword: keyword,
                    code: ruleModules[keyword],
                    implements: implKeywords
                };
                return rule;
            });
            if (group.type)
                RULES.types[group.type] = group;
        });
        RULES.keywords = toHash(ALL.concat(KEYWORDS));
        RULES.custom = {};
        return RULES;
    };
}
,
/* ajv/lib/compile/schema_obj */ function _(require, module, exports) {
    var util = require(14) /* ./util */;
    module.exports = SchemaObject;
    function SchemaObject(obj) {
        util.copy(obj, this);
    }
}
,
/* ajv/lib/compile/ucs2length */ function _(require, module, exports) {
    // https://mathiasbynens.be/notes/javascript-encoding
    // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
    module.exports = function ucs2length(str) {
        var length = 0, len = str.length, pos = 0, value;
        while (pos < len) {
            length++;
            value = str.charCodeAt(pos++);
            if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
                // high surrogate, and there is a next character
                value = str.charCodeAt(pos);
                if ((value & 0xFC00) == 0xDC00)
                    pos++; // low surrogate
            }
        }
        return length;
    };
}
,
/* ajv/lib/compile/util */ function _(require, module, exports) {
    module.exports = {
        copy: copy,
        checkDataType: checkDataType,
        checkDataTypes: checkDataTypes,
        coerceToTypes: coerceToTypes,
        toHash: toHash,
        getProperty: getProperty,
        escapeQuotes: escapeQuotes,
        equal: require(108) /* fast-deep-equal */,
        ucs2length: require(13) /* ./ucs2length */,
        varOccurences: varOccurences,
        varReplace: varReplace,
        cleanUpCode: cleanUpCode,
        finalCleanUpCode: finalCleanUpCode,
        schemaHasRules: schemaHasRules,
        schemaHasRulesExcept: schemaHasRulesExcept,
        toQuotedString: toQuotedString,
        getPathExpr: getPathExpr,
        getPath: getPath,
        getData: getData,
        unescapeFragment: unescapeFragment,
        unescapeJsonPointer: unescapeJsonPointer,
        escapeFragment: escapeFragment,
        escapeJsonPointer: escapeJsonPointer
    };
    function copy(o, to) {
        to = to || {};
        for (var key in o)
            to[key] = o[key];
        return to;
    }
    function checkDataType(dataType, data, negate) {
        var EQUAL = negate ? ' !== ' : ' === ', AND = negate ? ' || ' : ' && ', OK = negate ? '!' : '', NOT = negate ? '' : '!';
        switch (dataType) {
            case 'null': return data + EQUAL + 'null';
            case 'array': return OK + 'Array.isArray(' + data + ')';
            case 'object': return '(' + OK + data + AND +
                'typeof ' + data + EQUAL + '"object"' + AND +
                NOT + 'Array.isArray(' + data + '))';
            case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
                NOT + '(' + data + ' % 1)' +
                AND + data + EQUAL + data + ')';
            default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
        }
    }
    function checkDataTypes(dataTypes, data) {
        switch (dataTypes.length) {
            case 1: return checkDataType(dataTypes[0], data, true);
            default:
                var code = '';
                var types = toHash(dataTypes);
                if (types.array && types.object) {
                    code = types.null ? '(' : '(!' + data + ' || ';
                    code += 'typeof ' + data + ' !== "object")';
                    delete types.null;
                    delete types.array;
                    delete types.object;
                }
                if (types.number)
                    delete types.integer;
                for (var t in types)
                    code += (code ? ' && ' : '') + checkDataType(t, data, true);
                return code;
        }
    }
    var COERCE_TO_TYPES = toHash(['string', 'number', 'integer', 'boolean', 'null']);
    function coerceToTypes(optionCoerceTypes, dataTypes) {
        if (Array.isArray(dataTypes)) {
            var types = [];
            for (var i = 0; i < dataTypes.length; i++) {
                var t = dataTypes[i];
                if (COERCE_TO_TYPES[t])
                    types[types.length] = t;
                else if (optionCoerceTypes === 'array' && t === 'array')
                    types[types.length] = t;
            }
            if (types.length)
                return types;
        }
        else if (COERCE_TO_TYPES[dataTypes]) {
            return [dataTypes];
        }
        else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
            return ['array'];
        }
    }
    function toHash(arr) {
        var hash = {};
        for (var i = 0; i < arr.length; i++)
            hash[arr[i]] = true;
        return hash;
    }
    var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
    var SINGLE_QUOTE = /'|\\/g;
    function getProperty(key) {
        return typeof key == 'number'
            ? '[' + key + ']'
            : IDENTIFIER.test(key)
                ? '.' + key
                : "['" + escapeQuotes(key) + "']";
    }
    function escapeQuotes(str) {
        return str.replace(SINGLE_QUOTE, '\\$&')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\f/g, '\\f')
            .replace(/\t/g, '\\t');
    }
    function varOccurences(str, dataVar) {
        dataVar += '[^0-9]';
        var matches = str.match(new RegExp(dataVar, 'g'));
        return matches ? matches.length : 0;
    }
    function varReplace(str, dataVar, expr) {
        dataVar += '([^0-9])';
        expr = expr.replace(/\$/g, '$$$$');
        return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
    }
    var EMPTY_ELSE = /else\s*{\s*}/g, EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g, EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
    function cleanUpCode(out) {
        return out.replace(EMPTY_ELSE, '')
            .replace(EMPTY_IF_NO_ELSE, '')
            .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
    }
    var ERRORS_REGEXP = /[^v.]errors/g, REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g, REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g, RETURN_VALID = 'return errors === 0;', RETURN_TRUE = 'validate.errors = null; return true;', RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/, RETURN_DATA_ASYNC = 'return data;', ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g, REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;
    function finalCleanUpCode(out, async) {
        var matches = out.match(ERRORS_REGEXP);
        if (matches && matches.length == 2) {
            out = async
                ? out.replace(REMOVE_ERRORS_ASYNC, '')
                    .replace(RETURN_ASYNC, RETURN_DATA_ASYNC)
                : out.replace(REMOVE_ERRORS, '')
                    .replace(RETURN_VALID, RETURN_TRUE);
        }
        matches = out.match(ROOTDATA_REGEXP);
        if (!matches || matches.length !== 3)
            return out;
        return out.replace(REMOVE_ROOTDATA, '');
    }
    function schemaHasRules(schema, rules) {
        if (typeof schema == 'boolean')
            return !schema;
        for (var key in schema)
            if (rules[key])
                return true;
    }
    function schemaHasRulesExcept(schema, rules, exceptKeyword) {
        if (typeof schema == 'boolean')
            return !schema && exceptKeyword != 'not';
        for (var key in schema)
            if (key != exceptKeyword && rules[key])
                return true;
    }
    function toQuotedString(str) {
        return '\'' + escapeQuotes(str) + '\'';
    }
    function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
        var path = jsonPointers // false by default
            ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
            : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
        return joinPaths(currentPath, path);
    }
    function getPath(currentPath, prop, jsonPointers) {
        var path = jsonPointers // false by default
            ? toQuotedString('/' + escapeJsonPointer(prop))
            : toQuotedString(getProperty(prop));
        return joinPaths(currentPath, path);
    }
    var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
    function getData($data, lvl, paths) {
        var up, jsonPointer, data, matches;
        if ($data === '')
            return 'rootData';
        if ($data[0] == '/') {
            if (!JSON_POINTER.test($data))
                throw new Error('Invalid JSON-pointer: ' + $data);
            jsonPointer = $data;
            data = 'rootData';
        }
        else {
            matches = $data.match(RELATIVE_JSON_POINTER);
            if (!matches)
                throw new Error('Invalid JSON-pointer: ' + $data);
            up = +matches[1];
            jsonPointer = matches[2];
            if (jsonPointer == '#') {
                if (up >= lvl)
                    throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
                return paths[lvl - up];
            }
            if (up > lvl)
                throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
            data = 'data' + ((lvl - up) || '');
            if (!jsonPointer)
                return data;
        }
        var expr = data;
        var segments = jsonPointer.split('/');
        for (var i = 0; i < segments.length; i++) {
            var segment = segments[i];
            if (segment) {
                data += getProperty(unescapeJsonPointer(segment));
                expr += ' && ' + data;
            }
        }
        return expr;
    }
    function joinPaths(a, b) {
        if (a == '""')
            return b;
        return (a + ' + ' + b).replace(/' \+ '/g, '');
    }
    function unescapeFragment(str) {
        return unescapeJsonPointer(decodeURIComponent(str));
    }
    function escapeFragment(str) {
        return encodeURIComponent(escapeJsonPointer(str));
    }
    function escapeJsonPointer(str) {
        return str.replace(/~/g, '~0').replace(/\//g, '~1');
    }
    function unescapeJsonPointer(str) {
        return str.replace(/~1/g, '/').replace(/~0/g, '~');
    }
}
,
/* ajv/lib/dotjs/_limit */ function _(require, module, exports) {
    module.exports = function generate__limit(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $errorKeyword;
        var $data = 'data' + ($dataLvl || '');
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $isMax = $keyword == 'maximum', $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? '<' : '>', $notOp = $isMax ? '>' : '<', $errorKeyword = undefined;
        if ($isDataExcl) {
            var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = 'exclusive' + $lvl, $exclType = 'exclType' + $lvl, $exclIsNumber = 'exclIsNumber' + $lvl, $opExpr = 'op' + $lvl, $opStr = '\' + ' + $opExpr + ' + \'';
            out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
            $schemaValueExcl = 'schemaExcl' + $lvl;
            out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
            var $errorKeyword = $exclusiveKeyword;
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = ''; /* istanbul ignore else */
            if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
                if (it.opts.messages !== false) {
                    out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
                }
                if (it.opts.verbose) {
                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
            }
            else {
                out += ' {} ';
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                    out += ' throw new ValidationError([' + (__err) + ']); ';
                }
                else {
                    out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
            }
            else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
            }
            out += ' } else if ( ';
            if ($isData) {
                out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
            }
            out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
        }
        else {
            var $exclIsNumber = typeof $schemaExcl == 'number', $opStr = $op;
            if ($exclIsNumber && $isData) {
                var $opExpr = '\'' + $opStr + '\'';
                out += ' if ( ';
                if ($isData) {
                    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
                }
                out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
            }
            else {
                if ($exclIsNumber && $schema === undefined) {
                    $exclusive = true;
                    $errorKeyword = $exclusiveKeyword;
                    $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
                    $schemaValue = $schemaExcl;
                    $notOp += '=';
                }
                else {
                    if ($exclIsNumber)
                        $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
                    if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
                        $exclusive = true;
                        $errorKeyword = $exclusiveKeyword;
                        $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
                        $notOp += '=';
                    }
                    else {
                        $exclusive = false;
                        $opStr += '=';
                    }
                }
                var $opExpr = '\'' + $opStr + '\'';
                out += ' if ( ';
                if ($isData) {
                    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
                }
                out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
            }
        }
        $errorKeyword = $errorKeyword || $keyword;
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should be ' + ($opStr) + ' ';
                if ($isData) {
                    out += '\' + ' + ($schemaValue);
                }
                else {
                    out += '' + ($schemaValue) + '\'';
                }
            }
            if (it.opts.verbose) {
                out += ' , schema:  ';
                if ($isData) {
                    out += 'validate.schema' + ($schemaPath);
                }
                else {
                    out += '' + ($schema);
                }
                out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } ';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/_limitItems */ function _(require, module, exports) {
    module.exports = function generate__limitItems(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $errorKeyword;
        var $data = 'data' + ($dataLvl || '');
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $op = $keyword == 'maxItems' ? '>' : '<';
        out += 'if ( ';
        if ($isData) {
            out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
        }
        out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
        var $errorKeyword = $keyword;
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should NOT have ';
                if ($keyword == 'maxItems') {
                    out += 'more';
                }
                else {
                    out += 'less';
                }
                out += ' than ';
                if ($isData) {
                    out += '\' + ' + ($schemaValue) + ' + \'';
                }
                else {
                    out += '' + ($schema);
                }
                out += ' items\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema:  ';
                if ($isData) {
                    out += 'validate.schema' + ($schemaPath);
                }
                else {
                    out += '' + ($schema);
                }
                out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += '} ';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/_limitLength */ function _(require, module, exports) {
    module.exports = function generate__limitLength(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $errorKeyword;
        var $data = 'data' + ($dataLvl || '');
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $op = $keyword == 'maxLength' ? '>' : '<';
        out += 'if ( ';
        if ($isData) {
            out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
        }
        if (it.opts.unicode === false) {
            out += ' ' + ($data) + '.length ';
        }
        else {
            out += ' ucs2length(' + ($data) + ') ';
        }
        out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
        var $errorKeyword = $keyword;
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should NOT be ';
                if ($keyword == 'maxLength') {
                    out += 'longer';
                }
                else {
                    out += 'shorter';
                }
                out += ' than ';
                if ($isData) {
                    out += '\' + ' + ($schemaValue) + ' + \'';
                }
                else {
                    out += '' + ($schema);
                }
                out += ' characters\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema:  ';
                if ($isData) {
                    out += 'validate.schema' + ($schemaPath);
                }
                else {
                    out += '' + ($schema);
                }
                out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += '} ';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/_limitProperties */ function _(require, module, exports) {
    module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $errorKeyword;
        var $data = 'data' + ($dataLvl || '');
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $op = $keyword == 'maxProperties' ? '>' : '<';
        out += 'if ( ';
        if ($isData) {
            out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
        }
        out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
        var $errorKeyword = $keyword;
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should NOT have ';
                if ($keyword == 'maxProperties') {
                    out += 'more';
                }
                else {
                    out += 'less';
                }
                out += ' than ';
                if ($isData) {
                    out += '\' + ' + ($schemaValue) + ' + \'';
                }
                else {
                    out += '' + ($schema);
                }
                out += ' properties\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema:  ';
                if ($isData) {
                    out += 'validate.schema' + ($schemaPath);
                }
                else {
                    out += '' + ($schema);
                }
                out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += '} ';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/allOf */ function _(require, module, exports) {
    module.exports = function generate_allOf(it, $keyword, $ruleType) {
        var out = ' ';
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        var $currentBaseId = $it.baseId, $allSchemasEmpty = true;
        var arr1 = $schema;
        if (arr1) {
            var $sch, $i = -1, l1 = arr1.length - 1;
            while ($i < l1) {
                $sch = arr1[$i += 1];
                if (it.util.schemaHasRules($sch, it.RULES.all)) {
                    $allSchemasEmpty = false;
                    $it.schema = $sch;
                    $it.schemaPath = $schemaPath + '[' + $i + ']';
                    $it.errSchemaPath = $errSchemaPath + '/' + $i;
                    out += '  ' + (it.validate($it)) + ' ';
                    $it.baseId = $currentBaseId;
                    if ($breakOnError) {
                        out += ' if (' + ($nextValid) + ') { ';
                        $closingBraces += '}';
                    }
                }
            }
        }
        if ($breakOnError) {
            if ($allSchemasEmpty) {
                out += ' if (true) { ';
            }
            else {
                out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
            }
        }
        out = it.util.cleanUpCode(out);
        return out;
    };
}
,
/* ajv/lib/dotjs/anyOf */ function _(require, module, exports) {
    module.exports = function generate_anyOf(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        var $noEmptySchema = $schema.every(function ($sch) {
            return it.util.schemaHasRules($sch, it.RULES.all);
        });
        if ($noEmptySchema) {
            var $currentBaseId = $it.baseId;
            out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false;  ';
            var $wasComposite = it.compositeRule;
            it.compositeRule = $it.compositeRule = true;
            var arr1 = $schema;
            if (arr1) {
                var $sch, $i = -1, l1 = arr1.length - 1;
                while ($i < l1) {
                    $sch = arr1[$i += 1];
                    $it.schema = $sch;
                    $it.schemaPath = $schemaPath + '[' + $i + ']';
                    $it.errSchemaPath = $errSchemaPath + '/' + $i;
                    out += '  ' + (it.validate($it)) + ' ';
                    $it.baseId = $currentBaseId;
                    out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
                    $closingBraces += '}';
                }
            }
            it.compositeRule = $it.compositeRule = $wasComposite;
            out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
                if (it.opts.messages !== false) {
                    out += ' , message: \'should match some schema in anyOf\' ';
                }
                if (it.opts.verbose) {
                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
            }
            else {
                out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
            if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                    out += ' throw new ValidationError(vErrors); ';
                }
                else {
                    out += ' validate.errors = vErrors; return false; ';
                }
            }
            out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
            if (it.opts.allErrors) {
                out += ' } ';
            }
            out = it.util.cleanUpCode(out);
        }
        else {
            if ($breakOnError) {
                out += ' if (true) { ';
            }
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/const */ function _(require, module, exports) {
    module.exports = function generate_const(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        if (!$isData) {
            out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
        }
        out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should be equal to constant\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' }';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/contains */ function _(require, module, exports) {
    module.exports = function generate_contains(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all);
        out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
        if ($nonEmptySchema) {
            var $wasComposite = it.compositeRule;
            it.compositeRule = $it.compositeRule = true;
            $it.schema = $schema;
            $it.schemaPath = $schemaPath;
            $it.errSchemaPath = $errSchemaPath;
            out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
            $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
            var $passData = $data + '[' + $idx + ']';
            $it.dataPathArr[$dataNxt] = $idx;
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
                out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
            }
            else {
                out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
            }
            out += ' if (' + ($nextValid) + ') break; }  ';
            it.compositeRule = $it.compositeRule = $wasComposite;
            out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
        }
        else {
            out += ' if (' + ($data) + '.length == 0) {';
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should contain a valid item\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
        if ($nonEmptySchema) {
            out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
        }
        if (it.opts.allErrors) {
            out += ' } ';
        }
        out = it.util.cleanUpCode(out);
        return out;
    };
}
,
/* ajv/lib/dotjs/custom */ function _(require, module, exports) {
    module.exports = function generate_custom(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $errorKeyword;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $errs = 'errs__' + $lvl;
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $rule = this, $definition = 'definition' + $lvl, $rDef = $rule.definition, $closingBraces = '';
        var $compile, $inline, $macro, $ruleValidate, $validateCode;
        if ($isData && $rDef.$data) {
            $validateCode = 'keywordValidate' + $lvl;
            var $validateSchema = $rDef.validateSchema;
            out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
        }
        else {
            $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
            if (!$ruleValidate)
                return;
            $schemaValue = 'validate.schema' + $schemaPath;
            $validateCode = $ruleValidate.code;
            $compile = $rDef.compile;
            $inline = $rDef.inline;
            $macro = $rDef.macro;
        }
        var $ruleErrs = $validateCode + '.errors', $i = 'i' + $lvl, $ruleErr = 'ruleErr' + $lvl, $asyncKeyword = $rDef.async;
        if ($asyncKeyword && !it.async)
            throw new Error('async keyword in sync schema');
        if (!($inline || $macro)) {
            out += '' + ($ruleErrs) + ' = null;';
        }
        out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
        if ($isData && $rDef.$data) {
            $closingBraces += '}';
            out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
            if ($validateSchema) {
                $closingBraces += '}';
                out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
            }
        }
        if ($inline) {
            if ($rDef.statements) {
                out += ' ' + ($ruleValidate.validate) + ' ';
            }
            else {
                out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
            }
        }
        else if ($macro) {
            var $it = it.util.copy(it);
            var $closingBraces = '';
            $it.level++;
            var $nextValid = 'valid' + $it.level;
            $it.schema = $ruleValidate.validate;
            $it.schemaPath = '';
            var $wasComposite = it.compositeRule;
            it.compositeRule = $it.compositeRule = true;
            var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
            it.compositeRule = $it.compositeRule = $wasComposite;
            out += ' ' + ($code);
        }
        else {
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = '';
            out += '  ' + ($validateCode) + '.call( ';
            if (it.opts.passContext) {
                out += 'this';
            }
            else {
                out += 'self';
            }
            if ($compile || $rDef.schema === false) {
                out += ' , ' + ($data) + ' ';
            }
            else {
                out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
            }
            out += ' , (dataPath || \'\')';
            if (it.errorPath != '""') {
                out += ' + ' + (it.errorPath);
            }
            var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
            out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData )  ';
            var def_callRuleValidate = out;
            out = $$outStack.pop();
            if ($rDef.errors === false) {
                out += ' ' + ($valid) + ' = ';
                if ($asyncKeyword) {
                    out += '' + (it.yieldAwait);
                }
                out += '' + (def_callRuleValidate) + '; ';
            }
            else {
                if ($asyncKeyword) {
                    $ruleErrs = 'customErrors' + $lvl;
                    out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
                }
                else {
                    out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
                }
            }
        }
        if ($rDef.modifying) {
            out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
        }
        out += '' + ($closingBraces);
        if ($rDef.valid) {
            if ($breakOnError) {
                out += ' if (true) { ';
            }
        }
        else {
            out += ' if ( ';
            if ($rDef.valid === undefined) {
                out += ' !';
                if ($macro) {
                    out += '' + ($nextValid);
                }
                else {
                    out += '' + ($valid);
                }
            }
            else {
                out += ' ' + (!$rDef.valid) + ' ';
            }
            out += ') { ';
            $errorKeyword = $rule.keyword;
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = '';
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = ''; /* istanbul ignore else */
            if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
                if (it.opts.messages !== false) {
                    out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
                }
                if (it.opts.verbose) {
                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
            }
            else {
                out += ' {} ';
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                    out += ' throw new ValidationError([' + (__err) + ']); ';
                }
                else {
                    out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
            }
            else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
            }
            var def_customError = out;
            out = $$outStack.pop();
            if ($inline) {
                if ($rDef.errors) {
                    if ($rDef.errors != 'full') {
                        out += '  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
                        if (it.opts.verbose) {
                            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
                        }
                        out += ' } ';
                    }
                }
                else {
                    if ($rDef.errors === false) {
                        out += ' ' + (def_customError) + ' ';
                    }
                    else {
                        out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else {  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
                        if (it.opts.verbose) {
                            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
                        }
                        out += ' } } ';
                    }
                }
            }
            else if ($macro) {
                out += '   var err =   '; /* istanbul ignore else */
                if (it.createErrors !== false) {
                    out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
                    if (it.opts.messages !== false) {
                        out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
                    }
                    if (it.opts.verbose) {
                        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                    }
                    out += ' } ';
                }
                else {
                    out += ' {} ';
                }
                out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                    if (it.async) {
                        out += ' throw new ValidationError(vErrors); ';
                    }
                    else {
                        out += ' validate.errors = vErrors; return false; ';
                    }
                }
            }
            else {
                if ($rDef.errors === false) {
                    out += ' ' + (def_customError) + ' ';
                }
                else {
                    out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length;  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + ';  ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '";  ';
                    if (it.opts.verbose) {
                        out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
                    }
                    out += ' } } else { ' + (def_customError) + ' } ';
                }
            }
            out += ' } ';
            if ($breakOnError) {
                out += ' else { ';
            }
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/dependencies */ function _(require, module, exports) {
    module.exports = function generate_dependencies(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties;
        for ($property in $schema) {
            var $sch = $schema[$property];
            var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
            $deps[$property] = $sch;
        }
        out += 'var ' + ($errs) + ' = errors;';
        var $currentErrorPath = it.errorPath;
        out += 'var missing' + ($lvl) + ';';
        for (var $property in $propertyDeps) {
            $deps = $propertyDeps[$property];
            if ($deps.length) {
                out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
                if ($ownProperties) {
                    out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
                }
                if ($breakOnError) {
                    out += ' && ( ';
                    var arr1 = $deps;
                    if (arr1) {
                        var $propertyKey, $i = -1, l1 = arr1.length - 1;
                        while ($i < l1) {
                            $propertyKey = arr1[$i += 1];
                            if ($i) {
                                out += ' || ';
                            }
                            var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
                            out += ' ( ( ' + ($useData) + ' === undefined ';
                            if ($ownProperties) {
                                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                            }
                            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
                        }
                    }
                    out += ')) {  ';
                    var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \'';
                    if (it.opts._errorDataPathProperty) {
                        it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
                    }
                    var $$outStack = $$outStack || [];
                    $$outStack.push(out);
                    out = ''; /* istanbul ignore else */
                    if (it.createErrors !== false) {
                        out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
                        if (it.opts.messages !== false) {
                            out += ' , message: \'should have ';
                            if ($deps.length == 1) {
                                out += 'property ' + (it.util.escapeQuotes($deps[0]));
                            }
                            else {
                                out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
                            }
                            out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
                        }
                        if (it.opts.verbose) {
                            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                        }
                        out += ' } ';
                    }
                    else {
                        out += ' {} ';
                    }
                    var __err = out;
                    out = $$outStack.pop();
                    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                        if (it.async) {
                            out += ' throw new ValidationError([' + (__err) + ']); ';
                        }
                        else {
                            out += ' validate.errors = [' + (__err) + ']; return false; ';
                        }
                    }
                    else {
                        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                    }
                }
                else {
                    out += ' ) { ';
                    var arr2 = $deps;
                    if (arr2) {
                        var $propertyKey, i2 = -1, l2 = arr2.length - 1;
                        while (i2 < l2) {
                            $propertyKey = arr2[i2 += 1];
                            var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
                            if (it.opts._errorDataPathProperty) {
                                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
                            }
                            out += ' if ( ' + ($useData) + ' === undefined ';
                            if ($ownProperties) {
                                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                            }
                            out += ') {  var err =   '; /* istanbul ignore else */
                            if (it.createErrors !== false) {
                                out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
                                if (it.opts.messages !== false) {
                                    out += ' , message: \'should have ';
                                    if ($deps.length == 1) {
                                        out += 'property ' + (it.util.escapeQuotes($deps[0]));
                                    }
                                    else {
                                        out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
                                    }
                                    out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
                                }
                                if (it.opts.verbose) {
                                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                                }
                                out += ' } ';
                            }
                            else {
                                out += ' {} ';
                            }
                            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
                        }
                    }
                }
                out += ' }   ';
                if ($breakOnError) {
                    $closingBraces += '}';
                    out += ' else { ';
                }
            }
        }
        it.errorPath = $currentErrorPath;
        var $currentBaseId = $it.baseId;
        for (var $property in $schemaDeps) {
            var $sch = $schemaDeps[$property];
            if (it.util.schemaHasRules($sch, it.RULES.all)) {
                out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
                if ($ownProperties) {
                    out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
                }
                out += ') { ';
                $it.schema = $sch;
                $it.schemaPath = $schemaPath + it.util.getProperty($property);
                $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
                out += '  ' + (it.validate($it)) + ' ';
                $it.baseId = $currentBaseId;
                out += ' }  ';
                if ($breakOnError) {
                    out += ' if (' + ($nextValid) + ') { ';
                    $closingBraces += '}';
                }
            }
        }
        if ($breakOnError) {
            out += '   ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
        }
        out = it.util.cleanUpCode(out);
        return out;
    };
}
,
/* ajv/lib/dotjs/enum */ function _(require, module, exports) {
    module.exports = function generate_enum(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $i = 'i' + $lvl, $vSchema = 'schema' + $lvl;
        if (!$isData) {
            out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
        }
        out += 'var ' + ($valid) + ';';
        if ($isData) {
            out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
        }
        out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
        if ($isData) {
            out += '  }  ';
        }
        out += ' if (!' + ($valid) + ') {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should be equal to one of the allowed values\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' }';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/format */ function _(require, module, exports) {
    module.exports = function generate_format(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        if (it.opts.format === false) {
            if ($breakOnError) {
                out += ' if (true) { ';
            }
            return out;
        }
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats);
        if ($isData) {
            var $format = 'format' + $lvl, $isObject = 'isObject' + $lvl, $formatType = 'formatType' + $lvl;
            out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
            if (it.async) {
                out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
            }
            out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if (  ';
            if ($isData) {
                out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
            }
            out += ' (';
            if ($unknownFormats != 'ignore') {
                out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
                if ($allowUnknown) {
                    out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
                }
                out += ') || ';
            }
            out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
            if (it.async) {
                out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
            }
            else {
                out += ' ' + ($format) + '(' + ($data) + ') ';
            }
            out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
        }
        else {
            var $format = it.formats[$schema];
            if (!$format) {
                if ($unknownFormats == 'ignore') {
                    it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
                    if ($breakOnError) {
                        out += ' if (true) { ';
                    }
                    return out;
                }
                else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
                    if ($breakOnError) {
                        out += ' if (true) { ';
                    }
                    return out;
                }
                else {
                    throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
                }
            }
            var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
            var $formatType = $isObject && $format.type || 'string';
            if ($isObject) {
                var $async = $format.async === true;
                $format = $format.validate;
            }
            if ($formatType != $ruleType) {
                if ($breakOnError) {
                    out += ' if (true) { ';
                }
                return out;
            }
            if ($async) {
                if (!it.async)
                    throw new Error('async format in sync schema');
                var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
                out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { ';
            }
            else {
                out += ' if (! ';
                var $formatRef = 'formats' + it.util.getProperty($schema);
                if ($isObject)
                    $formatRef += '.validate';
                if (typeof $format == 'function') {
                    out += ' ' + ($formatRef) + '(' + ($data) + ') ';
                }
                else {
                    out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
                }
                out += ') { ';
            }
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format:  ';
            if ($isData) {
                out += '' + ($schemaValue);
            }
            else {
                out += '' + (it.util.toQuotedString($schema));
            }
            out += '  } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should match format "';
                if ($isData) {
                    out += '\' + ' + ($schemaValue) + ' + \'';
                }
                else {
                    out += '' + (it.util.escapeQuotes($schema));
                }
                out += '"\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema:  ';
                if ($isData) {
                    out += 'validate.schema' + ($schemaPath);
                }
                else {
                    out += '' + (it.util.toQuotedString($schema));
                }
                out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } ';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/items */ function _(require, module, exports) {
    module.exports = function generate_items(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId;
        out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
        if (Array.isArray($schema)) {
            var $additionalItems = it.schema.additionalItems;
            if ($additionalItems === false) {
                out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
                var $currErrSchemaPath = $errSchemaPath;
                $errSchemaPath = it.errSchemaPath + '/additionalItems';
                out += '  if (!' + ($valid) + ') {   ';
                var $$outStack = $$outStack || [];
                $$outStack.push(out);
                out = ''; /* istanbul ignore else */
                if (it.createErrors !== false) {
                    out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
                    if (it.opts.messages !== false) {
                        out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
                    }
                    if (it.opts.verbose) {
                        out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                    }
                    out += ' } ';
                }
                else {
                    out += ' {} ';
                }
                var __err = out;
                out = $$outStack.pop();
                if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                    if (it.async) {
                        out += ' throw new ValidationError([' + (__err) + ']); ';
                    }
                    else {
                        out += ' validate.errors = [' + (__err) + ']; return false; ';
                    }
                }
                else {
                    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                }
                out += ' } ';
                $errSchemaPath = $currErrSchemaPath;
                if ($breakOnError) {
                    $closingBraces += '}';
                    out += ' else { ';
                }
            }
            var arr1 = $schema;
            if (arr1) {
                var $sch, $i = -1, l1 = arr1.length - 1;
                while ($i < l1) {
                    $sch = arr1[$i += 1];
                    if (it.util.schemaHasRules($sch, it.RULES.all)) {
                        out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
                        var $passData = $data + '[' + $i + ']';
                        $it.schema = $sch;
                        $it.schemaPath = $schemaPath + '[' + $i + ']';
                        $it.errSchemaPath = $errSchemaPath + '/' + $i;
                        $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
                        $it.dataPathArr[$dataNxt] = $i;
                        var $code = it.validate($it);
                        $it.baseId = $currentBaseId;
                        if (it.util.varOccurences($code, $nextData) < 2) {
                            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
                        }
                        else {
                            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
                        }
                        out += ' }  ';
                        if ($breakOnError) {
                            out += ' if (' + ($nextValid) + ') { ';
                            $closingBraces += '}';
                        }
                    }
                }
            }
            if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
                $it.schema = $additionalItems;
                $it.schemaPath = it.schemaPath + '.additionalItems';
                $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
                out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') {  for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
                $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
                var $passData = $data + '[' + $idx + ']';
                $it.dataPathArr[$dataNxt] = $idx;
                var $code = it.validate($it);
                $it.baseId = $currentBaseId;
                if (it.util.varOccurences($code, $nextData) < 2) {
                    out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
                }
                else {
                    out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
                }
                if ($breakOnError) {
                    out += ' if (!' + ($nextValid) + ') break; ';
                }
                out += ' } }  ';
                if ($breakOnError) {
                    out += ' if (' + ($nextValid) + ') { ';
                    $closingBraces += '}';
                }
            }
        }
        else if (it.util.schemaHasRules($schema, it.RULES.all)) {
            $it.schema = $schema;
            $it.schemaPath = $schemaPath;
            $it.errSchemaPath = $errSchemaPath;
            out += '  for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
            $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
            var $passData = $data + '[' + $idx + ']';
            $it.dataPathArr[$dataNxt] = $idx;
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
                out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
            }
            else {
                out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
            }
            if ($breakOnError) {
                out += ' if (!' + ($nextValid) + ') break; ';
            }
            out += ' }';
        }
        if ($breakOnError) {
            out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
        }
        out = it.util.cleanUpCode(out);
        return out;
    };
}
,
/* ajv/lib/dotjs/multipleOf */ function _(require, module, exports) {
    module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        out += 'var division' + ($lvl) + ';if (';
        if ($isData) {
            out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
        }
        out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
        if (it.opts.multipleOfPrecision) {
            out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
        }
        else {
            out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
        }
        out += ' ) ';
        if ($isData) {
            out += '  )  ';
        }
        out += ' ) {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should be multiple of ';
                if ($isData) {
                    out += '\' + ' + ($schemaValue);
                }
                else {
                    out += '' + ($schemaValue) + '\'';
                }
            }
            if (it.opts.verbose) {
                out += ' , schema:  ';
                if ($isData) {
                    out += 'validate.schema' + ($schemaPath);
                }
                else {
                    out += '' + ($schema);
                }
                out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += '} ';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/not */ function _(require, module, exports) {
    module.exports = function generate_not(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        if (it.util.schemaHasRules($schema, it.RULES.all)) {
            $it.schema = $schema;
            $it.schemaPath = $schemaPath;
            $it.errSchemaPath = $errSchemaPath;
            out += ' var ' + ($errs) + ' = errors;  ';
            var $wasComposite = it.compositeRule;
            it.compositeRule = $it.compositeRule = true;
            $it.createErrors = false;
            var $allErrorsOption;
            if ($it.opts.allErrors) {
                $allErrorsOption = $it.opts.allErrors;
                $it.opts.allErrors = false;
            }
            out += ' ' + (it.validate($it)) + ' ';
            $it.createErrors = true;
            if ($allErrorsOption)
                $it.opts.allErrors = $allErrorsOption;
            it.compositeRule = $it.compositeRule = $wasComposite;
            out += ' if (' + ($nextValid) + ') {   ';
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = ''; /* istanbul ignore else */
            if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
                if (it.opts.messages !== false) {
                    out += ' , message: \'should NOT be valid\' ';
                }
                if (it.opts.verbose) {
                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
            }
            else {
                out += ' {} ';
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                    out += ' throw new ValidationError([' + (__err) + ']); ';
                }
                else {
                    out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
            }
            else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
            }
            out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
            if (it.opts.allErrors) {
                out += ' } ';
            }
        }
        else {
            out += '  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
                if (it.opts.messages !== false) {
                    out += ' , message: \'should NOT be valid\' ';
                }
                if (it.opts.verbose) {
                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
            }
            else {
                out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
            if ($breakOnError) {
                out += ' if (false) { ';
            }
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/oneOf */ function _(require, module, exports) {
    module.exports = function generate_oneOf(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;';
        var $currentBaseId = $it.baseId;
        var $wasComposite = it.compositeRule;
        it.compositeRule = $it.compositeRule = true;
        var arr1 = $schema;
        if (arr1) {
            var $sch, $i = -1, l1 = arr1.length - 1;
            while ($i < l1) {
                $sch = arr1[$i += 1];
                if (it.util.schemaHasRules($sch, it.RULES.all)) {
                    $it.schema = $sch;
                    $it.schemaPath = $schemaPath + '[' + $i + ']';
                    $it.errSchemaPath = $errSchemaPath + '/' + $i;
                    out += '  ' + (it.validate($it)) + ' ';
                    $it.baseId = $currentBaseId;
                }
                else {
                    out += ' var ' + ($nextValid) + ' = true; ';
                }
                if ($i) {
                    out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { ';
                    $closingBraces += '}';
                }
                out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;';
            }
        }
        it.compositeRule = $it.compositeRule = $wasComposite;
        out += '' + ($closingBraces) + 'if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should match exactly one schema in oneOf\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError(vErrors); ';
            }
            else {
                out += ' validate.errors = vErrors; return false; ';
            }
        }
        out += '} else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
        if (it.opts.allErrors) {
            out += ' } ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/pattern */ function _(require, module, exports) {
    module.exports = function generate_pattern(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
        out += 'if ( ';
        if ($isData) {
            out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
        }
        out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern:  ';
            if ($isData) {
                out += '' + ($schemaValue);
            }
            else {
                out += '' + (it.util.toQuotedString($schema));
            }
            out += '  } ';
            if (it.opts.messages !== false) {
                out += ' , message: \'should match pattern "';
                if ($isData) {
                    out += '\' + ' + ($schemaValue) + ' + \'';
                }
                else {
                    out += '' + (it.util.escapeQuotes($schema));
                }
                out += '"\' ';
            }
            if (it.opts.verbose) {
                out += ' , schema:  ';
                if ($isData) {
                    out += 'validate.schema' + ($schemaPath);
                }
                else {
                    out += '' + (it.util.toQuotedString($schema));
                }
                out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
        }
        else {
            out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
                out += ' throw new ValidationError([' + (__err) + ']); ';
            }
            else {
                out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
        }
        else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += '} ';
        if ($breakOnError) {
            out += ' else { ';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/properties */ function _(require, module, exports) {
    module.exports = function generate_properties(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl;
        var $schemaKeys = Object.keys($schema || {}), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
        var $required = it.schema.required;
        if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired)
            var $requiredHash = it.util.toHash($required);
        if (it.opts.patternGroups) {
            var $pgProperties = it.schema.patternGroups || {}, $pgPropertyKeys = Object.keys($pgProperties);
        }
        out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
        if ($ownProperties) {
            out += ' var ' + ($dataProperties) + ' = undefined;';
        }
        if ($checkAdditional) {
            if ($ownProperties) {
                out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
            }
            else {
                out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
            }
            if ($someProperties) {
                out += ' var isAdditional' + ($lvl) + ' = !(false ';
                if ($schemaKeys.length) {
                    if ($schemaKeys.length > 5) {
                        out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] ';
                    }
                    else {
                        var arr1 = $schemaKeys;
                        if (arr1) {
                            var $propertyKey, i1 = -1, l1 = arr1.length - 1;
                            while (i1 < l1) {
                                $propertyKey = arr1[i1 += 1];
                                out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
                            }
                        }
                    }
                }
                if ($pPropertyKeys.length) {
                    var arr2 = $pPropertyKeys;
                    if (arr2) {
                        var $pProperty, $i = -1, l2 = arr2.length - 1;
                        while ($i < l2) {
                            $pProperty = arr2[$i += 1];
                            out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
                        }
                    }
                }
                if (it.opts.patternGroups && $pgPropertyKeys.length) {
                    var arr3 = $pgPropertyKeys;
                    if (arr3) {
                        var $pgProperty, $i = -1, l3 = arr3.length - 1;
                        while ($i < l3) {
                            $pgProperty = arr3[$i += 1];
                            out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') ';
                        }
                    }
                }
                out += ' ); if (isAdditional' + ($lvl) + ') { ';
            }
            if ($removeAdditional == 'all') {
                out += ' delete ' + ($data) + '[' + ($key) + ']; ';
            }
            else {
                var $currentErrorPath = it.errorPath;
                var $additionalProperty = '\' + ' + $key + ' + \'';
                if (it.opts._errorDataPathProperty) {
                    it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
                }
                if ($noAdditional) {
                    if ($removeAdditional) {
                        out += ' delete ' + ($data) + '[' + ($key) + ']; ';
                    }
                    else {
                        out += ' ' + ($nextValid) + ' = false; ';
                        var $currErrSchemaPath = $errSchemaPath;
                        $errSchemaPath = it.errSchemaPath + '/additionalProperties';
                        var $$outStack = $$outStack || [];
                        $$outStack.push(out);
                        out = ''; /* istanbul ignore else */
                        if (it.createErrors !== false) {
                            out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
                            if (it.opts.messages !== false) {
                                out += ' , message: \'should NOT have additional properties\' ';
                            }
                            if (it.opts.verbose) {
                                out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                            }
                            out += ' } ';
                        }
                        else {
                            out += ' {} ';
                        }
                        var __err = out;
                        out = $$outStack.pop();
                        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                            if (it.async) {
                                out += ' throw new ValidationError([' + (__err) + ']); ';
                            }
                            else {
                                out += ' validate.errors = [' + (__err) + ']; return false; ';
                            }
                        }
                        else {
                            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                        }
                        $errSchemaPath = $currErrSchemaPath;
                        if ($breakOnError) {
                            out += ' break; ';
                        }
                    }
                }
                else if ($additionalIsSchema) {
                    if ($removeAdditional == 'failing') {
                        out += ' var ' + ($errs) + ' = errors;  ';
                        var $wasComposite = it.compositeRule;
                        it.compositeRule = $it.compositeRule = true;
                        $it.schema = $aProperties;
                        $it.schemaPath = it.schemaPath + '.additionalProperties';
                        $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
                        $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
                        var $passData = $data + '[' + $key + ']';
                        $it.dataPathArr[$dataNxt] = $key;
                        var $code = it.validate($it);
                        $it.baseId = $currentBaseId;
                        if (it.util.varOccurences($code, $nextData) < 2) {
                            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
                        }
                        else {
                            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
                        }
                        out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; }  ';
                        it.compositeRule = $it.compositeRule = $wasComposite;
                    }
                    else {
                        $it.schema = $aProperties;
                        $it.schemaPath = it.schemaPath + '.additionalProperties';
                        $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
                        $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
                        var $passData = $data + '[' + $key + ']';
                        $it.dataPathArr[$dataNxt] = $key;
                        var $code = it.validate($it);
                        $it.baseId = $currentBaseId;
                        if (it.util.varOccurences($code, $nextData) < 2) {
                            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
                        }
                        else {
                            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
                        }
                        if ($breakOnError) {
                            out += ' if (!' + ($nextValid) + ') break; ';
                        }
                    }
                }
                it.errorPath = $currentErrorPath;
            }
            if ($someProperties) {
                out += ' } ';
            }
            out += ' }  ';
            if ($breakOnError) {
                out += ' if (' + ($nextValid) + ') { ';
                $closingBraces += '}';
            }
        }
        var $useDefaults = it.opts.useDefaults && !it.compositeRule;
        if ($schemaKeys.length) {
            var arr4 = $schemaKeys;
            if (arr4) {
                var $propertyKey, i4 = -1, l4 = arr4.length - 1;
                while (i4 < l4) {
                    $propertyKey = arr4[i4 += 1];
                    var $sch = $schema[$propertyKey];
                    if (it.util.schemaHasRules($sch, it.RULES.all)) {
                        var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== undefined;
                        $it.schema = $sch;
                        $it.schemaPath = $schemaPath + $prop;
                        $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
                        $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
                        $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
                        var $code = it.validate($it);
                        $it.baseId = $currentBaseId;
                        if (it.util.varOccurences($code, $nextData) < 2) {
                            $code = it.util.varReplace($code, $nextData, $passData);
                            var $useData = $passData;
                        }
                        else {
                            var $useData = $nextData;
                            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
                        }
                        if ($hasDefault) {
                            out += ' ' + ($code) + ' ';
                        }
                        else {
                            if ($requiredHash && $requiredHash[$propertyKey]) {
                                out += ' if ( ' + ($useData) + ' === undefined ';
                                if ($ownProperties) {
                                    out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                                }
                                out += ') { ' + ($nextValid) + ' = false; ';
                                var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey);
                                if (it.opts._errorDataPathProperty) {
                                    it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
                                }
                                $errSchemaPath = it.errSchemaPath + '/required';
                                var $$outStack = $$outStack || [];
                                $$outStack.push(out);
                                out = ''; /* istanbul ignore else */
                                if (it.createErrors !== false) {
                                    out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                                    if (it.opts.messages !== false) {
                                        out += ' , message: \'';
                                        if (it.opts._errorDataPathProperty) {
                                            out += 'is a required property';
                                        }
                                        else {
                                            out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                                        }
                                        out += '\' ';
                                    }
                                    if (it.opts.verbose) {
                                        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                                    }
                                    out += ' } ';
                                }
                                else {
                                    out += ' {} ';
                                }
                                var __err = out;
                                out = $$outStack.pop();
                                if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                                    if (it.async) {
                                        out += ' throw new ValidationError([' + (__err) + ']); ';
                                    }
                                    else {
                                        out += ' validate.errors = [' + (__err) + ']; return false; ';
                                    }
                                }
                                else {
                                    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                                }
                                $errSchemaPath = $currErrSchemaPath;
                                it.errorPath = $currentErrorPath;
                                out += ' } else { ';
                            }
                            else {
                                if ($breakOnError) {
                                    out += ' if ( ' + ($useData) + ' === undefined ';
                                    if ($ownProperties) {
                                        out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                                    }
                                    out += ') { ' + ($nextValid) + ' = true; } else { ';
                                }
                                else {
                                    out += ' if (' + ($useData) + ' !== undefined ';
                                    if ($ownProperties) {
                                        out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                                    }
                                    out += ' ) { ';
                                }
                            }
                            out += ' ' + ($code) + ' } ';
                        }
                    }
                    if ($breakOnError) {
                        out += ' if (' + ($nextValid) + ') { ';
                        $closingBraces += '}';
                    }
                }
            }
        }
        if ($pPropertyKeys.length) {
            var arr5 = $pPropertyKeys;
            if (arr5) {
                var $pProperty, i5 = -1, l5 = arr5.length - 1;
                while (i5 < l5) {
                    $pProperty = arr5[i5 += 1];
                    var $sch = $pProperties[$pProperty];
                    if (it.util.schemaHasRules($sch, it.RULES.all)) {
                        $it.schema = $sch;
                        $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
                        $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
                        if ($ownProperties) {
                            out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
                        }
                        else {
                            out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
                        }
                        out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
                        $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
                        var $passData = $data + '[' + $key + ']';
                        $it.dataPathArr[$dataNxt] = $key;
                        var $code = it.validate($it);
                        $it.baseId = $currentBaseId;
                        if (it.util.varOccurences($code, $nextData) < 2) {
                            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
                        }
                        else {
                            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
                        }
                        if ($breakOnError) {
                            out += ' if (!' + ($nextValid) + ') break; ';
                        }
                        out += ' } ';
                        if ($breakOnError) {
                            out += ' else ' + ($nextValid) + ' = true; ';
                        }
                        out += ' }  ';
                        if ($breakOnError) {
                            out += ' if (' + ($nextValid) + ') { ';
                            $closingBraces += '}';
                        }
                    }
                }
            }
        }
        if (it.opts.patternGroups && $pgPropertyKeys.length) {
            var arr6 = $pgPropertyKeys;
            if (arr6) {
                var $pgProperty, i6 = -1, l6 = arr6.length - 1;
                while (i6 < l6) {
                    $pgProperty = arr6[i6 += 1];
                    var $pgSchema = $pgProperties[$pgProperty], $sch = $pgSchema.schema;
                    if (it.util.schemaHasRules($sch, it.RULES.all)) {
                        $it.schema = $sch;
                        $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema';
                        $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema';
                        out += ' var pgPropCount' + ($lvl) + ' = 0;  ';
                        if ($ownProperties) {
                            out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
                        }
                        else {
                            out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
                        }
                        out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; ';
                        $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
                        var $passData = $data + '[' + $key + ']';
                        $it.dataPathArr[$dataNxt] = $key;
                        var $code = it.validate($it);
                        $it.baseId = $currentBaseId;
                        if (it.util.varOccurences($code, $nextData) < 2) {
                            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
                        }
                        else {
                            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
                        }
                        if ($breakOnError) {
                            out += ' if (!' + ($nextValid) + ') break; ';
                        }
                        out += ' } ';
                        if ($breakOnError) {
                            out += ' else ' + ($nextValid) + ' = true; ';
                        }
                        out += ' }  ';
                        if ($breakOnError) {
                            out += ' if (' + ($nextValid) + ') { ';
                            $closingBraces += '}';
                        }
                        var $pgMin = $pgSchema.minimum, $pgMax = $pgSchema.maximum;
                        if ($pgMin !== undefined || $pgMax !== undefined) {
                            out += ' var ' + ($valid) + ' = true; ';
                            var $currErrSchemaPath = $errSchemaPath;
                            if ($pgMin !== undefined) {
                                var $limit = $pgMin, $reason = 'minimum', $moreOrLess = 'less';
                                out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; ';
                                $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum';
                                out += '  if (!' + ($valid) + ') {   ';
                                var $$outStack = $$outStack || [];
                                $$outStack.push(out);
                                out = ''; /* istanbul ignore else */
                                if (it.createErrors !== false) {
                                    out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
                                    if (it.opts.messages !== false) {
                                        out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
                                    }
                                    if (it.opts.verbose) {
                                        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                                    }
                                    out += ' } ';
                                }
                                else {
                                    out += ' {} ';
                                }
                                var __err = out;
                                out = $$outStack.pop();
                                if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                                    if (it.async) {
                                        out += ' throw new ValidationError([' + (__err) + ']); ';
                                    }
                                    else {
                                        out += ' validate.errors = [' + (__err) + ']; return false; ';
                                    }
                                }
                                else {
                                    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                                }
                                out += ' } ';
                                if ($pgMax !== undefined) {
                                    out += ' else ';
                                }
                            }
                            if ($pgMax !== undefined) {
                                var $limit = $pgMax, $reason = 'maximum', $moreOrLess = 'more';
                                out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; ';
                                $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum';
                                out += '  if (!' + ($valid) + ') {   ';
                                var $$outStack = $$outStack || [];
                                $$outStack.push(out);
                                out = ''; /* istanbul ignore else */
                                if (it.createErrors !== false) {
                                    out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
                                    if (it.opts.messages !== false) {
                                        out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
                                    }
                                    if (it.opts.verbose) {
                                        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                                    }
                                    out += ' } ';
                                }
                                else {
                                    out += ' {} ';
                                }
                                var __err = out;
                                out = $$outStack.pop();
                                if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                                    if (it.async) {
                                        out += ' throw new ValidationError([' + (__err) + ']); ';
                                    }
                                    else {
                                        out += ' validate.errors = [' + (__err) + ']; return false; ';
                                    }
                                }
                                else {
                                    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                                }
                                out += ' } ';
                            }
                            $errSchemaPath = $currErrSchemaPath;
                            if ($breakOnError) {
                                out += ' if (' + ($valid) + ') { ';
                                $closingBraces += '}';
                            }
                        }
                    }
                }
            }
        }
        if ($breakOnError) {
            out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
        }
        out = it.util.cleanUpCode(out);
        return out;
    };
}
,
/* ajv/lib/dotjs/propertyNames */ function _(require, module, exports) {
    module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $errs = 'errs__' + $lvl;
        var $it = it.util.copy(it);
        var $closingBraces = '';
        $it.level++;
        var $nextValid = 'valid' + $it.level;
        if (it.util.schemaHasRules($schema, it.RULES.all)) {
            $it.schema = $schema;
            $it.schemaPath = $schemaPath;
            $it.errSchemaPath = $errSchemaPath;
            var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $i = 'i' + $lvl, $invalidName = '\' + ' + $key + ' + \'', $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
            out += ' var ' + ($errs) + ' = errors; ';
            if ($ownProperties) {
                out += ' var ' + ($dataProperties) + ' = undefined; ';
            }
            if ($ownProperties) {
                out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
            }
            else {
                out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
            }
            out += ' var startErrs' + ($lvl) + ' = errors; ';
            var $passData = $key;
            var $wasComposite = it.compositeRule;
            it.compositeRule = $it.compositeRule = true;
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
                out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
            }
            else {
                out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
            }
            it.compositeRule = $it.compositeRule = $wasComposite;
            out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; }   var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
                if (it.opts.messages !== false) {
                    out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
                }
                if (it.opts.verbose) {
                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
            }
            else {
                out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
            if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                    out += ' throw new ValidationError(vErrors); ';
                }
                else {
                    out += ' validate.errors = vErrors; return false; ';
                }
            }
            if ($breakOnError) {
                out += ' break; ';
            }
            out += ' } }';
        }
        if ($breakOnError) {
            out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
        }
        out = it.util.cleanUpCode(out);
        return out;
    };
}
,
/* ajv/lib/dotjs/ref */ function _(require, module, exports) {
    module.exports = function generate_ref(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $async, $refCode;
        if ($schema == '#' || $schema == '#/') {
            if (it.isRoot) {
                $async = it.async;
                $refCode = 'validate';
            }
            else {
                $async = it.root.schema.$async === true;
                $refCode = 'root.refVal[0]';
            }
        }
        else {
            var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
            if ($refVal === undefined) {
                var $message = it.MissingRefError.message(it.baseId, $schema);
                if (it.opts.missingRefs == 'fail') {
                    it.logger.error($message);
                    var $$outStack = $$outStack || [];
                    $$outStack.push(out);
                    out = ''; /* istanbul ignore else */
                    if (it.createErrors !== false) {
                        out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
                        if (it.opts.messages !== false) {
                            out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
                        }
                        if (it.opts.verbose) {
                            out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                        }
                        out += ' } ';
                    }
                    else {
                        out += ' {} ';
                    }
                    var __err = out;
                    out = $$outStack.pop();
                    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                        if (it.async) {
                            out += ' throw new ValidationError([' + (__err) + ']); ';
                        }
                        else {
                            out += ' validate.errors = [' + (__err) + ']; return false; ';
                        }
                    }
                    else {
                        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                    }
                    if ($breakOnError) {
                        out += ' if (false) { ';
                    }
                }
                else if (it.opts.missingRefs == 'ignore') {
                    it.logger.warn($message);
                    if ($breakOnError) {
                        out += ' if (true) { ';
                    }
                }
                else {
                    throw new it.MissingRefError(it.baseId, $schema, $message);
                }
            }
            else if ($refVal.inline) {
                var $it = it.util.copy(it);
                $it.level++;
                var $nextValid = 'valid' + $it.level;
                $it.schema = $refVal.schema;
                $it.schemaPath = '';
                $it.errSchemaPath = $schema;
                var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
                out += ' ' + ($code) + ' ';
                if ($breakOnError) {
                    out += ' if (' + ($nextValid) + ') { ';
                }
            }
            else {
                $async = $refVal.$async === true;
                $refCode = $refVal.code;
            }
        }
        if ($refCode) {
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = '';
            if (it.opts.passContext) {
                out += ' ' + ($refCode) + '.call(this, ';
            }
            else {
                out += ' ' + ($refCode) + '( ';
            }
            out += ' ' + ($data) + ', (dataPath || \'\')';
            if (it.errorPath != '""') {
                out += ' + ' + (it.errorPath);
            }
            var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
            out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData)  ';
            var __callValidate = out;
            out = $$outStack.pop();
            if ($async) {
                if (!it.async)
                    throw new Error('async schema referenced by sync schema');
                if ($breakOnError) {
                    out += ' var ' + ($valid) + '; ';
                }
                out += ' try { ' + (it.yieldAwait) + ' ' + (__callValidate) + '; ';
                if ($breakOnError) {
                    out += ' ' + ($valid) + ' = true; ';
                }
                out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
                if ($breakOnError) {
                    out += ' ' + ($valid) + ' = false; ';
                }
                out += ' } ';
                if ($breakOnError) {
                    out += ' if (' + ($valid) + ') { ';
                }
            }
            else {
                out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
                if ($breakOnError) {
                    out += ' else { ';
                }
            }
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/required */ function _(require, module, exports) {
    module.exports = function generate_required(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        var $vSchema = 'schema' + $lvl;
        if (!$isData) {
            if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
                var $required = [];
                var arr1 = $schema;
                if (arr1) {
                    var $property, i1 = -1, l1 = arr1.length - 1;
                    while (i1 < l1) {
                        $property = arr1[i1 += 1];
                        var $propertySch = it.schema.properties[$property];
                        if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
                            $required[$required.length] = $property;
                        }
                    }
                }
            }
            else {
                var $required = $schema;
            }
        }
        if ($isData || $required.length) {
            var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties;
            if ($breakOnError) {
                out += ' var missing' + ($lvl) + '; ';
                if ($loopRequired) {
                    if (!$isData) {
                        out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
                    }
                    var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \'';
                    if (it.opts._errorDataPathProperty) {
                        it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
                    }
                    out += ' var ' + ($valid) + ' = true; ';
                    if ($isData) {
                        out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
                    }
                    out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
                    if ($ownProperties) {
                        out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
                    }
                    out += '; if (!' + ($valid) + ') break; } ';
                    if ($isData) {
                        out += '  }  ';
                    }
                    out += '  if (!' + ($valid) + ') {   ';
                    var $$outStack = $$outStack || [];
                    $$outStack.push(out);
                    out = ''; /* istanbul ignore else */
                    if (it.createErrors !== false) {
                        out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                        if (it.opts.messages !== false) {
                            out += ' , message: \'';
                            if (it.opts._errorDataPathProperty) {
                                out += 'is a required property';
                            }
                            else {
                                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                            }
                            out += '\' ';
                        }
                        if (it.opts.verbose) {
                            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                        }
                        out += ' } ';
                    }
                    else {
                        out += ' {} ';
                    }
                    var __err = out;
                    out = $$outStack.pop();
                    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                        if (it.async) {
                            out += ' throw new ValidationError([' + (__err) + ']); ';
                        }
                        else {
                            out += ' validate.errors = [' + (__err) + ']; return false; ';
                        }
                    }
                    else {
                        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                    }
                    out += ' } else { ';
                }
                else {
                    out += ' if ( ';
                    var arr2 = $required;
                    if (arr2) {
                        var $propertyKey, $i = -1, l2 = arr2.length - 1;
                        while ($i < l2) {
                            $propertyKey = arr2[$i += 1];
                            if ($i) {
                                out += ' || ';
                            }
                            var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
                            out += ' ( ( ' + ($useData) + ' === undefined ';
                            if ($ownProperties) {
                                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                            }
                            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
                        }
                    }
                    out += ') {  ';
                    var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \'';
                    if (it.opts._errorDataPathProperty) {
                        it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
                    }
                    var $$outStack = $$outStack || [];
                    $$outStack.push(out);
                    out = ''; /* istanbul ignore else */
                    if (it.createErrors !== false) {
                        out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                        if (it.opts.messages !== false) {
                            out += ' , message: \'';
                            if (it.opts._errorDataPathProperty) {
                                out += 'is a required property';
                            }
                            else {
                                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                            }
                            out += '\' ';
                        }
                        if (it.opts.verbose) {
                            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                        }
                        out += ' } ';
                    }
                    else {
                        out += ' {} ';
                    }
                    var __err = out;
                    out = $$outStack.pop();
                    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                        if (it.async) {
                            out += ' throw new ValidationError([' + (__err) + ']); ';
                        }
                        else {
                            out += ' validate.errors = [' + (__err) + ']; return false; ';
                        }
                    }
                    else {
                        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                    }
                    out += ' } else { ';
                }
            }
            else {
                if ($loopRequired) {
                    if (!$isData) {
                        out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
                    }
                    var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \'';
                    if (it.opts._errorDataPathProperty) {
                        it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
                    }
                    if ($isData) {
                        out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) {  var err =   '; /* istanbul ignore else */
                        if (it.createErrors !== false) {
                            out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                            if (it.opts.messages !== false) {
                                out += ' , message: \'';
                                if (it.opts._errorDataPathProperty) {
                                    out += 'is a required property';
                                }
                                else {
                                    out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                                }
                                out += '\' ';
                            }
                            if (it.opts.verbose) {
                                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                            }
                            out += ' } ';
                        }
                        else {
                            out += ' {} ';
                        }
                        out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
                    }
                    out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
                    if ($ownProperties) {
                        out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
                    }
                    out += ') {  var err =   '; /* istanbul ignore else */
                    if (it.createErrors !== false) {
                        out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                        if (it.opts.messages !== false) {
                            out += ' , message: \'';
                            if (it.opts._errorDataPathProperty) {
                                out += 'is a required property';
                            }
                            else {
                                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                            }
                            out += '\' ';
                        }
                        if (it.opts.verbose) {
                            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                        }
                        out += ' } ';
                    }
                    else {
                        out += ' {} ';
                    }
                    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
                    if ($isData) {
                        out += '  }  ';
                    }
                }
                else {
                    var arr3 = $required;
                    if (arr3) {
                        var $propertyKey, i3 = -1, l3 = arr3.length - 1;
                        while (i3 < l3) {
                            $propertyKey = arr3[i3 += 1];
                            var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
                            if (it.opts._errorDataPathProperty) {
                                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
                            }
                            out += ' if ( ' + ($useData) + ' === undefined ';
                            if ($ownProperties) {
                                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                            }
                            out += ') {  var err =   '; /* istanbul ignore else */
                            if (it.createErrors !== false) {
                                out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                                if (it.opts.messages !== false) {
                                    out += ' , message: \'';
                                    if (it.opts._errorDataPathProperty) {
                                        out += 'is a required property';
                                    }
                                    else {
                                        out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                                    }
                                    out += '\' ';
                                }
                                if (it.opts.verbose) {
                                    out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                                }
                                out += ' } ';
                            }
                            else {
                                out += ' {} ';
                            }
                            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
                        }
                    }
                }
            }
            it.errorPath = $currentErrorPath;
        }
        else if ($breakOnError) {
            out += ' if (true) {';
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/uniqueItems */ function _(require, module, exports) {
    module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
        var out = ' ';
        var $lvl = it.level;
        var $dataLvl = it.dataLevel;
        var $schema = it.schema[$keyword];
        var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
        var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
        var $breakOnError = !it.opts.allErrors;
        var $data = 'data' + ($dataLvl || '');
        var $valid = 'valid' + $lvl;
        var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
        if ($isData) {
            out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
            $schemaValue = 'schema' + $lvl;
        }
        else {
            $schemaValue = $schema;
        }
        if (($schema || $isData) && it.opts.uniqueItems !== false) {
            if ($isData) {
                out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
            }
            out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } ';
            if ($isData) {
                out += '  }  ';
            }
            out += ' if (!' + ($valid) + ') {   ';
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = ''; /* istanbul ignore else */
            if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
                if (it.opts.messages !== false) {
                    out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
                }
                if (it.opts.verbose) {
                    out += ' , schema:  ';
                    if ($isData) {
                        out += 'validate.schema' + ($schemaPath);
                    }
                    else {
                        out += '' + ($schema);
                    }
                    out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
            }
            else {
                out += ' {} ';
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                    out += ' throw new ValidationError([' + (__err) + ']); ';
                }
                else {
                    out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
            }
            else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
            }
            out += ' } ';
            if ($breakOnError) {
                out += ' else { ';
            }
        }
        else {
            if ($breakOnError) {
                out += ' if (true) { ';
            }
        }
        return out;
    };
}
,
/* ajv/lib/dotjs/validate */ function _(require, module, exports) {
    module.exports = function generate_validate(it, $keyword, $ruleType) {
        var out = '';
        var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), $id = it.self._getId(it.schema);
        if (it.isTop) {
            if ($async) {
                it.async = true;
                var $es7 = it.opts.async == 'es7';
                it.yieldAwait = $es7 ? 'await' : 'yield';
            }
            out += ' var validate = ';
            if ($async) {
                if ($es7) {
                    out += ' (async function ';
                }
                else {
                    if (it.opts.async != '*') {
                        out += 'co.wrap';
                    }
                    out += '(function* ';
                }
            }
            else {
                out += ' (function ';
            }
            out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
            if ($id && (it.opts.sourceCode || it.opts.processCode)) {
                out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
            }
        }
        if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
            var $keyword = 'false schema';
            var $lvl = it.level;
            var $dataLvl = it.dataLevel;
            var $schema = it.schema[$keyword];
            var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
            var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
            var $breakOnError = !it.opts.allErrors;
            var $errorKeyword;
            var $data = 'data' + ($dataLvl || '');
            var $valid = 'valid' + $lvl;
            if (it.schema === false) {
                if (it.isTop) {
                    $breakOnError = true;
                }
                else {
                    out += ' var ' + ($valid) + ' = false; ';
                }
                var $$outStack = $$outStack || [];
                $$outStack.push(out);
                out = ''; /* istanbul ignore else */
                if (it.createErrors !== false) {
                    out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
                    if (it.opts.messages !== false) {
                        out += ' , message: \'boolean schema is false\' ';
                    }
                    if (it.opts.verbose) {
                        out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                    }
                    out += ' } ';
                }
                else {
                    out += ' {} ';
                }
                var __err = out;
                out = $$outStack.pop();
                if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                    if (it.async) {
                        out += ' throw new ValidationError([' + (__err) + ']); ';
                    }
                    else {
                        out += ' validate.errors = [' + (__err) + ']; return false; ';
                    }
                }
                else {
                    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                }
            }
            else {
                if (it.isTop) {
                    if ($async) {
                        out += ' return data; ';
                    }
                    else {
                        out += ' validate.errors = null; return true; ';
                    }
                }
                else {
                    out += ' var ' + ($valid) + ' = true; ';
                }
            }
            if (it.isTop) {
                out += ' }); return validate; ';
            }
            return out;
        }
        if (it.isTop) {
            var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = 'data';
            it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
            it.baseId = it.baseId || it.rootId;
            delete it.isTop;
            it.dataPathArr = [undefined];
            out += ' var vErrors = null; ';
            out += ' var errors = 0;     ';
            out += ' if (rootData === undefined) rootData = data; ';
        }
        else {
            var $lvl = it.level, $dataLvl = it.dataLevel, $data = 'data' + ($dataLvl || '');
            if ($id)
                it.baseId = it.resolve.url(it.baseId, $id);
            if ($async && !it.async)
                throw new Error('async schema in sync schema');
            out += ' var errs_' + ($lvl) + ' = errors;';
        }
        var $valid = 'valid' + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = '', $closingBraces2 = '';
        var $errorKeyword;
        var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema);
        if ($typeIsArray && $typeSchema.length == 1) {
            $typeSchema = $typeSchema[0];
            $typeIsArray = false;
        }
        if (it.schema.$ref && $refKeywords) {
            if (it.opts.extendRefs == 'fail') {
                throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
            }
            else if (it.opts.extendRefs !== true) {
                $refKeywords = false;
                it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
            }
        }
        if ($typeSchema) {
            if (it.opts.coerceTypes) {
                var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
            }
            var $rulesGroup = it.RULES.types[$typeSchema];
            if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
                var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type';
                var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type', $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
                out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
                if ($coerceToTypes) {
                    var $dataType = 'dataType' + $lvl, $coerced = 'coerced' + $lvl;
                    out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
                    if (it.opts.coerceTypes == 'array') {
                        out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
                    }
                    out += ' var ' + ($coerced) + ' = undefined; ';
                    var $bracesCoercion = '';
                    var arr1 = $coerceToTypes;
                    if (arr1) {
                        var $type, $i = -1, l1 = arr1.length - 1;
                        while ($i < l1) {
                            $type = arr1[$i += 1];
                            if ($i) {
                                out += ' if (' + ($coerced) + ' === undefined) { ';
                                $bracesCoercion += '}';
                            }
                            if (it.opts.coerceTypes == 'array' && $type != 'array') {
                                out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + ';  } ';
                            }
                            if ($type == 'string') {
                                out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
                            }
                            else if ($type == 'number' || $type == 'integer') {
                                out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
                                if ($type == 'integer') {
                                    out += ' && !(' + ($data) + ' % 1)';
                                }
                                out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
                            }
                            else if ($type == 'boolean') {
                                out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
                            }
                            else if ($type == 'null') {
                                out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
                            }
                            else if (it.opts.coerceTypes == 'array' && $type == 'array') {
                                out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
                            }
                        }
                    }
                    out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) {   ';
                    var $$outStack = $$outStack || [];
                    $$outStack.push(out);
                    out = ''; /* istanbul ignore else */
                    if (it.createErrors !== false) {
                        out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                        if ($typeIsArray) {
                            out += '' + ($typeSchema.join(","));
                        }
                        else {
                            out += '' + ($typeSchema);
                        }
                        out += '\' } ';
                        if (it.opts.messages !== false) {
                            out += ' , message: \'should be ';
                            if ($typeIsArray) {
                                out += '' + ($typeSchema.join(","));
                            }
                            else {
                                out += '' + ($typeSchema);
                            }
                            out += '\' ';
                        }
                        if (it.opts.verbose) {
                            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                        }
                        out += ' } ';
                    }
                    else {
                        out += ' {} ';
                    }
                    var __err = out;
                    out = $$outStack.pop();
                    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                        if (it.async) {
                            out += ' throw new ValidationError([' + (__err) + ']); ';
                        }
                        else {
                            out += ' validate.errors = [' + (__err) + ']; return false; ';
                        }
                    }
                    else {
                        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                    }
                    out += ' } else {  ';
                    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
                    out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
                    if (!$dataLvl) {
                        out += 'if (' + ($parentData) + ' !== undefined)';
                    }
                    out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
                }
                else {
                    var $$outStack = $$outStack || [];
                    $$outStack.push(out);
                    out = ''; /* istanbul ignore else */
                    if (it.createErrors !== false) {
                        out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                        if ($typeIsArray) {
                            out += '' + ($typeSchema.join(","));
                        }
                        else {
                            out += '' + ($typeSchema);
                        }
                        out += '\' } ';
                        if (it.opts.messages !== false) {
                            out += ' , message: \'should be ';
                            if ($typeIsArray) {
                                out += '' + ($typeSchema.join(","));
                            }
                            else {
                                out += '' + ($typeSchema);
                            }
                            out += '\' ';
                        }
                        if (it.opts.verbose) {
                            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                        }
                        out += ' } ';
                    }
                    else {
                        out += ' {} ';
                    }
                    var __err = out;
                    out = $$outStack.pop();
                    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                        if (it.async) {
                            out += ' throw new ValidationError([' + (__err) + ']); ';
                        }
                        else {
                            out += ' validate.errors = [' + (__err) + ']; return false; ';
                        }
                    }
                    else {
                        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                    }
                }
                out += ' } ';
            }
        }
        if (it.schema.$ref && !$refKeywords) {
            out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
            if ($breakOnError) {
                out += ' } if (errors === ';
                if ($top) {
                    out += '0';
                }
                else {
                    out += 'errs_' + ($lvl);
                }
                out += ') { ';
                $closingBraces2 += '}';
            }
        }
        else {
            if (it.opts.v5 && it.schema.patternGroups) {
                it.logger.warn('keyword "patternGroups" is deprecated and disabled. Use option patternGroups: true to enable.');
            }
            var arr2 = it.RULES;
            if (arr2) {
                var $rulesGroup, i2 = -1, l2 = arr2.length - 1;
                while (i2 < l2) {
                    $rulesGroup = arr2[i2 += 1];
                    if ($shouldUseGroup($rulesGroup)) {
                        if ($rulesGroup.type) {
                            out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
                        }
                        if (it.opts.useDefaults && !it.compositeRule) {
                            if ($rulesGroup.type == 'object' && it.schema.properties) {
                                var $schema = it.schema.properties, $schemaKeys = Object.keys($schema);
                                var arr3 = $schemaKeys;
                                if (arr3) {
                                    var $propertyKey, i3 = -1, l3 = arr3.length - 1;
                                    while (i3 < l3) {
                                        $propertyKey = arr3[i3 += 1];
                                        var $sch = $schema[$propertyKey];
                                        if ($sch.default !== undefined) {
                                            var $passData = $data + it.util.getProperty($propertyKey);
                                            out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
                                            if (it.opts.useDefaults == 'shared') {
                                                out += ' ' + (it.useDefault($sch.default)) + ' ';
                                            }
                                            else {
                                                out += ' ' + (JSON.stringify($sch.default)) + ' ';
                                            }
                                            out += '; ';
                                        }
                                    }
                                }
                            }
                            else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
                                var arr4 = it.schema.items;
                                if (arr4) {
                                    var $sch, $i = -1, l4 = arr4.length - 1;
                                    while ($i < l4) {
                                        $sch = arr4[$i += 1];
                                        if ($sch.default !== undefined) {
                                            var $passData = $data + '[' + $i + ']';
                                            out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
                                            if (it.opts.useDefaults == 'shared') {
                                                out += ' ' + (it.useDefault($sch.default)) + ' ';
                                            }
                                            else {
                                                out += ' ' + (JSON.stringify($sch.default)) + ' ';
                                            }
                                            out += '; ';
                                        }
                                    }
                                }
                            }
                        }
                        var arr5 = $rulesGroup.rules;
                        if (arr5) {
                            var $rule, i5 = -1, l5 = arr5.length - 1;
                            while (i5 < l5) {
                                $rule = arr5[i5 += 1];
                                if ($shouldUseRule($rule)) {
                                    var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                                    if ($code) {
                                        out += ' ' + ($code) + ' ';
                                        if ($breakOnError) {
                                            $closingBraces1 += '}';
                                        }
                                    }
                                }
                            }
                        }
                        if ($breakOnError) {
                            out += ' ' + ($closingBraces1) + ' ';
                            $closingBraces1 = '';
                        }
                        if ($rulesGroup.type) {
                            out += ' } ';
                            if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
                                out += ' else { ';
                                var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type';
                                var $$outStack = $$outStack || [];
                                $$outStack.push(out);
                                out = ''; /* istanbul ignore else */
                                if (it.createErrors !== false) {
                                    out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                                    if ($typeIsArray) {
                                        out += '' + ($typeSchema.join(","));
                                    }
                                    else {
                                        out += '' + ($typeSchema);
                                    }
                                    out += '\' } ';
                                    if (it.opts.messages !== false) {
                                        out += ' , message: \'should be ';
                                        if ($typeIsArray) {
                                            out += '' + ($typeSchema.join(","));
                                        }
                                        else {
                                            out += '' + ($typeSchema);
                                        }
                                        out += '\' ';
                                    }
                                    if (it.opts.verbose) {
                                        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                                    }
                                    out += ' } ';
                                }
                                else {
                                    out += ' {} ';
                                }
                                var __err = out;
                                out = $$outStack.pop();
                                if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                                    if (it.async) {
                                        out += ' throw new ValidationError([' + (__err) + ']); ';
                                    }
                                    else {
                                        out += ' validate.errors = [' + (__err) + ']; return false; ';
                                    }
                                }
                                else {
                                    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
                                }
                                out += ' } ';
                            }
                        }
                        if ($breakOnError) {
                            out += ' if (errors === ';
                            if ($top) {
                                out += '0';
                            }
                            else {
                                out += 'errs_' + ($lvl);
                            }
                            out += ') { ';
                            $closingBraces2 += '}';
                        }
                    }
                }
            }
        }
        if ($breakOnError) {
            out += ' ' + ($closingBraces2) + ' ';
        }
        if ($top) {
            if ($async) {
                out += ' if (errors === 0) return data;           ';
                out += ' else throw new ValidationError(vErrors); ';
            }
            else {
                out += ' validate.errors = vErrors; ';
                out += ' return errors === 0;       ';
            }
            out += ' }); return validate;';
        }
        else {
            out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
        }
        out = it.util.cleanUpCode(out);
        if ($top) {
            out = it.util.finalCleanUpCode(out, $async);
        }
        function $shouldUseGroup($rulesGroup) {
            var rules = $rulesGroup.rules;
            for (var i = 0; i < rules.length; i++)
                if ($shouldUseRule(rules[i]))
                    return true;
        }
        function $shouldUseRule($rule) {
            return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
        }
        function $ruleImplementsSomeKeyword($rule) {
            var impl = $rule.implements;
            for (var i = 0; i < impl.length; i++)
                if (it.schema[impl[i]] !== undefined)
                    return true;
        }
        return out;
    };
}
,
/* ajv/lib/keyword */ function _(require, module, exports) {
    var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
    var customRuleCode = require(23) /* ./dotjs/custom */;
    module.exports = {
        add: addKeyword,
        get: getKeyword,
        remove: removeKeyword
    };
    /**
     * Define custom keyword
     * @this  Ajv
     * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
     * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
     * @return {Ajv} this for method chaining
     */
    function addKeyword(keyword, definition) {
        /* jshint validthis: true */
        /* eslint no-shadow: 0 */
        var RULES = this.RULES;
        if (RULES.keywords[keyword])
            throw new Error('Keyword ' + keyword + ' is already defined');
        if (!IDENTIFIER.test(keyword))
            throw new Error('Keyword ' + keyword + ' is not a valid identifier');
        if (definition) {
            if (definition.macro && definition.valid !== undefined)
                throw new Error('"valid" option cannot be used with macro keywords');
            var dataType = definition.type;
            if (Array.isArray(dataType)) {
                var i, len = dataType.length;
                for (i = 0; i < len; i++)
                    checkDataType(dataType[i]);
                for (i = 0; i < len; i++)
                    _addRule(keyword, dataType[i], definition);
            }
            else {
                if (dataType)
                    checkDataType(dataType);
                _addRule(keyword, dataType, definition);
            }
            var $data = definition.$data === true && this._opts.$data;
            if ($data && !definition.validate)
                throw new Error('$data support: "validate" function is not defined');
            var metaSchema = definition.metaSchema;
            if (metaSchema) {
                if ($data) {
                    metaSchema = {
                        anyOf: [
                            metaSchema,
                            { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }
                        ]
                    };
                }
                definition.validateSchema = this.compile(metaSchema, true);
            }
        }
        RULES.keywords[keyword] = RULES.all[keyword] = true;
        function _addRule(keyword, dataType, definition) {
            var ruleGroup;
            for (var i = 0; i < RULES.length; i++) {
                var rg = RULES[i];
                if (rg.type == dataType) {
                    ruleGroup = rg;
                    break;
                }
            }
            if (!ruleGroup) {
                ruleGroup = { type: dataType, rules: [] };
                RULES.push(ruleGroup);
            }
            var rule = {
                keyword: keyword,
                definition: definition,
                custom: true,
                code: customRuleCode,
                implements: definition.implements
            };
            ruleGroup.rules.push(rule);
            RULES.custom[keyword] = rule;
        }
        function checkDataType(dataType) {
            if (!RULES.types[dataType])
                throw new Error('Unknown type ' + dataType);
        }
        return this;
    }
    /**
     * Get keyword
     * @this  Ajv
     * @param {String} keyword pre-defined or custom keyword.
     * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
     */
    function getKeyword(keyword) {
        /* jshint validthis: true */
        var rule = this.RULES.custom[keyword];
        return rule ? rule.definition : this.RULES.keywords[keyword] || false;
    }
    /**
     * Remove keyword
     * @this  Ajv
     * @param {String} keyword pre-defined or custom keyword.
     * @return {Ajv} this for method chaining
     */
    function removeKeyword(keyword) {
        /* jshint validthis: true */
        var RULES = this.RULES;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        delete RULES.custom[keyword];
        for (var i = 0; i < RULES.length; i++) {
            var rules = RULES[i].rules;
            for (var j = 0; j < rules.length; j++) {
                if (rules[j].keyword == keyword) {
                    rules.splice(j, 1);
                    break;
                }
            }
        }
        return this;
    }
}
,
/* ajv/lib/patternGroups */ function _(require, module, exports) {
    var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema';
    module.exports = function (ajv) {
        var defaultMeta = ajv._opts.defaultMeta;
        var metaSchemaRef = typeof defaultMeta == 'string'
            ? { $ref: defaultMeta }
            : ajv.getSchema(META_SCHEMA_ID)
                ? { $ref: META_SCHEMA_ID }
                : {};
        ajv.addKeyword('patternGroups', {
            // implemented in properties.jst
            metaSchema: {
                type: 'object',
                additionalProperties: {
                    type: 'object',
                    required: ['schema'],
                    properties: {
                        maximum: {
                            type: 'integer',
                            minimum: 0
                        },
                        minimum: {
                            type: 'integer',
                            minimum: 0
                        },
                        schema: metaSchemaRef
                    },
                    additionalProperties: false
                }
            }
        });
        ajv.RULES.all.properties.implements.push('patternGroups');
    };
}
,
/* ajv/lib/refs/$data.json */ function _(require, module, exports) {
    {
        "$schema";
        "http://json-schema.org/draft-06/schema#",
            "$id";
        "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#",
            "description";
        "Meta-schema for $data reference (JSON-schema extension proposal)",
            "type";
        "object",
            "required";
        ["$data"],
            "properties";
        {
            "$data";
            {
                "type";
                "string",
                    "anyOf";
                [
                    { "format": "relative-json-pointer" },
                    { "format": "json-pointer" }
                ];
            }
        }
        "additionalProperties";
        false;
    }
}
,
/* ajv/lib/refs/json-schema-draft-06.json */ function _(require, module, exports) {
    {
        "$schema";
        "http://json-schema.org/draft-06/schema#",
            "$id";
        "http://json-schema.org/draft-06/schema#",
            "title";
        "Core schema meta-schema",
            "definitions";
        {
            "schemaArray";
            {
                "type";
                "array",
                    "minItems";
                1,
                    "items";
                {
                    "$ref";
                    "#";
                }
            }
            "nonNegativeInteger";
            {
                "type";
                "integer",
                    "minimum";
                0;
            }
            "nonNegativeIntegerDefault0";
            {
                "allOf";
                [
                    { "$ref": "#/definitions/nonNegativeInteger" },
                    { "default": 0 }
                ];
            }
            "simpleTypes";
            {
                "enum";
                [
                    "array",
                    "boolean",
                    "integer",
                    "null",
                    "number",
                    "object",
                    "string"
                ];
            }
            "stringArray";
            {
                "type";
                "array",
                    "items";
                {
                    "type";
                    "string";
                }
                "uniqueItems";
                true,
                    "default";
                [];
            }
        }
        "type";
        ["object", "boolean"],
            "properties";
        {
            "$id";
            {
                "type";
                "string",
                    "format";
                "uri-reference";
            }
            "$schema";
            {
                "type";
                "string",
                    "format";
                "uri";
            }
            "$ref";
            {
                "type";
                "string",
                    "format";
                "uri-reference";
            }
            "title";
            {
                "type";
                "string";
            }
            "description";
            {
                "type";
                "string";
            }
            "default";
            { }
            "examples";
            {
                "type";
                "array",
                    "items";
                { }
            }
            "multipleOf";
            {
                "type";
                "number",
                    "exclusiveMinimum";
                0;
            }
            "maximum";
            {
                "type";
                "number";
            }
            "exclusiveMaximum";
            {
                "type";
                "number";
            }
            "minimum";
            {
                "type";
                "number";
            }
            "exclusiveMinimum";
            {
                "type";
                "number";
            }
            "maxLength";
            {
                "$ref";
                "#/definitions/nonNegativeInteger";
            }
            "minLength";
            {
                "$ref";
                "#/definitions/nonNegativeIntegerDefault0";
            }
            "pattern";
            {
                "type";
                "string",
                    "format";
                "regex";
            }
            "additionalItems";
            {
                "$ref";
                "#";
            }
            "items";
            {
                "anyOf";
                [
                    { "$ref": "#" },
                    { "$ref": "#/definitions/schemaArray" }
                ],
                    "default";
                { }
            }
            "maxItems";
            {
                "$ref";
                "#/definitions/nonNegativeInteger";
            }
            "minItems";
            {
                "$ref";
                "#/definitions/nonNegativeIntegerDefault0";
            }
            "uniqueItems";
            {
                "type";
                "boolean",
                    "default";
                false;
            }
            "contains";
            {
                "$ref";
                "#";
            }
            "maxProperties";
            {
                "$ref";
                "#/definitions/nonNegativeInteger";
            }
            "minProperties";
            {
                "$ref";
                "#/definitions/nonNegativeIntegerDefault0";
            }
            "required";
            {
                "$ref";
                "#/definitions/stringArray";
            }
            "additionalProperties";
            {
                "$ref";
                "#";
            }
            "definitions";
            {
                "type";
                "object",
                    "additionalProperties";
                {
                    "$ref";
                    "#";
                }
                "default";
                { }
            }
            "properties";
            {
                "type";
                "object",
                    "additionalProperties";
                {
                    "$ref";
                    "#";
                }
                "default";
                { }
            }
            "patternProperties";
            {
                "type";
                "object",
                    "additionalProperties";
                {
                    "$ref";
                    "#";
                }
                "default";
                { }
            }
            "dependencies";
            {
                "type";
                "object",
                    "additionalProperties";
                {
                    "anyOf";
                    [
                        { "$ref": "#" },
                        { "$ref": "#/definitions/stringArray" }
                    ];
                }
            }
            "propertyNames";
            {
                "$ref";
                "#";
            }
            "const";
            { }
            "enum";
            {
                "type";
                "array",
                    "minItems";
                1,
                    "uniqueItems";
                true;
            }
            "type";
            {
                "anyOf";
                [
                    { "$ref": "#/definitions/simpleTypes" },
                    {
                        "type": "array",
                        "items": { "$ref": "#/definitions/simpleTypes" },
                        "minItems": 1,
                        "uniqueItems": true
                    }
                ];
            }
            "format";
            {
                "type";
                "string";
            }
            "allOf";
            {
                "$ref";
                "#/definitions/schemaArray";
            }
            "anyOf";
            {
                "$ref";
                "#/definitions/schemaArray";
            }
            "oneOf";
            {
                "$ref";
                "#/definitions/schemaArray";
            }
            "not";
            {
                "$ref";
                "#";
            }
        }
        "default";
        { }
    }
}
,
/* align-text/index */ function _(require, module, exports) {
    var typeOf = require(160) /* kind-of */;
    var repeat = require(294) /* repeat-string */;
    var longest = require(261) /* longest */;
    module.exports = function alignText(val, fn) {
        var lines, type = typeOf(val);
        if (type === 'array') {
            lines = val;
        }
        else if (type === 'string') {
            lines = val.split(/(?:\r\n|\n)/);
        }
        else {
            throw new TypeError('align-text expects a string or array.');
        }
        var fnType = typeOf(fn);
        var len = lines.length;
        var max = longest(lines);
        var res = [], i = 0;
        while (len--) {
            var line = String(lines[i++]);
            var diff;
            if (fnType === 'function') {
                diff = fn(line.length, max.length, line, lines, i);
            }
            else if (fnType === 'number') {
                diff = fn;
            }
            else {
                diff = max.length - line.length;
            }
            if (typeOf(diff) === 'number') {
                res.push(repeat(' ', diff) + line);
            }
            else if (typeOf(diff) === 'object') {
                var result = repeat(diff.character || ' ', diff.indent || 0);
                res.push((diff.prefix || '') + result + line);
            }
        }
        if (type === 'array')
            return res;
        return res.join('\n');
    };
}
,
/* amdefine/amdefine */ function _(require, module, exports) {
    /**
     * Creates a define for node.
     * @param {Object} module the "module" object that is defined by Node for the
     * current module.
     * @param {Function} [requireFn]. Node's require function for the current module.
     * It only needs to be passed in Node versions before 0.5, when module.require
     * did not exist.
     * @returns {Function} a define function that is usable for the current node
     * module.
     */
    function amdefine(module, requireFn) {
        'use strict';
        var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = require('path'), makeRequire, stringRequire;
        /**
         * Trims the . and .. from an array of path segments.
         * It will keep a leading path segment if a .. will become
         * the first path segment, to help with module name lookups,
         * which act like paths, but can be remapped. But the end result,
         * all paths that use this function should look normalized.
         * NOTE: this method MODIFIES the input array.
         * @param {Array} ary the array of path segments.
         */
        function trimDots(ary) {
            var i, part;
            for (i = 0; ary[i]; i += 1) {
                part = ary[i];
                if (part === '.') {
                    ary.splice(i, 1);
                    i -= 1;
                }
                else if (part === '..') {
                    if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
                        //End of the line. Keep at least one non-dot
                        //path segment at the front so it can be mapped
                        //correctly to disk. Otherwise, there is likely
                        //no path mapping for a path starting with '..'.
                        //This can still fail, but catches the most reasonable
                        //uses of ..
                        break;
                    }
                    else if (i > 0) {
                        ary.splice(i - 1, 2);
                        i -= 2;
                    }
                }
            }
        }
        function normalize(name, baseName) {
            var baseParts;
            //Adjust any relative paths.
            if (name && name.charAt(0) === '.') {
                //If have a base name, try to normalize against it,
                //otherwise, assume it is a top-level require that will
                //be relative to baseUrl in the end.
                if (baseName) {
                    baseParts = baseName.split('/');
                    baseParts = baseParts.slice(0, baseParts.length - 1);
                    baseParts = baseParts.concat(name.split('/'));
                    trimDots(baseParts);
                    name = baseParts.join('/');
                }
            }
            return name;
        }
        /**
         * Create the normalize() function passed to a loader plugin's
         * normalize method.
         */
        function makeNormalize(relName) {
            return function (name) {
                return normalize(name, relName);
            };
        }
        function makeLoad(id) {
            function load(value) {
                loaderCache[id] = value;
            }
            load.fromText = function (id, text) {
                //This one is difficult because the text can/probably uses
                //define, and any relative paths and requires should be relative
                //to that id was it would be found on disk. But this would require
                //bootstrapping a module/require fairly deeply from node core.
                //Not sure how best to go about that yet.
                throw new Error('amdefine does not implement load.fromText');
            };
            return load;
        }
        makeRequire = function (systemRequire, exports, module, relId) {
            function amdRequire(deps, callback) {
                if (typeof deps === 'string') {
                    //Synchronous, single module require('')
                    return stringRequire(systemRequire, exports, module, deps, relId);
                }
                else {
                    //Array of dependencies with a callback.
                    //Convert the dependencies to modules.
                    deps = deps.map(function (depName) {
                        return stringRequire(systemRequire, exports, module, depName, relId);
                    });
                    //Wait for next tick to call back the require call.
                    if (callback) {
                        process.nextTick(function () {
                            callback.apply(null, deps);
                        });
                    }
                }
            }
            amdRequire.toUrl = function (filePath) {
                if (filePath.indexOf('.') === 0) {
                    return normalize(filePath, path.dirname(module.filename));
                }
                else {
                    return filePath;
                }
            };
            return amdRequire;
        };
        //Favor explicit value, passed in if the module wants to support Node 0.4.
        requireFn = requireFn || function req() {
            return module.require.apply(module, arguments);
        };
        function runFactory(id, deps, factory) {
            var r, e, m, result;
            if (id) {
                e = loaderCache[id] = {};
                m = {
                    id: id,
                    uri: __filename,
                    exports: e
                };
                r = makeRequire(requireFn, e, m, id);
            }
            else {
                //Only support one define call per file
                if (alreadyCalled) {
                    throw new Error('amdefine with no module ID cannot be called more than once per file.');
                }
                alreadyCalled = true;
                //Use the real variables from node
                //Use module.exports for exports, since
                //the exports in here is amdefine exports.
                e = module.exports;
                m = module;
                r = makeRequire(requireFn, e, m, module.id);
            }
            //If there are dependencies, they are strings, so need
            //to convert them to dependency values.
            if (deps) {
                deps = deps.map(function (depName) {
                    return r(depName);
                });
            }
            //Call the factory with the right dependencies.
            if (typeof factory === 'function') {
                result = factory.apply(m.exports, deps);
            }
            else {
                result = factory;
            }
            if (result !== undefined) {
                m.exports = result;
                if (id) {
                    loaderCache[id] = m.exports;
                }
            }
        }
        stringRequire = function (systemRequire, exports, module, id, relId) {
            //Split the ID by a ! so that
            var index = id.indexOf('!'), originalId = id, prefix, plugin;
            if (index === -1) {
                id = normalize(id, relId);
                //Straight module lookup. If it is one of the special dependencies,
                //deal with it, otherwise, delegate to node.
                if (id === 'require') {
                    return makeRequire(systemRequire, exports, module, relId);
                }
                else if (id === 'exports') {
                    return exports;
                }
                else if (id === 'module') {
                    return module;
                }
                else if (loaderCache.hasOwnProperty(id)) {
                    return loaderCache[id];
                }
                else if (defineCache[id]) {
                    runFactory.apply(null, defineCache[id]);
                    return loaderCache[id];
                }
                else {
                    if (systemRequire) {
                        return systemRequire(originalId);
                    }
                    else {
                        throw new Error('No module with ID: ' + id);
                    }
                }
            }
            else {
                //There is a plugin in play.
                prefix = id.substring(0, index);
                id = id.substring(index + 1, id.length);
                plugin = stringRequire(systemRequire, exports, module, prefix, relId);
                if (plugin.normalize) {
                    id = plugin.normalize(id, makeNormalize(relId));
                }
                else {
                    //Normalize the ID normally.
                    id = normalize(id, relId);
                }
                if (loaderCache[id]) {
                    return loaderCache[id];
                }
                else {
                    plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
                    return loaderCache[id];
                }
            }
        };
        //Create a define function specific to the module asking for amdefine.
        function define(id, deps, factory) {
            if (Array.isArray(id)) {
                factory = deps;
                deps = id;
                id = undefined;
            }
            else if (typeof id !== 'string') {
                factory = id;
                id = deps = undefined;
            }
            if (deps && !Array.isArray(deps)) {
                factory = deps;
                deps = undefined;
            }
            if (!deps) {
                deps = ['require', 'exports', 'module'];
            }
            //Set up properties for this module. If an ID, then use
            //internal cache. If no ID, then use the external variables
            //for this node module.
            if (id) {
                //Put the module in deep freeze until there is a
                //require call for it.
                defineCache[id] = [id, deps, factory];
            }
            else {
                runFactory(id, deps, factory);
            }
        }
        //define.require, which has access to all the values in the
        //cache. Useful for AMD modules that all have IDs in the file,
        //but need to finally export a value to node based on one of those
        //IDs.
        define.require = function (id) {
            if (loaderCache[id]) {
                return loaderCache[id];
            }
            if (defineCache[id]) {
                runFactory.apply(null, defineCache[id]);
                return loaderCache[id];
            }
        };
        define.amd = {};
        return define;
    }
    module.exports = amdefine;
}
,
/* ansi-regex/index */ function _(require, module, exports) {
    module.exports = function () {
        return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
    };
}
,
/* asap/asap */ function _(require, module, exports) {
    var rawAsap = require(46) /* ./raw */;
    var freeTasks = [];
    /**
     * Calls a task as soon as possible after returning, in its own event, with
     * priority over IO events. An exception thrown in a task can be handled by
     * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise
     * crash the process. If the error is handled, all subsequent tasks will
     * resume.
     *
     * @param {{call}} task A callable object, typically a function that takes no
     * arguments.
     */
    module.exports = asap;
    function asap(task) {
        var rawTask;
        if (freeTasks.length) {
            rawTask = freeTasks.pop();
        }
        else {
            rawTask = new RawTask();
        }
        rawTask.task = task;
        rawTask.domain = process.domain;
        rawAsap(rawTask);
    }
    function RawTask() {
        this.task = null;
        this.domain = null;
    }
    RawTask.prototype.call = function () {
        if (this.domain) {
            this.domain.enter();
        }
        var threw = true;
        try {
            this.task.call();
            threw = false;
            // If the task throws an exception (presumably) Node.js restores the
            // domain stack for the next event.
            if (this.domain) {
                this.domain.exit();
            }
        }
        finally {
            // We use try/finally and a threw flag to avoid messing up stack traces
            // when we catch and release errors.
            if (threw) {
                // In Node.js, uncaught exceptions are considered fatal errors.
                // Re-throw them to interrupt flushing!
                // Ensure that flushing continues if an uncaught exception is
                // suppressed listening process.on("uncaughtException") or
                // domain.on("error").
                rawAsap.requestFlush();
            }
            // If the task threw an error, we do not want to exit the domain here.
            // Exiting the domain would prevent the domain from catching the error.
            this.task = null;
            this.domain = null;
            freeTasks.push(this);
        }
    };
}
,
/* asap/raw */ function _(require, module, exports) {
    var domain; // The domain module is executed on demand
    var hasSetImmediate = typeof setImmediate === "function";
    // Use the fastest means possible to execute a task in its own turn, with
    // priority over other events including network IO events in Node.js.
    //
    // An exception thrown by a task will permanently interrupt the processing of
    // subsequent tasks. The higher level `asap` function ensures that if an
    // exception is thrown by a task, that the task queue will continue flushing as
    // soon as possible, but if you use `rawAsap` directly, you are responsible to
    // either ensure that no exceptions are thrown from your task, or to manually
    // call `rawAsap.requestFlush` if an exception is thrown.
    module.exports = rawAsap;
    function rawAsap(task) {
        if (!queue.length) {
            requestFlush();
            flushing = true;
        }
        // Avoids a function call
        queue[queue.length] = task;
    }
    var queue = [];
    // Once a flush has been requested, no further calls to `requestFlush` are
    // necessary until the next `flush` completes.
    var flushing = false;
    // The position of the next task to execute in the task queue. This is
    // preserved between calls to `flush` so that it can be resumed if
    // a task throws an exception.
    var index = 0;
    // If a task schedules additional tasks recursively, the task queue can grow
    // unbounded. To prevent memory excaustion, the task queue will periodically
    // truncate already-completed tasks.
    var capacity = 1024;
    // The flush function processes all tasks that have been scheduled with
    // `rawAsap` unless and until one of those tasks throws an exception.
    // If a task throws an exception, `flush` ensures that its state will remain
    // consistent and will resume where it left off when called again.
    // However, `flush` does not make any arrangements to be called again if an
    // exception is thrown.
    function flush() {
        while (index < queue.length) {
            var currentIndex = index;
            // Advance the index before calling the task. This ensures that we will
            // begin flushing on the next task the task throws an error.
            index = index + 1;
            queue[currentIndex].call();
            // Prevent leaking memory for long chains of recursive calls to `asap`.
            // If we call `asap` within tasks scheduled by `asap`, the queue will
            // grow, but to avoid an O(n) walk for every task we execute, we don't
            // shift tasks off the queue after they have been executed.
            // Instead, we periodically shift 1024 tasks off the queue.
            if (index > capacity) {
                // Manually shift all values starting at the index back to the
                // beginning of the queue.
                for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
                    queue[scan] = queue[scan + index];
                }
                queue.length -= index;
                index = 0;
            }
        }
        queue.length = 0;
        index = 0;
        flushing = false;
    }
    rawAsap.requestFlush = requestFlush;
    function requestFlush() {
        // Ensure flushing is not bound to any domain.
        // It is not sufficient to exit the domain, because domains exist on a stack.
        // To execute code outside of any domain, the following dance is necessary.
        var parentDomain = process.domain;
        if (parentDomain) {
            if (!domain) {
                // Lazy execute the domain module.
                // Only employed if the user elects to use domains.
                domain = require("domain");
            }
            domain.active = process.domain = null;
        }
        // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
        // cannot handle recursion.
        // `requestFlush` will only be called recursively from `asap.js`, to resume
        // flushing after an error is thrown into a domain.
        // Conveniently, `setImmediate` was introduced in the same version
        // `process.nextTick` started throwing recursion errors.
        if (flushing && hasSetImmediate) {
            setImmediate(flush);
        }
        else {
            process.nextTick(flush);
        }
        if (parentDomain) {
            domain.active = process.domain = parentDomain;
        }
    }
}
,
/* asn1/lib/ber/errors */ function _(require, module, exports) {
    // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
    module.exports = {
        newInvalidAsn1Error: function (msg) {
            var e = new Error();
            e.name = 'InvalidAsn1Error';
            e.message = msg || '';
            return e;
        }
    };
}
,
/* asn1/lib/ber/index */ function _(require, module, exports) {
    // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
    var errors = require(47) /* ./errors */;
    var types = require(50) /* ./types */;
    var Reader = require(49) /* ./reader */;
    var Writer = require(51) /* ./writer */;
    // --- Exports
    module.exports = {
        Reader: Reader,
        Writer: Writer
    };
    for (var t in types) {
        if (types.hasOwnProperty(t))
            module.exports[t] = types[t];
    }
    for (var e in errors) {
        if (errors.hasOwnProperty(e))
            module.exports[e] = errors[e];
    }
}
,
/* asn1/lib/ber/reader */ function _(require, module, exports) {
    // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
    var assert = require('assert');
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var ASN1 = require(50) /* ./types */;
    var errors = require(47) /* ./errors */;
    // --- Globals
    var newInvalidAsn1Error = errors.newInvalidAsn1Error;
    // --- API
    function Reader(data) {
        if (!data || !Buffer.isBuffer(data))
            throw new TypeError('data must be a node Buffer');
        this._buf = data;
        this._size = data.length;
        // These hold the "current" state
        this._len = 0;
        this._offset = 0;
    }
    Object.defineProperty(Reader.prototype, 'length', {
        enumerable: true,
        get: function () { return (this._len); }
    });
    Object.defineProperty(Reader.prototype, 'offset', {
        enumerable: true,
        get: function () { return (this._offset); }
    });
    Object.defineProperty(Reader.prototype, 'remain', {
        get: function () { return (this._size - this._offset); }
    });
    Object.defineProperty(Reader.prototype, 'buffer', {
        get: function () { return (this._buf.slice(this._offset)); }
    });
    /**
     * Reads a single byte and advances offset; you can pass in `true` to make this
     * a "peek" operation (i.e., get the byte, but don't advance the offset).
     *
     * @param {Boolean} peek true means don't move offset.
     * @return {Number} the next byte, null if not enough data.
     */
    Reader.prototype.readByte = function (peek) {
        if (this._size - this._offset < 1)
            return null;
        var b = this._buf[this._offset] & 0xff;
        if (!peek)
            this._offset += 1;
        return b;
    };
    Reader.prototype.peek = function () {
        return this.readByte(true);
    };
    /**
     * Reads a (potentially) variable length off the BER buffer.  This call is
     * not really meant to be called directly, as callers have to manipulate
     * the internal buffer afterwards.
     *
     * As a result of this call, you can call `Reader.length`, until the
     * next thing called that does a readLength.
     *
     * @return {Number} the amount of offset to advance the buffer.
     * @throws {InvalidAsn1Error} on bad ASN.1
     */
    Reader.prototype.readLength = function (offset) {
        if (offset === undefined)
            offset = this._offset;
        if (offset >= this._size)
            return null;
        var lenB = this._buf[offset++] & 0xff;
        if (lenB === null)
            return null;
        if ((lenB & 0x80) === 0x80) {
            lenB &= 0x7f;
            if (lenB === 0)
                throw newInvalidAsn1Error('Indefinite length not supported');
            if (lenB > 4)
                throw newInvalidAsn1Error('encoding too long');
            if (this._size - offset < lenB)
                return null;
            this._len = 0;
            for (var i = 0; i < lenB; i++)
                this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
        }
        else {
            // Wasn't a variable length
            this._len = lenB;
        }
        return offset;
    };
    /**
     * Parses the next sequence in this BER buffer.
     *
     * To get the length of the sequence, call `Reader.length`.
     *
     * @return {Number} the sequence's tag.
     */
    Reader.prototype.readSequence = function (tag) {
        var seq = this.peek();
        if (seq === null)
            return null;
        if (tag !== undefined && tag !== seq)
            throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                ': got 0x' + seq.toString(16));
        var o = this.readLength(this._offset + 1); // stored in `length`
        if (o === null)
            return null;
        this._offset = o;
        return seq;
    };
    Reader.prototype.readInt = function () {
        return this._readTag(ASN1.Integer);
    };
    Reader.prototype.readBoolean = function () {
        return (this._readTag(ASN1.Boolean) === 0 ? false : true);
    };
    Reader.prototype.readEnumeration = function () {
        return this._readTag(ASN1.Enumeration);
    };
    Reader.prototype.readString = function (tag, retbuf) {
        if (!tag)
            tag = ASN1.OctetString;
        var b = this.peek();
        if (b === null)
            return null;
        if (b !== tag)
            throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                ': got 0x' + b.toString(16));
        var o = this.readLength(this._offset + 1); // stored in `length`
        if (o === null)
            return null;
        if (this.length > this._size - o)
            return null;
        this._offset = o;
        if (this.length === 0)
            return retbuf ? Buffer.alloc(0) : '';
        var str = this._buf.slice(this._offset, this._offset + this.length);
        this._offset += this.length;
        return retbuf ? str : str.toString('utf8');
    };
    Reader.prototype.readOID = function (tag) {
        if (!tag)
            tag = ASN1.OID;
        var b = this.readString(tag, true);
        if (b === null)
            return null;
        var values = [];
        var value = 0;
        for (var i = 0; i < b.length; i++) {
            var byte = b[i] & 0xff;
            value <<= 7;
            value += byte & 0x7f;
            if ((byte & 0x80) === 0) {
                values.push(value);
                value = 0;
            }
        }
        value = values.shift();
        values.unshift(value % 40);
        values.unshift((value / 40) >> 0);
        return values.join('.');
    };
    Reader.prototype._readTag = function (tag) {
        assert.ok(tag !== undefined);
        var b = this.peek();
        if (b === null)
            return null;
        if (b !== tag)
            throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                ': got 0x' + b.toString(16));
        var o = this.readLength(this._offset + 1); // stored in `length`
        if (o === null)
            return null;
        if (this.length > 4)
            throw newInvalidAsn1Error('Integer too long: ' + this.length);
        if (this.length > this._size - o)
            return null;
        this._offset = o;
        var fb = this._buf[this._offset];
        var value = 0;
        for (var i = 0; i < this.length; i++) {
            value <<= 8;
            value |= (this._buf[this._offset++] & 0xff);
        }
        if ((fb & 0x80) === 0x80 && i !== 4)
            value -= (1 << (i * 8));
        return value >> 0;
    };
    // --- Exported API
    module.exports = Reader;
}
,
/* asn1/lib/ber/types */ function _(require, module, exports) {
    // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
    module.exports = {
        EOC: 0,
        Boolean: 1,
        Integer: 2,
        BitString: 3,
        OctetString: 4,
        Null: 5,
        OID: 6,
        ObjectDescriptor: 7,
        External: 8,
        Real: 9,
        Enumeration: 10,
        PDV: 11,
        Utf8String: 12,
        RelativeOID: 13,
        Sequence: 16,
        Set: 17,
        NumericString: 18,
        PrintableString: 19,
        T61String: 20,
        VideotexString: 21,
        IA5String: 22,
        UTCTime: 23,
        GeneralizedTime: 24,
        GraphicString: 25,
        VisibleString: 26,
        GeneralString: 28,
        UniversalString: 29,
        CharacterString: 30,
        BMPString: 31,
        Constructor: 32,
        Context: 128
    };
}
,
/* asn1/lib/ber/writer */ function _(require, module, exports) {
    // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
    var assert = require('assert');
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var ASN1 = require(50) /* ./types */;
    var errors = require(47) /* ./errors */;
    // --- Globals
    var newInvalidAsn1Error = errors.newInvalidAsn1Error;
    var DEFAULT_OPTS = {
        size: 1024,
        growthFactor: 8
    };
    // --- Helpers
    function merge(from, to) {
        assert.ok(from);
        assert.equal(typeof (from), 'object');
        assert.ok(to);
        assert.equal(typeof (to), 'object');
        var keys = Object.getOwnPropertyNames(from);
        keys.forEach(function (key) {
            if (to[key])
                return;
            var value = Object.getOwnPropertyDescriptor(from, key);
            Object.defineProperty(to, key, value);
        });
        return to;
    }
    // --- API
    function Writer(options) {
        options = merge(DEFAULT_OPTS, options || {});
        this._buf = Buffer.alloc(options.size || 1024);
        this._size = this._buf.length;
        this._offset = 0;
        this._options = options;
        // A list of offsets in the buffer where we need to insert
        // sequence tag/len pairs.
        this._seq = [];
    }
    Object.defineProperty(Writer.prototype, 'buffer', {
        get: function () {
            if (this._seq.length)
                throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');
            return (this._buf.slice(0, this._offset));
        }
    });
    Writer.prototype.writeByte = function (b) {
        if (typeof (b) !== 'number')
            throw new TypeError('argument must be a Number');
        this._ensure(1);
        this._buf[this._offset++] = b;
    };
    Writer.prototype.writeInt = function (i, tag) {
        if (typeof (i) !== 'number')
            throw new TypeError('argument must be a Number');
        if (typeof (tag) !== 'number')
            tag = ASN1.Integer;
        var sz = 4;
        while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
            (sz > 1)) {
            sz--;
            i <<= 8;
        }
        if (sz > 4)
            throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');
        this._ensure(2 + sz);
        this._buf[this._offset++] = tag;
        this._buf[this._offset++] = sz;
        while (sz-- > 0) {
            this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
            i <<= 8;
        }
    };
    Writer.prototype.writeNull = function () {
        this.writeByte(ASN1.Null);
        this.writeByte(0x00);
    };
    Writer.prototype.writeEnumeration = function (i, tag) {
        if (typeof (i) !== 'number')
            throw new TypeError('argument must be a Number');
        if (typeof (tag) !== 'number')
            tag = ASN1.Enumeration;
        return this.writeInt(i, tag);
    };
    Writer.prototype.writeBoolean = function (b, tag) {
        if (typeof (b) !== 'boolean')
            throw new TypeError('argument must be a Boolean');
        if (typeof (tag) !== 'number')
            tag = ASN1.Boolean;
        this._ensure(3);
        this._buf[this._offset++] = tag;
        this._buf[this._offset++] = 0x01;
        this._buf[this._offset++] = b ? 0xff : 0x00;
    };
    Writer.prototype.writeString = function (s, tag) {
        if (typeof (s) !== 'string')
            throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');
        if (typeof (tag) !== 'number')
            tag = ASN1.OctetString;
        var len = Buffer.byteLength(s);
        this.writeByte(tag);
        this.writeLength(len);
        if (len) {
            this._ensure(len);
            this._buf.write(s, this._offset);
            this._offset += len;
        }
    };
    Writer.prototype.writeBuffer = function (buf, tag) {
        if (typeof (tag) !== 'number')
            throw new TypeError('tag must be a number');
        if (!Buffer.isBuffer(buf))
            throw new TypeError('argument must be a buffer');
        this.writeByte(tag);
        this.writeLength(buf.length);
        this._ensure(buf.length);
        buf.copy(this._buf, this._offset, 0, buf.length);
        this._offset += buf.length;
    };
    Writer.prototype.writeStringArray = function (strings) {
        if ((!strings instanceof Array))
            throw new TypeError('argument must be an Array[String]');
        var self = this;
        strings.forEach(function (s) {
            self.writeString(s);
        });
    };
    // This is really to solve DER cases, but whatever for now
    Writer.prototype.writeOID = function (s, tag) {
        if (typeof (s) !== 'string')
            throw new TypeError('argument must be a string');
        if (typeof (tag) !== 'number')
            tag = ASN1.OID;
        if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
            throw new Error('argument is not a valid OID string');
        function encodeOctet(bytes, octet) {
            if (octet < 128) {
                bytes.push(octet);
            }
            else if (octet < 16384) {
                bytes.push((octet >>> 7) | 0x80);
                bytes.push(octet & 0x7F);
            }
            else if (octet < 2097152) {
                bytes.push((octet >>> 14) | 0x80);
                bytes.push(((octet >>> 7) | 0x80) & 0xFF);
                bytes.push(octet & 0x7F);
            }
            else if (octet < 268435456) {
                bytes.push((octet >>> 21) | 0x80);
                bytes.push(((octet >>> 14) | 0x80) & 0xFF);
                bytes.push(((octet >>> 7) | 0x80) & 0xFF);
                bytes.push(octet & 0x7F);
            }
            else {
                bytes.push(((octet >>> 28) | 0x80) & 0xFF);
                bytes.push(((octet >>> 21) | 0x80) & 0xFF);
                bytes.push(((octet >>> 14) | 0x80) & 0xFF);
                bytes.push(((octet >>> 7) | 0x80) & 0xFF);
                bytes.push(octet & 0x7F);
            }
        }
        var tmp = s.split('.');
        var bytes = [];
        bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
        tmp.slice(2).forEach(function (b) {
            encodeOctet(bytes, parseInt(b, 10));
        });
        var self = this;
        this._ensure(2 + bytes.length);
        this.writeByte(tag);
        this.writeLength(bytes.length);
        bytes.forEach(function (b) {
            self.writeByte(b);
        });
    };
    Writer.prototype.writeLength = function (len) {
        if (typeof (len) !== 'number')
            throw new TypeError('argument must be a Number');
        this._ensure(4);
        if (len <= 0x7f) {
            this._buf[this._offset++] = len;
        }
        else if (len <= 0xff) {
            this._buf[this._offset++] = 0x81;
            this._buf[this._offset++] = len;
        }
        else if (len <= 0xffff) {
            this._buf[this._offset++] = 0x82;
            this._buf[this._offset++] = len >> 8;
            this._buf[this._offset++] = len;
        }
        else if (len <= 0xffffff) {
            this._buf[this._offset++] = 0x83;
            this._buf[this._offset++] = len >> 16;
            this._buf[this._offset++] = len >> 8;
            this._buf[this._offset++] = len;
        }
        else {
            throw newInvalidAsn1Error('Length too long (> 4 bytes)');
        }
    };
    Writer.prototype.startSequence = function (tag) {
        if (typeof (tag) !== 'number')
            tag = ASN1.Sequence | ASN1.Constructor;
        this.writeByte(tag);
        this._seq.push(this._offset);
        this._ensure(3);
        this._offset += 3;
    };
    Writer.prototype.endSequence = function () {
        var seq = this._seq.pop();
        var start = seq + 3;
        var len = this._offset - start;
        if (len <= 0x7f) {
            this._shift(start, len, -2);
            this._buf[seq] = len;
        }
        else if (len <= 0xff) {
            this._shift(start, len, -1);
            this._buf[seq] = 0x81;
            this._buf[seq + 1] = len;
        }
        else if (len <= 0xffff) {
            this._buf[seq] = 0x82;
            this._buf[seq + 1] = len >> 8;
            this._buf[seq + 2] = len;
        }
        else if (len <= 0xffffff) {
            this._shift(start, len, 1);
            this._buf[seq] = 0x83;
            this._buf[seq + 1] = len >> 16;
            this._buf[seq + 2] = len >> 8;
            this._buf[seq + 3] = len;
        }
        else {
            throw newInvalidAsn1Error('Sequence too long');
        }
    };
    Writer.prototype._shift = function (start, len, shift) {
        assert.ok(start !== undefined);
        assert.ok(len !== undefined);
        assert.ok(shift);
        this._buf.copy(this._buf, start + shift, start, start + len);
        this._offset += shift;
    };
    Writer.prototype._ensure = function (len) {
        assert.ok(len);
        if (this._size - this._offset < len) {
            var sz = this._size * this._options.growthFactor;
            if (sz - this._offset < len)
                sz += len;
            var buf = Buffer.alloc(sz);
            this._buf.copy(buf, 0, 0, this._offset);
            this._buf = buf;
            this._size = sz;
        }
    };
    // --- Exported API
    module.exports = Writer;
}
,
/* asn1/lib/index */ function _(require, module, exports) {
    // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
    // If you have no idea what ASN.1 or BER is, see this:
    // ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
    var Ber = require(48) /* ./ber/index */;
    // --- Exported API
    module.exports = {
        Ber: Ber,
        BerReader: Ber.Reader,
        BerWriter: Ber.Writer
    };
}
,
/* assert-plus/assert */ function _(require, module, exports) {
    // Copyright (c) 2012, Mark Cavage. All rights reserved.
    // Copyright 2015 Joyent, Inc.
    var assert = require('assert');
    var Stream = require('stream').Stream;
    var util = require('util');
    ///--- Globals
    /* JSSTYLED */
    var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
    ///--- Internal
    function _capitalize(str) {
        return (str.charAt(0).toUpperCase() + str.slice(1));
    }
    function _toss(name, expected, oper, arg, actual) {
        throw new assert.AssertionError({
            message: util.format('%s (%s) is required', name, expected),
            actual: (actual === undefined) ? typeof (arg) : actual(arg),
            expected: expected,
            operator: oper || '===',
            stackStartFunction: _toss.caller
        });
    }
    function _getClass(arg) {
        return (Object.prototype.toString.call(arg).slice(8, -1));
    }
    function noop() {
        // Why even bother with asserts?
    }
    ///--- Exports
    var types = {
        bool: {
            check: function (arg) { return typeof (arg) === 'boolean'; }
        },
        func: {
            check: function (arg) { return typeof (arg) === 'function'; }
        },
        string: {
            check: function (arg) { return typeof (arg) === 'string'; }
        },
        object: {
            check: function (arg) {
                return typeof (arg) === 'object' && arg !== null;
            }
        },
        number: {
            check: function (arg) {
                return typeof (arg) === 'number' && !isNaN(arg);
            }
        },
        finite: {
            check: function (arg) {
                return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
            }
        },
        buffer: {
            check: function (arg) { return Buffer.isBuffer(arg); },
            operator: 'Buffer.isBuffer'
        },
        array: {
            check: function (arg) { return Array.isArray(arg); },
            operator: 'Array.isArray'
        },
        stream: {
            check: function (arg) { return arg instanceof Stream; },
            operator: 'instanceof',
            actual: _getClass
        },
        date: {
            check: function (arg) { return arg instanceof Date; },
            operator: 'instanceof',
            actual: _getClass
        },
        regexp: {
            check: function (arg) { return arg instanceof RegExp; },
            operator: 'instanceof',
            actual: _getClass
        },
        uuid: {
            check: function (arg) {
                return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
            },
            operator: 'isUUID'
        }
    };
    function _setExports(ndebug) {
        var keys = Object.keys(types);
        var out;
        /* re-export standard assert */
        if (process.env.NODE_NDEBUG) {
            out = noop;
        }
        else {
            out = function (arg, msg) {
                if (!arg) {
                    _toss(msg, 'true', arg);
                }
            };
        }
        /* standard checks */
        keys.forEach(function (k) {
            if (ndebug) {
                out[k] = noop;
                return;
            }
            var type = types[k];
            out[k] = function (arg, msg) {
                if (!type.check(arg)) {
                    _toss(msg, k, type.operator, arg, type.actual);
                }
            };
        });
        /* optional checks */
        keys.forEach(function (k) {
            var name = 'optional' + _capitalize(k);
            if (ndebug) {
                out[name] = noop;
                return;
            }
            var type = types[k];
            out[name] = function (arg, msg) {
                if (arg === undefined || arg === null) {
                    return;
                }
                if (!type.check(arg)) {
                    _toss(msg, k, type.operator, arg, type.actual);
                }
            };
        });
        /* arrayOf checks */
        keys.forEach(function (k) {
            var name = 'arrayOf' + _capitalize(k);
            if (ndebug) {
                out[name] = noop;
                return;
            }
            var type = types[k];
            var expected = '[' + k + ']';
            out[name] = function (arg, msg) {
                if (!Array.isArray(arg)) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
                var i;
                for (i = 0; i < arg.length; i++) {
                    if (!type.check(arg[i])) {
                        _toss(msg, expected, type.operator, arg, type.actual);
                    }
                }
            };
        });
        /* optionalArrayOf checks */
        keys.forEach(function (k) {
            var name = 'optionalArrayOf' + _capitalize(k);
            if (ndebug) {
                out[name] = noop;
                return;
            }
            var type = types[k];
            var expected = '[' + k + ']';
            out[name] = function (arg, msg) {
                if (arg === undefined || arg === null) {
                    return;
                }
                if (!Array.isArray(arg)) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
                var i;
                for (i = 0; i < arg.length; i++) {
                    if (!type.check(arg[i])) {
                        _toss(msg, expected, type.operator, arg, type.actual);
                    }
                }
            };
        });
        /* re-export built-in assertions */
        Object.keys(assert).forEach(function (k) {
            if (k === 'AssertionError') {
                out[k] = assert[k];
                return;
            }
            if (ndebug) {
                out[k] = noop;
                return;
            }
            out[k] = assert[k];
        });
        /* export ourselves (for unit tests _only_) */
        out._setExports = _setExports;
        return out;
    }
    module.exports = _setExports(process.env.NODE_NDEBUG);
}
,
/* asynckit/index */ function _(require, module, exports) {
    module.exports =
        {
            parallel: require(61) /* ./parallel.js */,
            serial: require(62) /* ./serial.js */,
            serialOrdered: require(63) /* ./serialOrdered.js */
        };
}
,
/* asynckit/lib/abort */ function _(require, module, exports) {
    // API
    module.exports = abort;
    /**
     * Aborts leftover active jobs
     *
     * @param {object} state - current state object
     */
    function abort(state) {
        Object.keys(state.jobs).forEach(clean.bind(state));
        // reset leftover jobs
        state.jobs = {};
    }
    /**
     * Cleans up leftover job by invoking abort function for the provided job id
     *
     * @this  state
     * @param {string|number} key - job id to abort
     */
    function clean(key) {
        if (typeof this.jobs[key] == 'function') {
            this.jobs[key]();
        }
    }
}
,
/* asynckit/lib/async */ function _(require, module, exports) {
    var defer = require(57) /* ./defer.js */;
    // API
    module.exports = async;
    /**
     * Runs provided callback asynchronously
     * even if callback itself is not
     *
     * @param   {function} callback - callback to invoke
     * @returns {function} - augmented callback
     */
    function async(callback) {
        var isAsync = false;
        // check if async happened
        defer(function () { isAsync = true; });
        return function async_callback(err, result) {
            if (isAsync) {
                callback(err, result);
            }
            else {
                defer(function nextTick_callback() {
                    callback(err, result);
                });
            }
        };
    }
}
,
/* asynckit/lib/defer */ function _(require, module, exports) {
    module.exports = defer;
    /**
     * Runs provided function on next iteration of the event loop
     *
     * @param {function} fn - function to run
     */
    function defer(fn) {
        var nextTick = typeof setImmediate == 'function'
            ? setImmediate
            : (typeof process == 'object' && typeof process.nextTick == 'function'
                ? process.nextTick
                : null);
        if (nextTick) {
            nextTick(fn);
        }
        else {
            setTimeout(fn, 0);
        }
    }
}
,
/* asynckit/lib/iterate */ function _(require, module, exports) {
    var async = require(56) /* ./async.js */, abort = require(55) /* ./abort.js */;
    // API
    module.exports = iterate;
    /**
     * Iterates over each job object
     *
     * @param {array|object} list - array or object (named list) to iterate over
     * @param {function} iterator - iterator to run
     * @param {object} state - current job status
     * @param {function} callback - invoked when all elements processed
     */
    function iterate(list, iterator, state, callback) {
        // store current index
        var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
        state.jobs[key] = runJob(iterator, key, list[key], function (error, output) {
            // don't repeat yourself
            // skip secondary callbacks
            if (!(key in state.jobs)) {
                return;
            }
            // clean up jobs
            delete state.jobs[key];
            if (error) {
                // don't process rest of the results
                // stop still active jobs
                // and reset the list
                abort(state);
            }
            else {
                state.results[key] = output;
            }
            // return salvaged results
            callback(error, state.results);
        });
    }
    /**
     * Runs iterator over provided job element
     *
     * @param   {function} iterator - iterator to invoke
     * @param   {string|number} key - key/index of the element in the list of jobs
     * @param   {mixed} item - job description
     * @param   {function} callback - invoked after iterator is done with the job
     * @returns {function|mixed} - job abort function or something else
     */
    function runJob(iterator, key, item, callback) {
        var aborter;
        // allow shortcut if iterator expects only two arguments
        if (iterator.length == 2) {
            aborter = iterator(item, async(callback));
        }
        // otherwise go with full three arguments
        else {
            aborter = iterator(item, key, async(callback));
        }
        return aborter;
    }
}
,
/* asynckit/lib/state */ function _(require, module, exports) {
    // API
    module.exports = state;
    /**
     * Creates initial state object
     * for iteration over list
     *
     * @param   {array|object} list - list to iterate over
     * @param   {function|null} sortMethod - function to use for keys sort,
     *                                     or `null` to keep them as is
     * @returns {object} - initial state object
     */
    function state(list, sortMethod) {
        var isNamedList = !Array.isArray(list), initState = {
            index: 0,
            keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
            jobs: {},
            results: isNamedList ? {} : [],
            size: isNamedList ? Object.keys(list).length : list.length
        };
        if (sortMethod) {
            // sort array keys based on it's values
            // sort object's keys just on own merit
            initState.keyedList.sort(isNamedList ? sortMethod : function (a, b) {
                return sortMethod(list[a], list[b]);
            });
        }
        return initState;
    }
}
,
/* asynckit/lib/terminator */ function _(require, module, exports) {
    var abort = require(55) /* ./abort.js */, async = require(56) /* ./async.js */;
    // API
    module.exports = terminator;
    /**
     * Terminates jobs in the attached state context
     *
     * @this  AsyncKitState#
     * @param {function} callback - final callback to invoke after termination
     */
    function terminator(callback) {
        if (!Object.keys(this.jobs).length) {
            return;
        }
        // fast forward iteration index
        this.index = this.size;
        // abort jobs
        abort(this);
        // send back results we have so far
        async(callback)(null, this.results);
    }
}
,
/* asynckit/parallel */ function _(require, module, exports) {
    var iterate = require(58) /* ./lib/iterate.js */, initState = require(59) /* ./lib/state.js */, terminator = require(60) /* ./lib/terminator.js */;
    // Public API
    module.exports = parallel;
    /**
     * Runs iterator over provided array elements in parallel
     *
     * @param   {array|object} list - array or object (named list) to iterate over
     * @param   {function} iterator - iterator to run
     * @param   {function} callback - invoked when all elements processed
     * @returns {function} - jobs terminator
     */
    function parallel(list, iterator, callback) {
        var state = initState(list);
        while (state.index < (state['keyedList'] || list).length) {
            iterate(list, iterator, state, function (error, result) {
                if (error) {
                    callback(error, result);
                    return;
                }
                // looks like it's the last one
                if (Object.keys(state.jobs).length === 0) {
                    callback(null, state.results);
                    return;
                }
            });
            state.index++;
        }
        return terminator.bind(state, callback);
    }
}
,
/* asynckit/serial */ function _(require, module, exports) {
    var serialOrdered = require(63) /* ./serialOrdered.js */;
    // Public API
    module.exports = serial;
    /**
     * Runs iterator over provided array elements in series
     *
     * @param   {array|object} list - array or object (named list) to iterate over
     * @param   {function} iterator - iterator to run
     * @param   {function} callback - invoked when all elements processed
     * @returns {function} - jobs terminator
     */
    function serial(list, iterator, callback) {
        return serialOrdered(list, iterator, null, callback);
    }
}
,
/* asynckit/serialOrdered */ function _(require, module, exports) {
    var iterate = require(58) /* ./lib/iterate.js */, initState = require(59) /* ./lib/state.js */, terminator = require(60) /* ./lib/terminator.js */;
    // Public API
    module.exports = serialOrdered;
    // sorting helpers
    module.exports.ascending = ascending;
    module.exports.descending = descending;
    /**
     * Runs iterator over provided sorted array elements in series
     *
     * @param   {array|object} list - array or object (named list) to iterate over
     * @param   {function} iterator - iterator to run
     * @param   {function} sortMethod - custom sort function
     * @param   {function} callback - invoked when all elements processed
     * @returns {function} - jobs terminator
     */
    function serialOrdered(list, iterator, sortMethod, callback) {
        var state = initState(list, sortMethod);
        iterate(list, iterator, state, function iteratorHandler(error, result) {
            if (error) {
                callback(error, result);
                return;
            }
            state.index++;
            // are we there yet?
            if (state.index < (state['keyedList'] || list).length) {
                iterate(list, iterator, state, iteratorHandler);
                return;
            }
            // done here
            callback(null, state.results);
        });
        return terminator.bind(state, callback);
    }
    /*
     * -- Sort methods
     */
    /**
     * sort helper to sort array elements in ascending order
     *
     * @param   {mixed} a - an item to compare
     * @param   {mixed} b - an item to compare
     * @returns {number} - comparison result
     */
    function ascending(a, b) {
        return a < b ? -1 : a > b ? 1 : 0;
    }
    /**
     * sort helper to sort array elements in descending order
     *
     * @param   {mixed} a - an item to compare
     * @param   {mixed} b - an item to compare
     * @returns {number} - comparison result
     */
    function descending(a, b) {
        return -1 * ascending(a, b);
    }
}
,
/* aws-sign2/index */ function _(require, module, exports) {
    /*!
     *  Copyright 2010 LearnBoost <dev@learnboost.com>
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    /**
     * Module dependencies.
     */
    var crypto = require('crypto'), parse = require('url').parse;
    /**
     * Valid keys.
     */
    var keys = ['acl',
        'location',
        'logging',
        'notification',
        'partNumber',
        'policy',
        'requestPayment',
        'torrent',
        'uploadId',
        'uploads',
        'versionId',
        'versioning',
        'versions',
        'website'
    ];
    /**
     * Return an "Authorization" header value with the given `options`
     * in the form of "AWS <key>:<signature>"
     *
     * @param {Object} options
     * @return {String}
     * @api private
     */
    function authorization(options) {
        return 'AWS ' + options.key + ':' + sign(options);
    }
    module.exports = authorization;
    module.exports.authorization = authorization;
    /**
     * Simple HMAC-SHA1 Wrapper
     *
     * @param {Object} options
     * @return {String}
     * @api private
     */
    function hmacSha1(options) {
        return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64');
    }
    module.exports.hmacSha1 = hmacSha1;
    /**
     * Create a base64 sha1 HMAC for `options`.
     *
     * @param {Object} options
     * @return {String}
     * @api private
     */
    function sign(options) {
        options.message = stringToSign(options);
        return hmacSha1(options);
    }
    module.exports.sign = sign;
    /**
     * Create a base64 sha1 HMAC for `options`.
     *
     * Specifically to be used with S3 presigned URLs
     *
     * @param {Object} options
     * @return {String}
     * @api private
     */
    function signQuery(options) {
        options.message = queryStringToSign(options);
        return hmacSha1(options);
    }
    module.exports.signQuery = signQuery;
    /**
     * Return a string for sign() with the given `options`.
     *
     * Spec:
     *
     *    <verb>\n
     *    <md5>\n
     *    <content-type>\n
     *    <date>\n
     *    [headers\n]
     *    <resource>
     *
     * @param {Object} options
     * @return {String}
     * @api private
     */
    function stringToSign(options) {
        var headers = options.amazonHeaders || '';
        if (headers)
            headers += '\n';
        var r = [options.verb,
            options.md5,
            options.contentType,
            options.date ? options.date.toUTCString() : '',
            headers + options.resource
        ];
        return r.join('\n');
    }
    module.exports.stringToSign = stringToSign;
    /**
     * Return a string for sign() with the given `options`, but is meant exclusively
     * for S3 presigned URLs
     *
     * Spec:
     *
     *    <date>\n
     *    <resource>
     *
     * @param {Object} options
     * @return {String}
     * @api private
     */
    function queryStringToSign(options) {
        return 'GET\n\n\n' + options.date + '\n' + options.resource;
    }
    module.exports.queryStringToSign = queryStringToSign;
    /**
     * Perform the following:
     *
     *  - ignore non-amazon headers
     *  - lowercase fields
     *  - sort lexicographically
     *  - trim whitespace between ":"
     *  - join with newline
     *
     * @param {Object} headers
     * @return {String}
     * @api private
     */
    function canonicalizeHeaders(headers) {
        var buf = [], fields = Object.keys(headers);
        for (var i = 0, len = fields.length; i < len; ++i) {
            var field = fields[i], val = headers[field], field = field.toLowerCase();
            if (0 !== field.indexOf('x-amz'))
                continue;
            buf.push(field + ':' + val);
        }
        return buf.sort().join('\n');
    }
    module.exports.canonicalizeHeaders = canonicalizeHeaders;
    /**
     * Perform the following:
     *
     *  - ignore non sub-resources
     *  - sort lexicographically
     *
     * @param {String} resource
     * @return {String}
     * @api private
     */
    function canonicalizeResource(resource) {
        var url = parse(resource, true), path = url.pathname, buf = [];
        Object.keys(url.query).forEach(function (key) {
            if (!~keys.indexOf(key))
                return;
            var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]);
            buf.push(key + val);
        });
        return path + (buf.length ? '?' + buf.sort().join('&') : '');
    }
    module.exports.canonicalizeResource = canonicalizeResource;
}
,
/* aws4/aws4 */ function _(require, module, exports) {
    var aws4 = exports, url = require('url'), querystring = require('querystring'), crypto = require('crypto'), lru = require(66) /* ./lru */, credentialsCache = lru(1000);
    // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
    function hmac(key, string, encoding) {
        return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding);
    }
    function hash(string, encoding) {
        return crypto.createHash('sha256').update(string, 'utf8').digest(encoding);
    }
    // This function assumes the string has already been percent encoded
    function encodeRfc3986(urlEncodedString) {
        return urlEncodedString.replace(/[!'()*]/g, function (c) {
            return '%' + c.charCodeAt(0).toString(16).toUpperCase();
        });
    }
    // request: { path | body, [host], [method], [headers], [service], [region] }
    // credentials: { accessKeyId, secretAccessKey, [sessionToken] }
    function RequestSigner(request, credentials) {
        if (typeof request === 'string')
            request = url.parse(request);
        var headers = request.headers = (request.headers || {}), hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host);
        this.request = request;
        this.credentials = credentials || this.defaultCredentials();
        this.service = request.service || hostParts[0] || '';
        this.region = request.region || hostParts[1] || 'us-east-1';
        // SES uses a different domain from the service name
        if (this.service === 'email')
            this.service = 'ses';
        if (!request.method && request.body)
            request.method = 'POST';
        if (!headers.Host && !headers.host) {
            headers.Host = request.hostname || request.host || this.createHost();
            // If a port is specified explicitly, use it as is
            if (request.port)
                headers.Host += ':' + request.port;
        }
        if (!request.hostname && !request.host)
            request.hostname = headers.Host || headers.host;
        this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT';
    }
    RequestSigner.prototype.matchHost = function (host) {
        var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/);
        var hostParts = (match || []).slice(1, 3);
        // ES's hostParts are sometimes the other way round, if the value that is expected
        // to be region equals ‘es’ switch them back
        // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
        if (hostParts[1] === 'es')
            hostParts = hostParts.reverse();
        return hostParts;
    };
    // http://docs.aws.amazon.com/general/latest/gr/rande.html
    RequestSigner.prototype.isSingleRegion = function () {
        // Special case for S3 and SimpleDB in us-east-1
        if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1')
            return true;
        return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
            .indexOf(this.service) >= 0;
    };
    RequestSigner.prototype.createHost = function () {
        var region = this.isSingleRegion() ? '' :
            (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region, service = this.service === 'ses' ? 'email' : this.service;
        return service + region + '.amazonaws.com';
    };
    RequestSigner.prototype.prepareRequest = function () {
        this.parsePath();
        var request = this.request, headers = request.headers, query;
        if (request.signQuery) {
            this.parsedPath.query = query = this.parsedPath.query || {};
            if (this.credentials.sessionToken)
                query['X-Amz-Security-Token'] = this.credentials.sessionToken;
            if (this.service === 's3' && !query['X-Amz-Expires'])
                query['X-Amz-Expires'] = 86400;
            if (query['X-Amz-Date'])
                this.datetime = query['X-Amz-Date'];
            else
                query['X-Amz-Date'] = this.getDateTime();
            query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
            query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString();
            query['X-Amz-SignedHeaders'] = this.signedHeaders();
        }
        else {
            if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
                if (request.body && !headers['Content-Type'] && !headers['content-type'])
                    headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
                if (request.body && !headers['Content-Length'] && !headers['content-length'])
                    headers['Content-Length'] = Buffer.byteLength(request.body);
                if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
                    headers['X-Amz-Security-Token'] = this.credentials.sessionToken;
                if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
                    headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex');
                if (headers['X-Amz-Date'] || headers['x-amz-date'])
                    this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'];
                else
                    headers['X-Amz-Date'] = this.getDateTime();
            }
            delete headers.Authorization;
            delete headers.authorization;
        }
    };
    RequestSigner.prototype.sign = function () {
        if (!this.parsedPath)
            this.prepareRequest();
        if (this.request.signQuery) {
            this.parsedPath.query['X-Amz-Signature'] = this.signature();
        }
        else {
            this.request.headers.Authorization = this.authHeader();
        }
        this.request.path = this.formatPath();
        return this.request;
    };
    RequestSigner.prototype.getDateTime = function () {
        if (!this.datetime) {
            var headers = this.request.headers, date = new Date(headers.Date || headers.date || new Date);
            this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '');
            // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
            if (this.isCodeCommitGit)
                this.datetime = this.datetime.slice(0, -1);
        }
        return this.datetime;
    };
    RequestSigner.prototype.getDate = function () {
        return this.getDateTime().substr(0, 8);
    };
    RequestSigner.prototype.authHeader = function () {
        return [
            'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
            'SignedHeaders=' + this.signedHeaders(),
            'Signature=' + this.signature(),
        ].join(', ');
    };
    RequestSigner.prototype.signature = function () {
        var date = this.getDate(), cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey);
        if (!kCredentials) {
            kDate = hmac('AWS4' + this.credentials.secretAccessKey, date);
            kRegion = hmac(kDate, this.region);
            kService = hmac(kRegion, this.service);
            kCredentials = hmac(kService, 'aws4_request');
            credentialsCache.set(cacheKey, kCredentials);
        }
        return hmac(kCredentials, this.stringToSign(), 'hex');
    };
    RequestSigner.prototype.stringToSign = function () {
        return [
            'AWS4-HMAC-SHA256',
            this.getDateTime(),
            this.credentialString(),
            hash(this.canonicalString(), 'hex'),
        ].join('\n');
    };
    RequestSigner.prototype.canonicalString = function () {
        if (!this.parsedPath)
            this.prepareRequest();
        var pathStr = this.parsedPath.path, query = this.parsedPath.query, headers = this.request.headers, queryStr = '', normalizePath = this.service !== 's3', decodePath = this.service === 's3' || this.request.doNotEncodePath, decodeSlashesInPath = this.service === 's3', firstValOnly = this.service === 's3', bodyHash;
        if (this.service === 's3' && this.request.signQuery) {
            bodyHash = 'UNSIGNED-PAYLOAD';
        }
        else if (this.isCodeCommitGit) {
            bodyHash = '';
        }
        else {
            bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
                hash(this.request.body || '', 'hex');
        }
        if (query) {
            queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function (obj, key) {
                if (!key)
                    return obj;
                obj[key] = !Array.isArray(query[key]) ? query[key] :
                    (firstValOnly ? query[key][0] : query[key].slice().sort());
                return obj;
            }, {})));
        }
        if (pathStr !== '/') {
            if (normalizePath)
                pathStr = pathStr.replace(/\/{2,}/g, '/');
            pathStr = pathStr.split('/').reduce(function (path, piece) {
                if (normalizePath && piece === '..') {
                    path.pop();
                }
                else if (!normalizePath || piece !== '.') {
                    if (decodePath)
                        piece = decodeURIComponent(piece);
                    path.push(encodeRfc3986(encodeURIComponent(piece)));
                }
                return path;
            }, []).join('/');
            if (pathStr[0] !== '/')
                pathStr = '/' + pathStr;
            if (decodeSlashesInPath)
                pathStr = pathStr.replace(/%2F/g, '/');
        }
        return [
            this.request.method || 'GET',
            pathStr,
            queryStr,
            this.canonicalHeaders() + '\n',
            this.signedHeaders(),
            bodyHash,
        ].join('\n');
    };
    RequestSigner.prototype.canonicalHeaders = function () {
        var headers = this.request.headers;
        function trimAll(header) {
            return header.toString().trim().replace(/\s+/g, ' ');
        }
        return Object.keys(headers)
            .sort(function (a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; })
            .map(function (key) { return key.toLowerCase() + ':' + trimAll(headers[key]); })
            .join('\n');
    };
    RequestSigner.prototype.signedHeaders = function () {
        return Object.keys(this.request.headers)
            .map(function (key) { return key.toLowerCase(); })
            .sort()
            .join(';');
    };
    RequestSigner.prototype.credentialString = function () {
        return [
            this.getDate(),
            this.region,
            this.service,
            'aws4_request',
        ].join('/');
    };
    RequestSigner.prototype.defaultCredentials = function () {
        var env = process.env;
        return {
            accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
            secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
            sessionToken: env.AWS_SESSION_TOKEN,
        };
    };
    RequestSigner.prototype.parsePath = function () {
        var path = this.request.path || '/', queryIx = path.indexOf('?'), query = null;
        if (queryIx >= 0) {
            query = querystring.parse(path.slice(queryIx + 1));
            path = path.slice(0, queryIx);
        }
        // S3 doesn't always encode characters > 127 correctly and
        // all services don't encode characters > 255 correctly
        // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
        if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
            path = path.split('/').map(function (piece) {
                return encodeURIComponent(decodeURIComponent(piece));
            }).join('/');
        }
        this.parsedPath = {
            path: path,
            query: query,
        };
    };
    RequestSigner.prototype.formatPath = function () {
        var path = this.parsedPath.path, query = this.parsedPath.query;
        if (!query)
            return path;
        // Services don't support empty query string keys
        if (query[''] != null)
            delete query[''];
        return path + '?' + encodeRfc3986(querystring.stringify(query));
    };
    aws4.RequestSigner = RequestSigner;
    aws4.sign = function (request, credentials) {
        return new RequestSigner(request, credentials).sign();
    };
}
,
/* aws4/lru */ function _(require, module, exports) {
    module.exports = function (size) {
        return new LruCache(size);
    };
    function LruCache(size) {
        this.capacity = size | 0;
        this.map = Object.create(null);
        this.list = new DoublyLinkedList();
    }
    LruCache.prototype.get = function (key) {
        var node = this.map[key];
        if (node == null)
            return undefined;
        this.used(node);
        return node.val;
    };
    LruCache.prototype.set = function (key, val) {
        var node = this.map[key];
        if (node != null) {
            node.val = val;
        }
        else {
            if (!this.capacity)
                this.prune();
            if (!this.capacity)
                return false;
            node = new DoublyLinkedNode(key, val);
            this.map[key] = node;
            this.capacity--;
        }
        this.used(node);
        return true;
    };
    LruCache.prototype.used = function (node) {
        this.list.moveToFront(node);
    };
    LruCache.prototype.prune = function () {
        var node = this.list.pop();
        if (node != null) {
            delete this.map[node.key];
            this.capacity++;
        }
    };
    function DoublyLinkedList() {
        this.firstNode = null;
        this.lastNode = null;
    }
    DoublyLinkedList.prototype.moveToFront = function (node) {
        if (this.firstNode == node)
            return;
        this.remove(node);
        if (this.firstNode == null) {
            this.firstNode = node;
            this.lastNode = node;
            node.prev = null;
            node.next = null;
        }
        else {
            node.prev = null;
            node.next = this.firstNode;
            node.next.prev = node;
            this.firstNode = node;
        }
    };
    DoublyLinkedList.prototype.pop = function () {
        var lastNode = this.lastNode;
        if (lastNode != null) {
            this.remove(lastNode);
        }
        return lastNode;
    };
    DoublyLinkedList.prototype.remove = function (node) {
        if (this.firstNode == node) {
            this.firstNode = node.next;
        }
        else if (node.prev != null) {
            node.prev.next = node.next;
        }
        if (this.lastNode == node) {
            this.lastNode = node.prev;
        }
        else if (node.next != null) {
            node.next.prev = node.prev;
        }
    };
    function DoublyLinkedNode(key, val) {
        this.key = key;
        this.val = val;
        this.prev = null;
        this.next = null;
    }
}
,
/* bcrypt-pbkdf/index */ function _(require, module, exports) {
    var crypto_hash_sha512 = require(366) /* tweetnacl */.lowlevel.crypto_hash;
    /*
     * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a
     * result, it retains the original copyright and license. The two files are
     * under slightly different (but compatible) licenses, and are here combined in
     * one file.
     *
     * Credit for the actual porting work goes to:
     *  Devi Mandiri <me@devi.web.id>
     */
    /*
     * The Blowfish portions are under the following license:
     *
     * Blowfish block cipher for OpenBSD
     * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
     * All rights reserved.
     *
     * Implementation advice by David Mazieres <dm@lcs.mit.edu>.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     * 1. Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     * 2. 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.
     * 3. The name of the author may not be used to endorse or promote products
     *    derived from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
     */
    /*
     * The bcrypt_pbkdf portions are under the following license:
     *
     * Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
     *
     * Permission to use, copy, modify, and distribute this software for any
     * purpose with or without fee is hereby granted, provided that the above
     * copyright notice and this permission notice appear in all copies.
     *
     * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     */
    /*
     * Performance improvements (Javascript-specific):
     *
     * Copyright 2016, Joyent Inc
     * Author: Alex Wilson <alex.wilson@joyent.com>
     *
     * Permission to use, copy, modify, and distribute this software for any
     * purpose with or without fee is hereby granted, provided that the above
     * copyright notice and this permission notice appear in all copies.
     *
     * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     */
    // Ported from OpenBSD bcrypt_pbkdf.c v1.9
    var BLF_J = 0;
    var Blowfish = function () {
        this.S = [
            new Uint32Array([
                0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
                0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
                0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
                0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
                0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
                0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
                0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
                0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
                0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
                0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
                0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
                0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
                0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
                0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
                0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
                0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
                0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
                0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
                0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
                0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
                0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
                0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
                0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
                0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
                0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
                0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
                0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
                0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
                0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
                0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
                0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
                0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
                0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
                0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
                0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
                0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
                0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
                0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
                0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
                0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
                0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
                0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
                0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
                0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
                0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
                0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
                0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
                0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
                0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
                0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
                0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
                0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
                0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
                0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
                0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
                0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
                0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
                0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
                0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
                0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
                0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
                0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
                0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
                0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
            ]),
            new Uint32Array([
                0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
                0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
                0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
                0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
                0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
                0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
                0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
                0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
                0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
                0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
                0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
                0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
                0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
                0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
                0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
                0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
                0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
                0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
                0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
                0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
                0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
                0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
                0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
                0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
                0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
                0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
                0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
                0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
                0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
                0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
                0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
                0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
                0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
                0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
                0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
                0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
                0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
                0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
                0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
                0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
                0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
                0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
                0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
                0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
                0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
                0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
                0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
                0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
                0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
                0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
                0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
                0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
                0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
                0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
                0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
                0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
                0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
                0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
                0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
                0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
                0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
                0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
                0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
                0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
            ]),
            new Uint32Array([
                0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
                0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
                0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
                0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
                0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
                0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
                0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
                0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
                0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
                0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
                0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
                0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
                0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
                0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
                0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
                0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
                0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
                0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
                0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
                0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
                0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
                0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
                0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
                0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
                0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
                0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
                0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
                0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
                0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
                0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
                0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
                0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
                0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
                0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
                0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
                0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
                0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
                0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
                0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
                0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
                0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
                0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
                0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
                0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
                0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
                0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
                0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
                0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
                0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
                0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
                0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
                0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
                0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
                0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
                0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
                0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
                0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
                0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
                0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
                0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
                0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
                0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
                0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
                0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
            ]),
            new Uint32Array([
                0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
                0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
                0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
                0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
                0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
                0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
                0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
                0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
                0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
                0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
                0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
                0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
                0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
                0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
                0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
                0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
                0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
                0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
                0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
                0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
                0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
                0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
                0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
                0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
                0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
                0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
                0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
                0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
                0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
                0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
                0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
                0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
                0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
                0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
                0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
                0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
                0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
                0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
                0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
                0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
                0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
                0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
                0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
                0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
                0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
                0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
                0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
                0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
                0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
                0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
                0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
                0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
                0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
                0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
                0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
                0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
                0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
                0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
                0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
                0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
                0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
                0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
                0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
                0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
            ])
        ];
        this.P = new Uint32Array([
            0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
            0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
            0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
            0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
            0x9216d5d9, 0x8979fb1b
        ]);
    };
    function F(S, x8, i) {
        return (((S[0][x8[i + 3]] +
            S[1][x8[i + 2]]) ^
            S[2][x8[i + 1]]) +
            S[3][x8[i]]);
    }
    ;
    Blowfish.prototype.encipher = function (x, x8) {
        if (x8 === undefined) {
            x8 = new Uint8Array(x.buffer);
            if (x.byteOffset !== 0)
                x8 = x8.subarray(x.byteOffset);
        }
        x[0] ^= this.P[0];
        for (var i = 1; i < 16; i += 2) {
            x[1] ^= F(this.S, x8, 0) ^ this.P[i];
            x[0] ^= F(this.S, x8, 4) ^ this.P[i + 1];
        }
        var t = x[0];
        x[0] = x[1] ^ this.P[17];
        x[1] = t;
    };
    Blowfish.prototype.decipher = function (x) {
        var x8 = new Uint8Array(x.buffer);
        if (x.byteOffset !== 0)
            x8 = x8.subarray(x.byteOffset);
        x[0] ^= this.P[17];
        for (var i = 16; i > 0; i -= 2) {
            x[1] ^= F(this.S, x8, 0) ^ this.P[i];
            x[0] ^= F(this.S, x8, 4) ^ this.P[i - 1];
        }
        var t = x[0];
        x[0] = x[1] ^ this.P[0];
        x[1] = t;
    };
    function stream2word(data, databytes) {
        var i, temp = 0;
        for (i = 0; i < 4; i++, BLF_J++) {
            if (BLF_J >= databytes)
                BLF_J = 0;
            temp = (temp << 8) | data[BLF_J];
        }
        return temp;
    }
    ;
    Blowfish.prototype.expand0state = function (key, keybytes) {
        var d = new Uint32Array(2), i, k;
        var d8 = new Uint8Array(d.buffer);
        for (i = 0, BLF_J = 0; i < 18; i++) {
            this.P[i] ^= stream2word(key, keybytes);
        }
        BLF_J = 0;
        for (i = 0; i < 18; i += 2) {
            this.encipher(d, d8);
            this.P[i] = d[0];
            this.P[i + 1] = d[1];
        }
        for (i = 0; i < 4; i++) {
            for (k = 0; k < 256; k += 2) {
                this.encipher(d, d8);
                this.S[i][k] = d[0];
                this.S[i][k + 1] = d[1];
            }
        }
    };
    Blowfish.prototype.expandstate = function (data, databytes, key, keybytes) {
        var d = new Uint32Array(2), i, k;
        for (i = 0, BLF_J = 0; i < 18; i++) {
            this.P[i] ^= stream2word(key, keybytes);
        }
        for (i = 0, BLF_J = 0; i < 18; i += 2) {
            d[0] ^= stream2word(data, databytes);
            d[1] ^= stream2word(data, databytes);
            this.encipher(d);
            this.P[i] = d[0];
            this.P[i + 1] = d[1];
        }
        for (i = 0; i < 4; i++) {
            for (k = 0; k < 256; k += 2) {
                d[0] ^= stream2word(data, databytes);
                d[1] ^= stream2word(data, databytes);
                this.encipher(d);
                this.S[i][k] = d[0];
                this.S[i][k + 1] = d[1];
            }
        }
        BLF_J = 0;
    };
    Blowfish.prototype.enc = function (data, blocks) {
        for (var i = 0; i < blocks; i++) {
            this.encipher(data.subarray(i * 2));
        }
    };
    Blowfish.prototype.dec = function (data, blocks) {
        for (var i = 0; i < blocks; i++) {
            this.decipher(data.subarray(i * 2));
        }
    };
    var BCRYPT_BLOCKS = 8, BCRYPT_HASHSIZE = 32;
    function bcrypt_hash(sha2pass, sha2salt, out) {
        var state = new Blowfish(), cdata = new Uint32Array(BCRYPT_BLOCKS), i, ciphertext = new Uint8Array([79, 120, 121, 99, 104, 114, 111, 109, 97, 116, 105,
            99, 66, 108, 111, 119, 102, 105, 115, 104, 83, 119, 97, 116, 68, 121, 110, 97, 109,
            105, 116, 101]); //"OxychromaticBlowfishSwatDynamite"
        state.expandstate(sha2salt, 64, sha2pass, 64);
        for (i = 0; i < 64; i++) {
            state.expand0state(sha2salt, 64);
            state.expand0state(sha2pass, 64);
        }
        for (i = 0; i < BCRYPT_BLOCKS; i++)
            cdata[i] = stream2word(ciphertext, ciphertext.byteLength);
        for (i = 0; i < 64; i++)
            state.enc(cdata, cdata.byteLength / 8);
        for (i = 0; i < BCRYPT_BLOCKS; i++) {
            out[4 * i + 3] = cdata[i] >>> 24;
            out[4 * i + 2] = cdata[i] >>> 16;
            out[4 * i + 1] = cdata[i] >>> 8;
            out[4 * i + 0] = cdata[i];
        }
    }
    ;
    function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {
        var sha2pass = new Uint8Array(64), sha2salt = new Uint8Array(64), out = new Uint8Array(BCRYPT_HASHSIZE), tmpout = new Uint8Array(BCRYPT_HASHSIZE), countsalt = new Uint8Array(saltlen + 4), i, j, amt, stride, dest, count, origkeylen = keylen;
        if (rounds < 1)
            return -1;
        if (passlen === 0 || saltlen === 0 || keylen === 0 ||
            keylen > (out.byteLength * out.byteLength) || saltlen > (1 << 20))
            return -1;
        stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);
        amt = Math.floor((keylen + stride - 1) / stride);
        for (i = 0; i < saltlen; i++)
            countsalt[i] = salt[i];
        crypto_hash_sha512(sha2pass, pass, passlen);
        for (count = 1; keylen > 0; count++) {
            countsalt[saltlen + 0] = count >>> 24;
            countsalt[saltlen + 1] = count >>> 16;
            countsalt[saltlen + 2] = count >>> 8;
            countsalt[saltlen + 3] = count;
            crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);
            bcrypt_hash(sha2pass, sha2salt, tmpout);
            for (i = out.byteLength; i--;)
                out[i] = tmpout[i];
            for (i = 1; i < rounds; i++) {
                crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);
                bcrypt_hash(sha2pass, sha2salt, tmpout);
                for (j = 0; j < out.byteLength; j++)
                    out[j] ^= tmpout[j];
            }
            amt = Math.min(amt, keylen);
            for (i = 0; i < amt; i++) {
                dest = i * stride + (count - 1);
                if (dest >= origkeylen)
                    break;
                key[dest] = out[i];
            }
            keylen -= i;
        }
        return 0;
    }
    ;
    module.exports = {
        BLOCKS: BCRYPT_BLOCKS,
        HASHSIZE: BCRYPT_HASHSIZE,
        hash: bcrypt_hash,
        pbkdf: bcrypt_pbkdf
    };
}
,
/* buffer-from/index */ function _(require, module, exports) {
    var toString = Object.prototype.toString;
    var isModern = (typeof Buffer.alloc === 'function' &&
        typeof Buffer.allocUnsafe === 'function' &&
        typeof Buffer.from === 'function');
    function isArrayBuffer(input) {
        return toString.call(input).slice(8, -1) === 'ArrayBuffer';
    }
    function fromArrayBuffer(obj, byteOffset, length) {
        byteOffset >>>= 0;
        var maxLength = obj.byteLength - byteOffset;
        if (maxLength < 0) {
            throw new RangeError("'offset' is out of bounds");
        }
        if (length === undefined) {
            length = maxLength;
        }
        else {
            length >>>= 0;
            if (length > maxLength) {
                throw new RangeError("'length' is out of bounds");
            }
        }
        return isModern
            ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
            : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)));
    }
    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');
        }
        return isModern
            ? Buffer.from(string, encoding)
            : new Buffer(string, encoding);
    }
    function bufferFrom(value, encodingOrOffset, length) {
        if (typeof value === 'number') {
            throw new TypeError('"value" argument must not be a number');
        }
        if (isArrayBuffer(value)) {
            return fromArrayBuffer(value, encodingOrOffset, length);
        }
        if (typeof value === 'string') {
            return fromString(value, encodingOrOffset);
        }
        return isModern
            ? Buffer.from(value)
            : new Buffer(value);
    }
    module.exports = bufferFrom;
}
,
/* camelcase/index */ function _(require, module, exports) {
    module.exports = function () {
        var str = [].map.call(arguments, function (str) {
            return str.trim();
        }).filter(function (str) {
            return str.length;
        }).join('-');
        if (!str.length) {
            return '';
        }
        if (str.length === 1 || !(/[_.\- ]+/).test(str)) {
            if (str[0] === str[0].toLowerCase() && str.slice(1) !== str.slice(1).toLowerCase()) {
                return str;
            }
            return str.toLowerCase();
        }
        return str
            .replace(/^[_.\- ]+/, '')
            .toLowerCase()
            .replace(/[_.\- ]+(\w|$)/g, function (m, p1) {
            return p1.toUpperCase();
        });
    };
}
,
/* caseless/index */ function _(require, module, exports) {
    function Caseless(dict) {
        this.dict = dict || {};
    }
    Caseless.prototype.set = function (name, value, clobber) {
        if (typeof name === 'object') {
            for (var i in name) {
                this.set(i, name[i], value);
            }
        }
        else {
            if (typeof clobber === 'undefined')
                clobber = true;
            var has = this.has(name);
            if (!clobber && has)
                this.dict[has] = this.dict[has] + ',' + value;
            else
                this.dict[has || name] = value;
            return has;
        }
    };
    Caseless.prototype.has = function (name) {
        var keys = Object.keys(this.dict), name = name.toLowerCase();
        for (var i = 0; i < keys.length; i++) {
            if (keys[i].toLowerCase() === name)
                return keys[i];
        }
        return false;
    };
    Caseless.prototype.get = function (name) {
        name = name.toLowerCase();
        var result, _key;
        var headers = this.dict;
        Object.keys(headers).forEach(function (key) {
            _key = key.toLowerCase();
            if (name === _key)
                result = headers[key];
        });
        return result;
    };
    Caseless.prototype.swap = function (name) {
        var has = this.has(name);
        if (has === name)
            return;
        if (!has)
            throw new Error('There is no header than matches "' + name + '"');
        this.dict[name] = this.dict[has];
        delete this.dict[has];
    };
    Caseless.prototype.del = function (name) {
        var has = this.has(name);
        return delete this.dict[has || name];
    };
    module.exports = function (dict) { return new Caseless(dict); };
    module.exports.httpify = function (resp, headers) {
        var c = new Caseless(headers);
        resp.setHeader = function (key, value, clobber) {
            if (typeof value === 'undefined')
                return;
            return c.set(key, value, clobber);
        };
        resp.hasHeader = function (key) {
            return c.has(key);
        };
        resp.getHeader = function (key) {
            return c.get(key);
        };
        resp.removeHeader = function (key) {
            return c.del(key);
        };
        resp.headers = c.dict;
        return c;
    };
}
,
/* center-align/index */ function _(require, module, exports) {
    var utils = require(72) /* ./utils */;
    module.exports = function centerAlign(val) {
        return utils.align(val, function (len, longest) {
            return Math.floor((longest - len) / 2);
        });
    };
}
,
/* center-align/utils */ function _(require, module, exports) {
    /**
     * Lazily-required module dependencies (makes the application
     * faster)
     */
    var utils = require(161) /* lazy-cache */(require);
    /**
     * Temporarily re-assign `require` to trick browserify and
     * webpack into reconizing lazy dependencies.
     *
     * This tiny bit of ugliness has the huge dual advantage of
     * only loading modules that are actually called at some
     * point in the lifecycle of the application, whilst also
     * allowing browserify and webpack to find modules that
     * are depended on but never actually called.
     */
    var fn = require;
    require = utils;
    /**
     * Lazily required module dependencies
     */
    require('align-text', 'align');
    /**
     * Restore `require`
     */
    require = fn;
    /**
     * Expose `utils` modules
     */
    module.exports = utils;
}
,
/* cliui/index */ function _(require, module, exports) {
    var wrap = require(374) /* wordwrap */, align = {
        right: require(310) /* right-align */,
        center: require(71) /* center-align */
    }, top = 0, right = 1, bottom = 2, left = 3;
    function UI(opts) {
        this.width = opts.width;
        this.wrap = opts.wrap;
        this.rows = [];
    }
    UI.prototype.span = function () {
        var cols = this.div.apply(this, arguments);
        cols.span = true;
    };
    UI.prototype.div = function () {
        if (arguments.length === 0)
            this.div('');
        if (this.wrap && this._shouldApplyLayoutDSL.apply(this, arguments)) {
            return this._applyLayoutDSL(arguments[0]);
        }
        var cols = [];
        for (var i = 0, arg; (arg = arguments[i]) !== undefined; i++) {
            if (typeof arg === 'string')
                cols.push(this._colFromString(arg));
            else
                cols.push(arg);
        }
        this.rows.push(cols);
        return cols;
    };
    UI.prototype._shouldApplyLayoutDSL = function () {
        return arguments.length === 1 && typeof arguments[0] === 'string' &&
            /[\t\n]/.test(arguments[0]);
    };
    UI.prototype._applyLayoutDSL = function (str) {
        var _this = this, rows = str.split('\n'), leftColumnWidth = 0;
        // simple heuristic for layout, make sure the
        // second column lines up along the left-hand.
        // don't allow the first column to take up more
        // than 50% of the screen.
        rows.forEach(function (row) {
            var columns = row.split('\t');
            if (columns.length > 1 && columns[0].length > leftColumnWidth) {
                leftColumnWidth = Math.min(Math.floor(_this.width * 0.5), columns[0].length);
            }
        });
        // generate a table:
        //  replacing ' ' with padding calculations.
        //  using the algorithmically generated width.
        rows.forEach(function (row) {
            var columns = row.split('\t');
            _this.div.apply(_this, columns.map(function (r, i) {
                return {
                    text: r.trim(),
                    padding: [0, r.match(/\s*$/)[0].length, 0, r.match(/^\s*/)[0].length],
                    width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
                };
            }));
        });
        return this.rows[this.rows.length - 1];
    };
    UI.prototype._colFromString = function (str) {
        return {
            text: str
        };
    };
    UI.prototype.toString = function () {
        var _this = this, lines = [];
        _this.rows.forEach(function (row, i) {
            _this.rowToString(row, lines);
        });
        // don't display any lines with the
        // hidden flag set.
        lines = lines.filter(function (line) {
            return !line.hidden;
        });
        return lines.map(function (line) {
            return line.text;
        }).join('\n');
    };
    UI.prototype.rowToString = function (row, lines) {
        var _this = this, paddingLeft, rrows = this._rasterize(row), str = '', ts, width, wrapWidth;
        rrows.forEach(function (rrow, r) {
            str = '';
            rrow.forEach(function (col, c) {
                ts = ''; // temporary string used during alignment/padding.
                width = row[c].width; // the width with padding.
                wrapWidth = _this._negatePadding(row[c]); // the width without padding.
                for (var i = 0; i < Math.max(wrapWidth, col.length); i++) {
                    ts += col.charAt(i) || ' ';
                }
                // align the string within its column.
                if (row[c].align && row[c].align !== 'left' && _this.wrap) {
                    ts = align[row[c].align](ts.trim() + '\n' + new Array(wrapWidth + 1).join(' '))
                        .split('\n')[0];
                    if (ts.length < wrapWidth)
                        ts += new Array(width - ts.length).join(' ');
                }
                // add left/right padding and print string.
                paddingLeft = (row[c].padding || [0, 0, 0, 0])[left];
                if (paddingLeft)
                    str += new Array(row[c].padding[left] + 1).join(' ');
                str += ts;
                if (row[c].padding && row[c].padding[right])
                    str += new Array(row[c].padding[right] + 1).join(' ');
                // if prior row is span, try to render the
                // current row on the prior line.
                if (r === 0 && lines.length > 0) {
                    str = _this._renderInline(str, lines[lines.length - 1], paddingLeft);
                }
            });
            // remove trailing whitespace.
            lines.push({
                text: str.replace(/ +$/, ''),
                span: row.span
            });
        });
        return lines;
    };
    // if the full 'source' can render in
    // the target line, do so.
    UI.prototype._renderInline = function (source, previousLine, paddingLeft) {
        var target = previousLine.text, str = '';
        if (!previousLine.span)
            return source;
        // if we're not applying wrapping logic,
        // just always append to the span.
        if (!this.wrap) {
            previousLine.hidden = true;
            return target + source;
        }
        for (var i = 0, tc, sc; i < Math.max(source.length, target.length); i++) {
            tc = target.charAt(i) || ' ';
            sc = source.charAt(i) || ' ';
            // we tried to overwrite a character in the other string.
            if (tc !== ' ' && sc !== ' ')
                return source;
            // there is not enough whitespace to maintain padding.
            if (sc !== ' ' && i < paddingLeft + target.length)
                return source;
            // :thumbsup:
            if (tc === ' ')
                str += sc;
            else
                str += tc;
        }
        previousLine.hidden = true;
        return str;
    };
    UI.prototype._rasterize = function (row) {
        var _this = this, i, rrow, rrows = [], widths = this._columnWidths(row), wrapped;
        // word wrap all columns, and create
        // a data-structure that is easy to rasterize.
        row.forEach(function (col, c) {
            // leave room for left and right padding.
            col.width = widths[c];
            if (_this.wrap)
                wrapped = wrap.hard(_this._negatePadding(col))(col.text).split('\n');
            else
                wrapped = col.text.split('\n');
            // add top and bottom padding.
            if (col.padding) {
                for (i = 0; i < (col.padding[top] || 0); i++)
                    wrapped.unshift('');
                for (i = 0; i < (col.padding[bottom] || 0); i++)
                    wrapped.push('');
            }
            wrapped.forEach(function (str, r) {
                if (!rrows[r])
                    rrows.push([]);
                rrow = rrows[r];
                for (var i = 0; i < c; i++) {
                    if (rrow[i] === undefined)
                        rrow.push('');
                }
                rrow.push(str);
            });
        });
        return rrows;
    };
    UI.prototype._negatePadding = function (col) {
        var wrapWidth = col.width;
        if (col.padding)
            wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
        return wrapWidth;
    };
    UI.prototype._columnWidths = function (row) {
        var _this = this, widths = [], unset = row.length, unsetWidth, remainingWidth = this.width;
        // column widths can be set in config.
        row.forEach(function (col, i) {
            if (col.width) {
                unset--;
                widths[i] = col.width;
                remainingWidth -= col.width;
            }
            else {
                widths[i] = undefined;
            }
        });
        // any unset widths should be calculated.
        if (unset)
            unsetWidth = Math.floor(remainingWidth / unset);
        widths.forEach(function (w, i) {
            if (!_this.wrap)
                widths[i] = row[i].width || row[i].text.length;
            else if (w === undefined)
                widths[i] = Math.max(unsetWidth, _minWidth(row[i]));
        });
        return widths;
    };
    // calculates the minimum width of
    // a column, based on padding preferences.
    function _minWidth(col) {
        var padding = col.padding || [];
        return 1 + (padding[left] || 0) + (padding[right] || 0);
    }
    module.exports = function (opts) {
        opts = opts || {};
        return new UI({
            width: (opts || {}).width || 80,
            wrap: typeof opts.wrap === 'boolean' ? opts.wrap : true
        });
    };
}
,
/* co/index */ function _(require, module, exports) {
    /**
     * slice() reference.
     */
    var slice = Array.prototype.slice;
    /**
     * Expose `co`.
     */
    module.exports = co['default'] = co.co = co;
    /**
     * Wrap the given generator `fn` into a
     * function that returns a promise.
     * This is a separate function so that
     * every `co()` call doesn't create a new,
     * unnecessary closure.
     *
     * @param {GeneratorFunction} fn
     * @return {Function}
     * @api public
     */
    co.wrap = function (fn) {
        createPromise.__generatorFunction__ = fn;
        return createPromise;
        function createPromise() {
            return co.call(this, fn.apply(this, arguments));
        }
    };
    /**
     * Execute the generator function or a generator
     * and return a promise.
     *
     * @param {Function} fn
     * @return {Promise}
     * @api public
     */
    function co(gen) {
        var ctx = this;
        var args = slice.call(arguments, 1);
        // we wrap everything in a promise to avoid promise chaining,
        // which leads to memory leak errors.
        // see https://github.com/tj/co/issues/180
        return new Promise(function (resolve, reject) {
            if (typeof gen === 'function')
                gen = gen.apply(ctx, args);
            if (!gen || typeof gen.next !== 'function')
                return resolve(gen);
            onFulfilled();
            /**
             * @param {Mixed} res
             * @return {Promise}
             * @api private
             */
            function onFulfilled(res) {
                var ret;
                try {
                    ret = gen.next(res);
                }
                catch (e) {
                    return reject(e);
                }
                next(ret);
            }
            /**
             * @param {Error} err
             * @return {Promise}
             * @api private
             */
            function onRejected(err) {
                var ret;
                try {
                    ret = gen.throw(err);
                }
                catch (e) {
                    return reject(e);
                }
                next(ret);
            }
            /**
             * Get the next value in the generator,
             * return a promise.
             *
             * @param {Object} ret
             * @return {Promise}
             * @api private
             */
            function next(ret) {
                if (ret.done)
                    return resolve(ret.value);
                var value = toPromise.call(ctx, ret.value);
                if (value && isPromise(value))
                    return value.then(onFulfilled, onRejected);
                return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
                    + 'but the following object was passed: "' + String(ret.value) + '"'));
            }
        });
    }
    /**
     * Convert a `yield`ed value into a promise.
     *
     * @param {Mixed} obj
     * @return {Promise}
     * @api private
     */
    function toPromise(obj) {
        if (!obj)
            return obj;
        if (isPromise(obj))
            return obj;
        if (isGeneratorFunction(obj) || isGenerator(obj))
            return co.call(this, obj);
        if ('function' == typeof obj)
            return thunkToPromise.call(this, obj);
        if (Array.isArray(obj))
            return arrayToPromise.call(this, obj);
        if (isObject(obj))
            return objectToPromise.call(this, obj);
        return obj;
    }
    /**
     * Convert a thunk to a promise.
     *
     * @param {Function}
     * @return {Promise}
     * @api private
     */
    function thunkToPromise(fn) {
        var ctx = this;
        return new Promise(function (resolve, reject) {
            fn.call(ctx, function (err, res) {
                if (err)
                    return reject(err);
                if (arguments.length > 2)
                    res = slice.call(arguments, 1);
                resolve(res);
            });
        });
    }
    /**
     * Convert an array of "yieldables" to a promise.
     * Uses `Promise.all()` internally.
     *
     * @param {Array} obj
     * @return {Promise}
     * @api private
     */
    function arrayToPromise(obj) {
        return Promise.all(obj.map(toPromise, this));
    }
    /**
     * Convert an object of "yieldables" to a promise.
     * Uses `Promise.all()` internally.
     *
     * @param {Object} obj
     * @return {Promise}
     * @api private
     */
    function objectToPromise(obj) {
        var results = new obj.constructor();
        var keys = Object.keys(obj);
        var promises = [];
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var promise = toPromise.call(this, obj[key]);
            if (promise && isPromise(promise))
                defer(promise, key);
            else
                results[key] = obj[key];
        }
        return Promise.all(promises).then(function () {
            return results;
        });
        function defer(promise, key) {
            // predefine the key in the result
            results[key] = undefined;
            promises.push(promise.then(function (res) {
                results[key] = res;
            }));
        }
    }
    /**
     * Check if `obj` is a promise.
     *
     * @param {Object} obj
     * @return {Boolean}
     * @api private
     */
    function isPromise(obj) {
        return 'function' == typeof obj.then;
    }
    /**
     * Check if `obj` is a generator.
     *
     * @param {Mixed} obj
     * @return {Boolean}
     * @api private
     */
    function isGenerator(obj) {
        return 'function' == typeof obj.next && 'function' == typeof obj.throw;
    }
    /**
     * Check if `obj` is a generator function.
     *
     * @param {Mixed} obj
     * @return {Boolean}
     * @api private
     */
    function isGeneratorFunction(obj) {
        var constructor = obj.constructor;
        if (!constructor)
            return false;
        if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName)
            return true;
        return isGenerator(constructor.prototype);
    }
    /**
     * Check for plain object.
     *
     * @param {Mixed} val
     * @return {Boolean}
     * @api private
     */
    function isObject(val) {
        return Object == val.constructor;
    }
}
,
/* coffeescript/lib/coffeescript/coffeescript */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // CoffeeScript can be used both on the server, as a command-line compiler based
        // on Node.js/V8, or to run CoffeeScript directly in the browser. This module
        // contains the main entry functions for tokenizing, parsing, and compiling
        // source CoffeeScript into JavaScript.
        var FILE_EXTENSIONS, Lexer, SourceMap, base64encode, checkShebangLine, compile, formatSourcePosition, getSourceMap, helpers, lexer, packageJson, parser, sourceMaps, sources, withPrettyErrors, indexOf = [].indexOf;
        ({ Lexer } = require(78) /* ./lexer */);
        ({ parser } = require(80) /* ./parser */);
        helpers = require(76) /* ./helpers */;
        SourceMap = require(84) /* ./sourcemap */;
        // Require `package.json`, which is two levels above this file, as this file is
        // evaluated from `lib/coffeescript`.
        packageJson = require(85) /* ../../package.json */;
        // The current CoffeeScript version number.
        exports.VERSION = packageJson.version;
        exports.FILE_EXTENSIONS = FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];
        // Expose helpers for testing.
        exports.helpers = helpers;
        // Function that allows for btoa in both nodejs and the browser.
        base64encode = function (src) {
            switch (false) {
                case typeof Buffer !== 'function':
                    return Buffer.from(src).toString('base64');
                case typeof btoa !== 'function':
                    // The contents of a `<script>` block are encoded via UTF-16, so if any extended
                    // characters are used in the block, btoa will fail as it maxes out at UTF-8.
                    // See https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
                    // for the gory details, and for the solution implemented here.
                    return btoa(encodeURIComponent(src).replace(/%([0-9A-F]{2})/g, function (match, p1) {
                        return String.fromCharCode('0x' + p1);
                    }));
                default:
                    throw new Error('Unable to base64 encode inline sourcemap.');
            }
        };
        // Function wrapper to add source file information to SyntaxErrors thrown by the
        // lexer/parser/compiler.
        withPrettyErrors = function (fn) {
            return function (code, options = {}) {
                var err;
                try {
                    return fn.call(this, code, options);
                }
                catch (error) {
                    err = error;
                    if (typeof code !== 'string') { // Support `CoffeeScript.nodes(tokens)`.
                        throw err;
                    }
                    throw helpers.updateSyntaxError(err, code, options.filename);
                }
            };
        };
        // For each compiled file, save its source in memory in case we need to
        // recompile it later. We might need to recompile if the first compilation
        // didn’t create a source map (faster) but something went wrong and we need
        // a stack trace. Assuming that most of the time, code isn’t throwing
        // exceptions, it’s probably more efficient to compile twice only when we
        // need a stack trace, rather than always generating a source map even when
        // it’s not likely to be used. Save in form of `filename`: [`(source)`]
        sources = {};
        // Also save source maps if generated, in form of `(source)`: [`(source map)`].
        sourceMaps = {};
        // Compile CoffeeScript code to JavaScript, using the Coffee/Jison compiler.
        // If `options.sourceMap` is specified, then `options.filename` must also be
        // specified. All options that can be passed to `SourceMap#generate` may also
        // be passed here.
        // This returns a javascript string, unless `options.sourceMap` is passed,
        // in which case this returns a `{js, v3SourceMap, sourceMap}`
        // object, where sourceMap is a sourcemap.coffee#SourceMap object, handy for
        // doing programmatic lookups.
        exports.compile = compile = withPrettyErrors(function (code, options = {}) {
            var currentColumn, currentLine, encoded, filename, fragment, fragments, generateSourceMap, header, i, j, js, len, len1, map, newLines, ref, ref1, sourceMapDataURI, sourceURL, token, tokens, transpiler, transpilerOptions, transpilerOutput, v3SourceMap;
            // Clone `options`, to avoid mutating the `options` object passed in.
            options = Object.assign({}, options);
            // Always generate a source map if no filename is passed in, since without a
            // a filename we have no way to retrieve this source later in the event that
            // we need to recompile it to get a source map for `prepareStackTrace`.
            generateSourceMap = options.sourceMap || options.inlineMap || (options.filename == null);
            filename = options.filename || '<anonymous>';
            checkShebangLine(filename, code);
            if (sources[filename] == null) {
                sources[filename] = [];
            }
            sources[filename].push(code);
            if (generateSourceMap) {
                map = new SourceMap;
            }
            tokens = lexer.tokenize(code, options);
            // Pass a list of referenced variables, so that generated variables won’t get
            // the same name.
            options.referencedVars = (function () {
                var i, len, results;
                results = [];
                for (i = 0, len = tokens.length; i < len; i++) {
                    token = tokens[i];
                    if (token[0] === 'IDENTIFIER') {
                        results.push(token[1]);
                    }
                }
                return results;
            })();
            // Check for import or export; if found, force bare mode.
            if (!((options.bare != null) && options.bare === true)) {
                for (i = 0, len = tokens.length; i < len; i++) {
                    token = tokens[i];
                    if ((ref = token[0]) === 'IMPORT' || ref === 'EXPORT') {
                        options.bare = true;
                        break;
                    }
                }
            }
            fragments = parser.parse(tokens).compileToFragments(options);
            currentLine = 0;
            if (options.header) {
                currentLine += 1;
            }
            if (options.shiftLine) {
                currentLine += 1;
            }
            currentColumn = 0;
            js = "";
            for (j = 0, len1 = fragments.length; j < len1; j++) {
                fragment = fragments[j];
                // Update the sourcemap with data from each fragment.
                if (generateSourceMap) {
                    // Do not include empty, whitespace, or semicolon-only fragments.
                    if (fragment.locationData && !/^[;\s]*$/.test(fragment.code)) {
                        map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
                            noReplace: true
                        });
                    }
                    newLines = helpers.count(fragment.code, "\n");
                    currentLine += newLines;
                    if (newLines) {
                        currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
                    }
                    else {
                        currentColumn += fragment.code.length;
                    }
                }
                // Copy the code from each fragment into the final JavaScript.
                js += fragment.code;
            }
            if (options.header) {
                header = `Generated by CoffeeScript ${this.VERSION}`;
                js = `// ${header}\n${js}`;
            }
            if (generateSourceMap) {
                v3SourceMap = map.generate(options, code);
                if (sourceMaps[filename] == null) {
                    sourceMaps[filename] = [];
                }
                sourceMaps[filename].push(map);
            }
            if (options.transpile) {
                if (typeof options.transpile !== 'object') {
                    // This only happens if run via the Node API and `transpile` is set to
                    // something other than an object.
                    throw new Error('The transpile option must be given an object with options to pass to Babel');
                }
                // Get the reference to Babel that we have been passed if this compiler
                // is run via the CLI or Node API.
                transpiler = options.transpile.transpile;
                delete options.transpile.transpile;
                transpilerOptions = Object.assign({}, options.transpile);
                // See https://github.com/babel/babel/issues/827#issuecomment-77573107:
                // Babel can take a v3 source map object as input in `inputSourceMap`
                // and it will return an *updated* v3 source map object in its output.
                if (v3SourceMap && (transpilerOptions.inputSourceMap == null)) {
                    transpilerOptions.inputSourceMap = v3SourceMap;
                }
                transpilerOutput = transpiler(js, transpilerOptions);
                js = transpilerOutput.code;
                if (v3SourceMap && transpilerOutput.map) {
                    v3SourceMap = transpilerOutput.map;
                }
            }
            if (options.inlineMap) {
                encoded = base64encode(JSON.stringify(v3SourceMap));
                sourceMapDataURI = `
                sourceURL = `//# sourceURL=${(ref1 = options.filename) != null ? ref1 : 'coffeescript'}`;
                js = `${js}\n${sourceMapDataURI}\n${sourceURL}`;
            }
            if (options.sourceMap) {
                return {
                    js,
                    sourceMap: map,
                    v3SourceMap: JSON.stringify(v3SourceMap, null, 2)
                };
            }
            else {
                return js;
            }
        });
        // Tokenize a string of CoffeeScript code, and return the array of tokens.
        exports.tokens = withPrettyErrors(function (code, options) {
            return lexer.tokenize(code, options);
        });
        // Parse a string of CoffeeScript code or an array of lexed tokens, and
        // return the AST. You can then compile it by calling `.compile()` on the root,
        // or traverse it by using `.traverseChildren()` with a callback.
        exports.nodes = withPrettyErrors(function (source, options) {
            if (typeof source === 'string') {
                return parser.parse(lexer.tokenize(source, options));
            }
            else {
                return parser.parse(source);
            }
        });
        // This file used to export these methods; leave stubs that throw warnings
        // instead. These methods have been moved into `index.coffee` to provide
        // separate entrypoints for Node and non-Node environments, so that static
        // analysis tools don’t choke on Node packages when compiling for a non-Node
        // environment.
        exports.run = exports.eval = exports.register = function () {
            throw new Error('require index.coffee, not this file');
        };
        // Instantiate a Lexer for our use here.
        lexer = new Lexer;
        // The real Lexer produces a generic stream of tokens. This object provides a
        // thin wrapper around it, compatible with the Jison API. We can then pass it
        // directly as a "Jison lexer".
        parser.lexer = {
            lex: function () {
                var tag, token;
                token = parser.tokens[this.pos++];
                if (token) {
                    [tag, this.yytext, this.yylloc] = token;
                    parser.errorToken = token.origin || token;
                    this.yylineno = this.yylloc.first_line;
                }
                else {
                    tag = '';
                }
                return tag;
            },
            setInput: function (tokens) {
                parser.tokens = tokens;
                return this.pos = 0;
            },
            upcomingInput: function () {
                return '';
            }
        };
        // Make all the AST nodes visible to the parser.
        parser.yy = require(79) /* ./nodes */;
        // Override Jison's default error handling function.
        parser.yy.parseError = function (message, { token }) {
            var errorLoc, errorTag, errorText, errorToken, tokens;
            // Disregard Jison's message, it contains redundant line number information.
            // Disregard the token, we take its value directly from the lexer in case
            // the error is caused by a generated token which might refer to its origin.
            ({ errorToken, tokens } = parser);
            [errorTag, errorText, errorLoc] = errorToken;
            errorText = (function () {
                switch (false) {
                    case errorToken !== tokens[tokens.length - 1]:
                        return 'end of input';
                    case errorTag !== 'INDENT' && errorTag !== 'OUTDENT':
                        return 'indentation';
                    case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'INFINITY' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
                        return errorTag.replace(/_START$/, '').toLowerCase();
                    default:
                        return helpers.nameWhitespaceCharacter(errorText);
                }
            })();
            // The second argument has a `loc` property, which should have the location
            // data for this token. Unfortunately, Jison seems to send an outdated `loc`
            // (from the previous token), so we take the location information directly
            // from the lexer.
            return helpers.throwSyntaxError(`unexpected ${errorText}`, errorLoc);
        };
        // Based on http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js
        // Modified to handle sourceMap
        formatSourcePosition = function (frame, getSourceMapping) {
            var as, column, fileLocation, filename, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName;
            filename = void 0;
            fileLocation = '';
            if (frame.isNative()) {
                fileLocation = "native";
            }
            else {
                if (frame.isEval()) {
                    filename = frame.getScriptNameOrSourceURL();
                    if (!filename) {
                        fileLocation = `${frame.getEvalOrigin()}, `;
                    }
                }
                else {
                    filename = frame.getFileName();
                }
                filename || (filename = "<anonymous>");
                line = frame.getLineNumber();
                column = frame.getColumnNumber();
                // Check for a sourceMap position
                source = getSourceMapping(filename, line, column);
                fileLocation = source ? `${filename}:${source[0]}:${source[1]}` : `${filename}:${line}:${column}`;
            }
            functionName = frame.getFunctionName();
            isConstructor = frame.isConstructor();
            isMethodCall = !(frame.isToplevel() || isConstructor);
            if (isMethodCall) {
                methodName = frame.getMethodName();
                typeName = frame.getTypeName();
                if (functionName) {
                    tp = as = '';
                    if (typeName && functionName.indexOf(typeName)) {
                        tp = `${typeName}.`;
                    }
                    if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1) {
                        as = ` [as ${methodName}]`;
                    }
                    return `${tp}${functionName}${as} (${fileLocation})`;
                }
                else {
                    return `${typeName}.${methodName || '<anonymous>'} (${fileLocation})`;
                }
            }
            else if (isConstructor) {
                return `new ${functionName || '<anonymous>'} (${fileLocation})`;
            }
            else if (functionName) {
                return `${functionName} (${fileLocation})`;
            }
            else {
                return fileLocation;
            }
        };
        getSourceMap = function (filename, line, column) {
            var answer, i, map, ref, ref1, sourceLocation;
            if (!(filename === '<anonymous>' || (ref = filename.slice(filename.lastIndexOf('.')), indexOf.call(FILE_EXTENSIONS, ref) >= 0))) {
                // Skip files that we didn’t compile, like Node system files that appear in
                // the stack trace, as they never have source maps.
                return null;
            }
            if (filename !== '<anonymous>' && (sourceMaps[filename] != null)) {
                return sourceMaps[filename][sourceMaps[filename].length - 1];
                // CoffeeScript compiled in a browser or via `CoffeeScript.compile` or `.run`
                // may get compiled with `options.filename` that’s missing, which becomes
                // `<anonymous>`; but the runtime might request the stack trace with the
                // filename of the script file. See if we have a source map cached under
                // `<anonymous>` that matches the error.
            }
            else if (sourceMaps['<anonymous>'] != null) {
                ref1 = sourceMaps['<anonymous>'];
                // Work backwards from the most recent anonymous source maps, until we find
                // one that works. This isn’t foolproof; there is a chance that multiple
                // source maps will have line/column pairs that match. But we have no other
                // way to match them. `frame.getFunction().toString()` doesn’t always work,
                // and it’s not foolproof either.
                for (i = ref1.length - 1; i >= 0; i += -1) {
                    map = ref1[i];
                    sourceLocation = map.sourceLocation([line - 1, column - 1]);
                    if (((sourceLocation != null ? sourceLocation[0] : void 0) != null) && (sourceLocation[1] != null)) {
                        return map;
                    }
                }
            }
            // If all else fails, recompile this source to get a source map. We need the
            // previous section (for `<anonymous>`) despite this option, because after it
            // gets compiled we will still need to look it up from
            // `sourceMaps['<anonymous>']` in order to find and return it. That’s why we
            // start searching from the end in the previous block, because most of the
            // time the source map we want is the last one.
            if (sources[filename] != null) {
                answer = compile(sources[filename][sources[filename].length - 1], {
                    filename: filename,
                    sourceMap: true,
                    literate: helpers.isLiterate(filename)
                });
                return answer.sourceMap;
            }
            else {
                return null;
            }
        };
        // Based on [michaelficarra/CoffeeScriptRedux](http://goo.gl/ZTx1p)
        // NodeJS / V8 have no support for transforming positions in stack traces using
        // sourceMap, so we must monkey-patch Error to display CoffeeScript source
        // positions.
        Error.prepareStackTrace = function (err, stack) {
            var frame, frames, getSourceMapping;
            getSourceMapping = function (filename, line, column) {
                var answer, sourceMap;
                sourceMap = getSourceMap(filename, line, column);
                if (sourceMap != null) {
                    answer = sourceMap.sourceLocation([line - 1, column - 1]);
                }
                if (answer != null) {
                    return [answer[0] + 1, answer[1] + 1];
                }
                else {
                    return null;
                }
            };
            frames = (function () {
                var i, len, results;
                results = [];
                for (i = 0, len = stack.length; i < len; i++) {
                    frame = stack[i];
                    if (frame.getFunction() === exports.run) {
                        break;
                    }
                    results.push(`    at ${formatSourcePosition(frame, getSourceMapping)}`);
                }
                return results;
            })();
            return `${err.toString()}\n${frames.join('\n')}\n`;
        };
        checkShebangLine = function (file, input) {
            var args, firstLine, ref, rest;
            firstLine = input.split(/$/m)[0];
            rest = firstLine != null ? firstLine.match(/^#!\s*([^\s]+\s*)(.*)/) : void 0;
            args = rest != null ? (ref = rest[2]) != null ? ref.split(/\s/).filter(function (s) {
                return s !== '';
            }) : void 0 : void 0;
            if ((args != null ? args.length : void 0) > 1) {
                console.error('The script to be run begins with a shebang line with more than one\nargument. This script will fail on platforms such as Linux which only\nallow a single argument.');
                console.error(`The shebang line was: '${firstLine}' in file '${file}'`);
                return console.error(`The arguments were: ${JSON.stringify(args)}`);
            }
        };
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/helpers */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // This file contains the common helper functions that we'd like to share among
        // the **Lexer**, **Rewriter**, and the **Nodes**. Merge objects, flatten
        // arrays, count characters, that sort of thing.
        // Peek at the beginning of a given string to see if it matches a sequence.
        var attachCommentsToNode, buildLocationData, buildLocationHash, extend, flatten, ref, repeat, syntaxErrorToString;
        exports.starts = function (string, literal, start) {
            return literal === string.substr(start, literal.length);
        };
        // Peek at the end of a given string to see if it matches a sequence.
        exports.ends = function (string, literal, back) {
            var len;
            len = literal.length;
            return literal === string.substr(string.length - len - (back || 0), len);
        };
        // Repeat a string `n` times.
        exports.repeat = repeat = function (str, n) {
            var res;
            // Use clever algorithm to have O(log(n)) string concatenation operations.
            res = '';
            while (n > 0) {
                if (n & 1) {
                    res += str;
                }
                n >>>= 1;
                str += str;
            }
            return res;
        };
        // Trim out all falsy values from an array.
        exports.compact = function (array) {
            var i, item, len1, results;
            results = [];
            for (i = 0, len1 = array.length; i < len1; i++) {
                item = array[i];
                if (item) {
                    results.push(item);
                }
            }
            return results;
        };
        // Count the number of occurrences of a string in a string.
        exports.count = function (string, substr) {
            var num, pos;
            num = pos = 0;
            if (!substr.length) {
                return 1 / 0;
            }
            while (pos = 1 + string.indexOf(substr, pos)) {
                num++;
            }
            return num;
        };
        // Merge objects, returning a fresh copy with attributes from both sides.
        // Used every time `Base#compile` is called, to allow properties in the
        // options hash to propagate down the tree without polluting other branches.
        exports.merge = function (options, overrides) {
            return extend(extend({}, options), overrides);
        };
        // Extend a source object with the properties of another object (shallow copy).
        extend = exports.extend = function (object, properties) {
            var key, val;
            for (key in properties) {
                val = properties[key];
                object[key] = val;
            }
            return object;
        };
        // Return a flattened version of an array.
        // Handy for getting a list of `children` from the nodes.
        exports.flatten = flatten = function (array) {
            var element, flattened, i, len1;
            flattened = [];
            for (i = 0, len1 = array.length; i < len1; i++) {
                element = array[i];
                if ('[object Array]' === Object.prototype.toString.call(element)) {
                    flattened = flattened.concat(flatten(element));
                }
                else {
                    flattened.push(element);
                }
            }
            return flattened;
        };
        // Delete a key from an object, returning the value. Useful when a node is
        // looking for a particular method in an options hash.
        exports.del = function (obj, key) {
            var val;
            val = obj[key];
            delete obj[key];
            return val;
        };
        // Typical Array::some
        exports.some = (ref = Array.prototype.some) != null ? ref : function (fn) {
            var e, i, len1, ref1;
            ref1 = this;
            for (i = 0, len1 = ref1.length; i < len1; i++) {
                e = ref1[i];
                if (fn(e)) {
                    return true;
                }
            }
            return false;
        };
        // Helper function for extracting code from Literate CoffeeScript by stripping
        // out all non-code blocks, producing a string of CoffeeScript code that can
        // be compiled “normally.”
        exports.invertLiterate = function (code) {
            var blankLine, i, indented, insideComment, len1, line, listItemStart, out, ref1;
            out = [];
            blankLine = /^\s*$/;
            indented = /^[\t ]/;
            listItemStart = /^(?:\t?| {0,3})(?:[\*\-\+]|[0-9]{1,9}\.)[ \t]/; // Up to one tab, or up to three spaces, or neither;
            // followed by `*`, `-` or `+`;
            // or by an integer up to 9 digits long, followed by a period;
            // followed by a space or a tab.
            insideComment = false;
            ref1 = code.split('\n');
            for (i = 0, len1 = ref1.length; i < len1; i++) {
                line = ref1[i];
                if (blankLine.test(line)) {
                    insideComment = false;
                    out.push(line);
                }
                else if (insideComment || listItemStart.test(line)) {
                    insideComment = true;
                    out.push(`# ${line}`);
                }
                else if (!insideComment && indented.test(line)) {
                    out.push(line);
                }
                else {
                    insideComment = true;
                    out.push(`# ${line}`);
                }
            }
            return out.join('\n');
        };
        // Merge two jison-style location data objects together.
        // If `last` is not provided, this will simply return `first`.
        buildLocationData = function (first, last) {
            if (!last) {
                return first;
            }
            else {
                return {
                    first_line: first.first_line,
                    first_column: first.first_column,
                    last_line: last.last_line,
                    last_column: last.last_column
                };
            }
        };
        buildLocationHash = function (loc) {
            return `${loc.first_line}x${loc.first_column}-${loc.last_line}x${loc.last_column}`;
        };
        // This returns a function which takes an object as a parameter, and if that
        // object is an AST node, updates that object's locationData.
        // The object is returned either way.
        exports.addDataToNode = function (parserState, first, last) {
            return function (obj) {
                var i, len1, objHash, ref1, token, tokenHash;
                // Add location data
                if (((obj != null ? obj.updateLocationDataIfMissing : void 0) != null) && (first != null)) {
                    obj.updateLocationDataIfMissing(buildLocationData(first, last));
                }
                // Add comments data
                if (!parserState.tokenComments) {
                    parserState.tokenComments = {};
                    ref1 = parserState.parser.tokens;
                    for (i = 0, len1 = ref1.length; i < len1; i++) {
                        token = ref1[i];
                        if (!token.comments) {
                            continue;
                        }
                        tokenHash = buildLocationHash(token[2]);
                        if (parserState.tokenComments[tokenHash] == null) {
                            parserState.tokenComments[tokenHash] = token.comments;
                        }
                        else {
                            parserState.tokenComments[tokenHash].push(...token.comments);
                        }
                    }
                }
                if (obj.locationData != null) {
                    objHash = buildLocationHash(obj.locationData);
                    if (parserState.tokenComments[objHash] != null) {
                        attachCommentsToNode(parserState.tokenComments[objHash], obj);
                    }
                }
                return obj;
            };
        };
        exports.attachCommentsToNode = attachCommentsToNode = function (comments, node) {
            if ((comments == null) || comments.length === 0) {
                return;
            }
            if (node.comments == null) {
                node.comments = [];
            }
            return node.comments.push(...comments);
        };
        // Convert jison location data to a string.
        // `obj` can be a token, or a locationData.
        exports.locationDataToString = function (obj) {
            var locationData;
            if (("2" in obj) && ("first_line" in obj[2])) {
                locationData = obj[2];
            }
            else if ("first_line" in obj) {
                locationData = obj;
            }
            if (locationData) {
                return `${locationData.first_line + 1}:${locationData.first_column + 1}-` + `${locationData.last_line + 1}:${locationData.last_column + 1}`;
            }
            else {
                return "No location data";
            }
        };
        // A `.coffee.md` compatible version of `basename`, that returns the file sans-extension.
        exports.baseFileName = function (file, stripExt = false, useWinPathSep = false) {
            var parts, pathSep;
            pathSep = useWinPathSep ? /\\|\// : /\//;
            parts = file.split(pathSep);
            file = parts[parts.length - 1];
            if (!(stripExt && file.indexOf('.') >= 0)) {
                return file;
            }
            parts = file.split('.');
            parts.pop();
            if (parts[parts.length - 1] === 'coffee' && parts.length > 1) {
                parts.pop();
            }
            return parts.join('.');
        };
        // Determine if a filename represents a CoffeeScript file.
        exports.isCoffee = function (file) {
            return /\.((lit)?coffee|coffee\.md)$/.test(file);
        };
        // Determine if a filename represents a Literate CoffeeScript file.
        exports.isLiterate = function (file) {
            return /\.(litcoffee|coffee\.md)$/.test(file);
        };
        // Throws a SyntaxError from a given location.
        // The error's `toString` will return an error message following the "standard"
        // format `<filename>:<line>:<col>: <message>` plus the line with the error and a
        // marker showing where the error is.
        exports.throwSyntaxError = function (message, location) {
            var error;
            error = new SyntaxError(message);
            error.location = location;
            error.toString = syntaxErrorToString;
            // Instead of showing the compiler's stacktrace, show our custom error message
            // (this is useful when the error bubbles up in Node.js applications that
            // compile CoffeeScript for example).
            error.stack = error.toString();
            throw error;
        };
        // Update a compiler SyntaxError with source code information if it didn't have
        // it already.
        exports.updateSyntaxError = function (error, code, filename) {
            // Avoid screwing up the `stack` property of other errors (i.e. possible bugs).
            if (error.toString === syntaxErrorToString) {
                error.code || (error.code = code);
                error.filename || (error.filename = filename);
                error.stack = error.toString();
            }
            return error;
        };
        syntaxErrorToString = function () {
            var codeLine, colorize, colorsEnabled, end, filename, first_column, first_line, last_column, last_line, marker, ref1, ref2, ref3, start;
            if (!(this.code && this.location)) {
                return Error.prototype.toString.call(this);
            }
            ({ first_line, first_column, last_line, last_column } = this.location);
            if (last_line == null) {
                last_line = first_line;
            }
            if (last_column == null) {
                last_column = first_column;
            }
            filename = this.filename || '[stdin]';
            codeLine = this.code.split('\n')[first_line];
            start = first_column;
            // Show only the first line on multi-line errors.
            end = first_line === last_line ? last_column + 1 : codeLine.length;
            marker = codeLine.slice(0, start).replace(/[^\s]/g, ' ') + repeat('^', end - start);
            // Check to see if we're running on a color-enabled TTY.
            if (typeof process !== "undefined" && process !== null) {
                colorsEnabled = ((ref1 = process.stdout) != null ? ref1.isTTY : void 0) && !((ref2 = process.env) != null ? ref2.NODE_DISABLE_COLORS : void 0);
            }
            if ((ref3 = this.colorful) != null ? ref3 : colorsEnabled) {
                colorize = function (str) {
                    return `\x1B[1;31m${str}\x1B[0m`;
                };
                codeLine = codeLine.slice(0, start) + colorize(codeLine.slice(start, end)) + codeLine.slice(end);
                marker = colorize(marker);
            }
            return `${filename}:${first_line + 1}:${first_column + 1}: error: ${this.message}\n${codeLine}\n${marker}`;
        };
        exports.nameWhitespaceCharacter = function (string) {
            switch (string) {
                case ' ':
                    return 'space';
                case '\n':
                    return 'newline';
                case '\r':
                    return 'carriage return';
                case '\t':
                    return 'tab';
                default:
                    return string;
            }
        };
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/index */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // Node.js Implementation
        var CoffeeScript, ext, fs, helpers, i, len, path, ref, universalCompile, vm, hasProp = {}.hasOwnProperty;
        CoffeeScript = require(75) /* ./coffeescript */;
        fs = require('fs');
        vm = require('vm');
        path = require('path');
        helpers = CoffeeScript.helpers;
        CoffeeScript.transpile = function (js, options) {
            var babel;
            try {
                babel = require('babel-core');
            }
            catch (error) {
                // This error is only for Node, as CLI users will see a different error
                // earlier if they don’t have Babel installed.
                throw new Error('To use the transpile option, you must have the \'babel-core\' module installed');
            }
            return babel.transform(js, options);
        };
        // The `compile` method shared by the CLI, Node and browser APIs.
        universalCompile = CoffeeScript.compile;
        // The `compile` method particular to the Node API.
        CoffeeScript.compile = function (code, options) {
            // Pass a reference to Babel into the compiler, so that the transpile option
            // is available in the Node API. We need to do this so that tools like Webpack
            // can `require('coffeescript')` and build correctly, without trying to
            // require Babel.
            if (options != null ? options.transpile : void 0) {
                options.transpile.transpile = CoffeeScript.transpile;
            }
            return universalCompile.call(CoffeeScript, code, options);
        };
        // Compile and execute a string of CoffeeScript (on the server), correctly
        // setting `__filename`, `__dirname`, and relative `require()`.
        CoffeeScript.run = function (code, options = {}) {
            var answer, dir, mainModule, ref;
            mainModule = require.main;
            // Set the filename.
            mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '<anonymous>';
            // Clear the module cache.
            mainModule.moduleCache && (mainModule.moduleCache = {});
            // Assign paths for node_modules loading
            dir = options.filename != null ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.');
            mainModule.paths = require('module')._nodeModulePaths(dir);
            // Save the options for compiling child imports.
            mainModule.options = options;
            // Compile.
            if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
                answer = CoffeeScript.compile(code, options);
                code = (ref = answer.js) != null ? ref : answer;
            }
            return mainModule._compile(code, mainModule.filename);
        };
        // Compile and evaluate a string of CoffeeScript (in a Node.js-like environment).
        // The CoffeeScript REPL uses this to run the input.
        CoffeeScript.eval = function (code, options = {}) {
            var Module, _module, _require, createContext, i, isContext, js, k, len, o, r, ref, ref1, ref2, ref3, sandbox, v;
            if (!(code = code.trim())) {
                return;
            }
            createContext = (ref = vm.Script.createContext) != null ? ref : vm.createContext;
            isContext = (ref1 = vm.isContext) != null ? ref1 : function (ctx) {
                return options.sandbox instanceof createContext().constructor;
            };
            if (createContext) {
                if (options.sandbox != null) {
                    if (isContext(options.sandbox)) {
                        sandbox = options.sandbox;
                    }
                    else {
                        sandbox = createContext();
                        ref2 = options.sandbox;
                        for (k in ref2) {
                            if (!hasProp.call(ref2, k))
                                continue;
                            v = ref2[k];
                            sandbox[k] = v;
                        }
                    }
                    sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
                }
                else {
                    sandbox = global;
                }
                sandbox.__filename = options.filename || 'eval';
                sandbox.__dirname = path.dirname(sandbox.__filename);
                // define module/require only if they chose not to specify their own
                if (!(sandbox !== global || sandbox.module || sandbox.require)) {
                    Module = require('module');
                    sandbox.module = _module = new Module(options.modulename || 'eval');
                    sandbox.require = _require = function (path) {
                        return Module._load(path, _module, true);
                    };
                    _module.filename = sandbox.__filename;
                    ref3 = Object.getOwnPropertyNames(require);
                    for (i = 0, len = ref3.length; i < len; i++) {
                        r = ref3[i];
                        if (r !== 'paths' && r !== 'arguments' && r !== 'caller') {
                            _require[r] = require[r];
                        }
                    }
                    // use the same hack node currently uses for their own REPL
                    _require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
                    _require.resolve = function (request) {
                        return Module._resolveFilename(request, _module);
                    };
                }
            }
            o = {};
            for (k in options) {
                if (!hasProp.call(options, k))
                    continue;
                v = options[k];
                o[k] = v;
            }
            o.bare = true; // ensure return value
            js = CoffeeScript.compile(code, o);
            if (sandbox === global) {
                return vm.runInThisContext(js);
            }
            else {
                return vm.runInContext(js, sandbox);
            }
        };
        CoffeeScript.register = function () {
            return require(81) /* ./register */;
        };
        // Throw error with deprecation warning when depending upon implicit `require.extensions` registration
        if (require.extensions) {
            ref = CoffeeScript.FILE_EXTENSIONS;
            for (i = 0, len = ref.length; i < len; i++) {
                ext = ref[i];
                (function (ext) {
                    var base;
                    return (base = require.extensions)[ext] != null ? base[ext] : base[ext] = function () {
                        throw new Error(`Use CoffeeScript.register() or require the coffeescript/register module to require ${ext} files.`);
                    };
                })(ext);
            }
        }
        CoffeeScript._compileFile = function (filename, options = {}) {
            var answer, err, raw, stripped;
            raw = fs.readFileSync(filename, 'utf8');
            // Strip the Unicode byte order mark, if this file begins with one.
            stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
            options = Object.assign({}, options, {
                filename: filename,
                literate: helpers.isLiterate(filename),
                sourceFiles: [filename],
                inlineMap: true // Always generate a source map, so that stack traces line up.
            });
            try {
                answer = CoffeeScript.compile(stripped, options);
            }
            catch (error) {
                err = error;
                // As the filename and code of a dynamically loaded file will be different
                // from the original file compiled with CoffeeScript.run, add that
                // information to error so it can be pretty-printed later.
                throw helpers.updateSyntaxError(err, stripped, filename);
            }
            return answer;
        };
        module.exports = CoffeeScript;
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/lexer */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // The CoffeeScript Lexer. Uses a series of token-matching regexes to attempt
        // matches against the beginning of the source code. When a match is found,
        // a token is produced, we consume the match, and start again. Tokens are in the
        // form:
        //     [tag, value, locationData]
        // where locationData is {first_line, first_column, last_line, last_column}, which is a
        // format that can be fed directly into [Jison](https://github.com/zaach/jison).  These
        // are read by jison in the `parser.lexer` function defined in coffeescript.coffee.
        var BOM, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARABLE_LEFT_SIDE, COMPARE, COMPOUND_ASSIGN, CSX_ATTRIBUTE, CSX_FRAGMENT_IDENTIFIER, CSX_IDENTIFIER, CSX_INTERPOLATION, HERECOMMENT_ILLEGAL, HEREDOC_DOUBLE, HEREDOC_INDENT, HEREDOC_SINGLE, HEREGEX, HEREGEX_OMIT, HERE_JSTOKEN, IDENTIFIER, INDENTABLE_CLOSERS, INDEXABLE, INSIDE_CSX, INVERSES, JSTOKEN, JS_KEYWORDS, LEADING_BLANK_LINE, LINE_BREAK, LINE_CONTINUER, Lexer, MATH, MULTI_DENT, NOT_REGEX, NUMBER, OPERATOR, POSSIBLY_DIVISION, REGEX, REGEX_FLAGS, REGEX_ILLEGAL, REGEX_INVALID_ESCAPE, RELATION, RESERVED, Rewriter, SHIFT, SIMPLE_STRING_OMIT, STRICT_PROSCRIBED, STRING_DOUBLE, STRING_INVALID_ESCAPE, STRING_OMIT, STRING_SINGLE, STRING_START, TRAILING_BLANK_LINE, TRAILING_SPACES, UNARY, UNARY_MATH, UNFINISHED, UNICODE_CODE_POINT_ESCAPE, VALID_FLAGS, WHITESPACE, attachCommentsToNode, compact, count, invertLiterate, isForFrom, isUnassignable, key, locationDataToString, merge, repeat, starts, throwSyntaxError, indexOf = [].indexOf, slice = [].slice;
        ({ Rewriter, INVERSES } = require(82) /* ./rewriter */);
        // Import the helpers we need.
        ({ count, starts, compact, repeat, invertLiterate, merge, attachCommentsToNode, locationDataToString, throwSyntaxError } = require(76) /* ./helpers */);
        // The Lexer Class
        // ---------------
        // The Lexer class reads a stream of CoffeeScript and divvies it up into tagged
        // tokens. Some potential ambiguity in the grammar has been avoided by
        // pushing some extra smarts into the Lexer.
        exports.Lexer = Lexer = class Lexer {
            // **tokenize** is the Lexer's main method. Scan by attempting to match tokens
            // one at a time, using a regular expression anchored at the start of the
            // remaining code, or a custom recursive token-matching method
            // (for interpolations). When the next token has been recorded, we move forward
            // within the code past the token, and begin again.
            // Each tokenizing method is responsible for returning the number of characters
            // it has consumed.
            // Before returning the token stream, run it through the [Rewriter](rewriter.html).
            tokenize(code, opts = {}) {
                var consumed, end, i, ref;
                this.literate = opts.literate; // Are we lexing literate CoffeeScript?
                this.indent = 0; // The current indentation level.
                this.baseIndent = 0; // The overall minimum indentation level.
                this.indebt = 0; // The over-indentation at the current level.
                this.outdebt = 0; // The under-outdentation at the current level.
                this.indents = []; // The stack of all current indentation levels.
                this.indentLiteral = ''; // The indentation.
                this.ends = []; // The stack for pairing up tokens.
                this.tokens = []; // Stream of parsed tokens in the form `['TYPE', value, location data]`.
                this.seenFor = false; // Used to recognize `FORIN`, `FOROF` and `FORFROM` tokens.
                this.seenImport = false; // Used to recognize `IMPORT FROM? AS?` tokens.
                this.seenExport = false; // Used to recognize `EXPORT FROM? AS?` tokens.
                this.importSpecifierList = false; // Used to identify when in an `IMPORT {...} FROM? ...`.
                this.exportSpecifierList = false; // Used to identify when in an `EXPORT {...} FROM? ...`.
                this.csxDepth = 0; // Used to optimize CSX checks, how deep in CSX we are.
                this.csxObjAttribute = {}; // Used to detect if CSX attributes is wrapped in {} (<div {props...} />).
                this.chunkLine = opts.line || 0; // The start line for the current @chunk.
                this.chunkColumn = opts.column || 0; // The start column of the current @chunk.
                code = this.clean(code); // The stripped, cleaned original source code.
                // At every position, run through this list of attempted matches,
                // short-circuiting if any of them succeed. Their order determines precedence:
                // `@literalToken` is the fallback catch-all.
                i = 0;
                while (this.chunk = code.slice(i)) {
                    consumed = this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.stringToken() || this.numberToken() || this.csxToken() || this.regexToken() || this.jsToken() || this.literalToken();
                    // Update position.
                    [this.chunkLine, this.chunkColumn] = this.getLineAndColumnFromChunk(consumed);
                    i += consumed;
                    if (opts.untilBalanced && this.ends.length === 0) {
                        return {
                            tokens: this.tokens,
                            index: i
                        };
                    }
                }
                this.closeIndentation();
                if (end = this.ends.pop()) {
                    this.error(`missing ${end.tag}`, ((ref = end.origin) != null ? ref : end)[2]);
                }
                if (opts.rewrite === false) {
                    return this.tokens;
                }
                return (new Rewriter).rewrite(this.tokens);
            }
            // Preprocess the code to remove leading and trailing whitespace, carriage
            // returns, etc. If we’re lexing literate CoffeeScript, strip external Markdown
            // by removing all lines that aren’t indented by at least four spaces or a tab.
            clean(code) {
                if (code.charCodeAt(0) === BOM) {
                    code = code.slice(1);
                }
                code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
                if (WHITESPACE.test(code)) {
                    code = `\n${code}`;
                    this.chunkLine--;
                }
                if (this.literate) {
                    code = invertLiterate(code);
                }
                return code;
            }
            // Tokenizers
            // ----------
            // Matches identifying literals: variables, keywords, method names, etc.
            // Check to ensure that JavaScript reserved words aren’t being used as
            // identifiers. Because CoffeeScript reserves a handful of keywords that are
            // allowed in JavaScript, we’re careful not to tag them as keywords when
            // referenced as property names here, so you can still do `jQuery.is()` even
            // though `is` means `===` otherwise.
            identifierToken() {
                var alias, colon, colonOffset, colonToken, id, idLength, inCSXTag, input, match, poppedToken, prev, prevprev, ref, ref1, ref10, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, regExSuper, regex, sup, tag, tagToken;
                inCSXTag = this.atCSXTag();
                regex = inCSXTag ? CSX_ATTRIBUTE : IDENTIFIER;
                if (!(match = regex.exec(this.chunk))) {
                    return 0;
                }
                [input, id, colon] = match;
                // Preserve length of id for location data
                idLength = id.length;
                poppedToken = void 0;
                if (id === 'own' && this.tag() === 'FOR') {
                    this.token('OWN', id);
                    return id.length;
                }
                if (id === 'from' && this.tag() === 'YIELD') {
                    this.token('FROM', id);
                    return id.length;
                }
                if (id === 'as' && this.seenImport) {
                    if (this.value() === '*') {
                        this.tokens[this.tokens.length - 1][0] = 'IMPORT_ALL';
                    }
                    else if (ref = this.value(true), indexOf.call(COFFEE_KEYWORDS, ref) >= 0) {
                        prev = this.prev();
                        [prev[0], prev[1]] = ['IDENTIFIER', this.value(true)];
                    }
                    if ((ref1 = this.tag()) === 'DEFAULT' || ref1 === 'IMPORT_ALL' || ref1 === 'IDENTIFIER') {
                        this.token('AS', id);
                        return id.length;
                    }
                }
                if (id === 'as' && this.seenExport) {
                    if ((ref2 = this.tag()) === 'IDENTIFIER' || ref2 === 'DEFAULT') {
                        this.token('AS', id);
                        return id.length;
                    }
                    if (ref3 = this.value(true), indexOf.call(COFFEE_KEYWORDS, ref3) >= 0) {
                        prev = this.prev();
                        [prev[0], prev[1]] = ['IDENTIFIER', this.value(true)];
                        this.token('AS', id);
                        return id.length;
                    }
                }
                if (id === 'default' && this.seenExport && ((ref4 = this.tag()) === 'EXPORT' || ref4 === 'AS')) {
                    this.token('DEFAULT', id);
                    return id.length;
                }
                if (id === 'do' && (regExSuper = /^(\s*super)(?!\(\))/.exec(this.chunk.slice(3)))) {
                    this.token('SUPER', 'super');
                    this.token('CALL_START', '(');
                    this.token('CALL_END', ')');
                    [input, sup] = regExSuper;
                    return sup.length + 3;
                }
                prev = this.prev();
                tag = colon || (prev != null) && (((ref5 = prev[0]) === '.' || ref5 === '?.' || ref5 === '::' || ref5 === '?::') || !prev.spaced && prev[0] === '@') ? 'PROPERTY' : 'IDENTIFIER';
                if (tag === 'IDENTIFIER' && (indexOf.call(JS_KEYWORDS, id) >= 0 || indexOf.call(COFFEE_KEYWORDS, id) >= 0) && !(this.exportSpecifierList && indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
                    tag = id.toUpperCase();
                    if (tag === 'WHEN' && (ref6 = this.tag(), indexOf.call(LINE_BREAK, ref6) >= 0)) {
                        tag = 'LEADING_WHEN';
                    }
                    else if (tag === 'FOR') {
                        this.seenFor = true;
                    }
                    else if (tag === 'UNLESS') {
                        tag = 'IF';
                    }
                    else if (tag === 'IMPORT') {
                        this.seenImport = true;
                    }
                    else if (tag === 'EXPORT') {
                        this.seenExport = true;
                    }
                    else if (indexOf.call(UNARY, tag) >= 0) {
                        tag = 'UNARY';
                    }
                    else if (indexOf.call(RELATION, tag) >= 0) {
                        if (tag !== 'INSTANCEOF' && this.seenFor) {
                            tag = 'FOR' + tag;
                            this.seenFor = false;
                        }
                        else {
                            tag = 'RELATION';
                            if (this.value() === '!') {
                                poppedToken = this.tokens.pop();
                                id = '!' + id;
                            }
                        }
                    }
                }
                else if (tag === 'IDENTIFIER' && this.seenFor && id === 'from' && isForFrom(prev)) {
                    tag = 'FORFROM';
                    this.seenFor = false;
                    // Throw an error on attempts to use `get` or `set` as keywords, or
                    // what CoffeeScript would normally interpret as calls to functions named
                    // `get` or `set`, i.e. `get({foo: function () {}})`.
                }
                else if (tag === 'PROPERTY' && prev) {
                    if (prev.spaced && (ref7 = prev[0], indexOf.call(CALLABLE, ref7) >= 0) && /^[gs]et$/.test(prev[1]) && this.tokens.length > 1 && ((ref8 = this.tokens[this.tokens.length - 2][0]) !== '.' && ref8 !== '?.' && ref8 !== '@')) {
                        this.error(`'${prev[1]}' cannot be used as a keyword, or as a function call without parentheses`, prev[2]);
                    }
                    else if (this.tokens.length > 2) {
                        prevprev = this.tokens[this.tokens.length - 2];
                        if (((ref9 = prev[0]) === '@' || ref9 === 'THIS') && prevprev && prevprev.spaced && /^[gs]et$/.test(prevprev[1]) && ((ref10 = this.tokens[this.tokens.length - 3][0]) !== '.' && ref10 !== '?.' && ref10 !== '@')) {
                            this.error(`'${prevprev[1]}' cannot be used as a keyword, or as a function call without parentheses`, prevprev[2]);
                        }
                    }
                }
                if (tag === 'IDENTIFIER' && indexOf.call(RESERVED, id) >= 0) {
                    this.error(`reserved word '${id}'`, {
                        length: id.length
                    });
                }
                if (!(tag === 'PROPERTY' || this.exportSpecifierList)) {
                    if (indexOf.call(COFFEE_ALIASES, id) >= 0) {
                        alias = id;
                        id = COFFEE_ALIAS_MAP[id];
                    }
                    tag = (function () {
                        switch (id) {
                            case '!':
                                return 'UNARY';
                            case '==':
                            case '!=':
                                return 'COMPARE';
                            case 'true':
                            case 'false':
                                return 'BOOL';
                            case 'break':
                            case 'continue':
                            case 'debugger':
                                return 'STATEMENT';
                            case '&&':
                            case '||':
                                return id;
                            default:
                                return tag;
                        }
                    })();
                }
                tagToken = this.token(tag, id, 0, idLength);
                if (alias) {
                    tagToken.origin = [tag, alias, tagToken[2]];
                }
                if (poppedToken) {
                    [tagToken[2].first_line, tagToken[2].first_column] = [poppedToken[2].first_line, poppedToken[2].first_column];
                }
                if (colon) {
                    colonOffset = input.lastIndexOf(inCSXTag ? '=' : ':');
                    colonToken = this.token(':', ':', colonOffset, colon.length);
                    if (inCSXTag) { // used by rewriter
                        colonToken.csxColon = true;
                    }
                }
                if (inCSXTag && tag === 'IDENTIFIER' && prev[0] !== ':') {
                    this.token(',', ',', 0, 0, tagToken);
                }
                return input.length;
            }
            // Matches numbers, including decimals, hex, and exponential notation.
            // Be careful not to interfere with ranges in progress.
            numberToken() {
                var base, lexedLength, match, number, numberValue, tag;
                if (!(match = NUMBER.exec(this.chunk))) {
                    return 0;
                }
                number = match[0];
                lexedLength = number.length;
                switch (false) {
                    case !/^0[BOX]/.test(number):
                        this.error(`radix prefix in '${number}' must be lowercase`, {
                            offset: 1
                        });
                        break;
                    case !/^(?!0x).*E/.test(number):
                        this.error(`exponential notation in '${number}' must be indicated with a lowercase 'e'`, {
                            offset: number.indexOf('E')
                        });
                        break;
                    case !/^0\d*[89]/.test(number):
                        this.error(`decimal literal '${number}' must not be prefixed with '0'`, {
                            length: lexedLength
                        });
                        break;
                    case !/^0\d+/.test(number):
                        this.error(`octal literal '${number}' must be prefixed with '0o'`, {
                            length: lexedLength
                        });
                }
                base = (function () {
                    switch (number.charAt(1)) {
                        case 'b':
                            return 2;
                        case 'o':
                            return 8;
                        case 'x':
                            return 16;
                        default:
                            return null;
                    }
                })();
                numberValue = base != null ? parseInt(number.slice(2), base) : parseFloat(number);
                tag = numberValue === 2e308 ? 'INFINITY' : 'NUMBER';
                this.token(tag, number, 0, lexedLength);
                return lexedLength;
            }
            // Matches strings, including multiline strings, as well as heredocs, with or without
            // interpolation.
            stringToken() {
                var $, attempt, delimiter, doc, end, heredoc, i, indent, indentRegex, match, prev, quote, ref, regex, token, tokens;
                [quote] = STRING_START.exec(this.chunk) || [];
                if (!quote) {
                    return 0;
                }
                // If the preceding token is `from` and this is an import or export statement,
                // properly tag the `from`.
                prev = this.prev();
                if (prev && this.value() === 'from' && (this.seenImport || this.seenExport)) {
                    prev[0] = 'FROM';
                }
                regex = (function () {
                    switch (quote) {
                        case "'":
                            return STRING_SINGLE;
                        case '"':
                            return STRING_DOUBLE;
                        case "'''":
                            return HEREDOC_SINGLE;
                        case '"""':
                            return HEREDOC_DOUBLE;
                    }
                })();
                heredoc = quote.length === 3;
                ({
                    tokens,
                    index: end
                } = this.matchWithInterpolations(regex, quote));
                $ = tokens.length - 1;
                delimiter = quote.charAt(0);
                if (heredoc) {
                    // Find the smallest indentation. It will be removed from all lines later.
                    indent = null;
                    doc = ((function () {
                        var j, len, results;
                        results = [];
                        for (i = j = 0, len = tokens.length; j < len; i = ++j) {
                            token = tokens[i];
                            if (token[0] === 'NEOSTRING') {
                                results.push(token[1]);
                            }
                        }
                        return results;
                    })()).join('#{}');
                    while (match = HEREDOC_INDENT.exec(doc)) {
                        attempt = match[1];
                        if (indent === null || (0 < (ref = attempt.length) && ref < indent.length)) {
                            indent = attempt;
                        }
                    }
                    if (indent) {
                        indentRegex = RegExp(`\\n${indent}`, "g");
                    }
                    this.mergeInterpolationTokens(tokens, { delimiter }, (value, i) => {
                        value = this.formatString(value, {
                            delimiter: quote
                        });
                        if (indentRegex) {
                            value = value.replace(indentRegex, '\n');
                        }
                        if (i === 0) {
                            value = value.replace(LEADING_BLANK_LINE, '');
                        }
                        if (i === $) {
                            value = value.replace(TRAILING_BLANK_LINE, '');
                        }
                        return value;
                    });
                }
                else {
                    this.mergeInterpolationTokens(tokens, { delimiter }, (value, i) => {
                        value = this.formatString(value, {
                            delimiter: quote
                        });
                        value = value.replace(SIMPLE_STRING_OMIT, function (match, offset) {
                            if ((i === 0 && offset === 0) || (i === $ && offset + match.length === value.length)) {
                                return '';
                            }
                            else {
                                return ' ';
                            }
                        });
                        return value;
                    });
                }
                if (this.atCSXTag()) {
                    this.token(',', ',', 0, 0, this.prev);
                }
                return end;
            }
            // Matches and consumes comments. The comments are taken out of the token
            // stream and saved for later, to be reinserted into the output after
            // everything has been parsed and the JavaScript code generated.
            commentToken(chunk = this.chunk) {
                var comment, commentAttachments, content, contents, here, i, match, matchIllegal, newLine, placeholderToken, prev;
                if (!(match = chunk.match(COMMENT))) {
                    return 0;
                }
                [comment, here] = match;
                contents = null;
                // Does this comment follow code on the same line?
                newLine = /^\s*\n+\s*#/.test(comment);
                if (here) {
                    matchIllegal = HERECOMMENT_ILLEGAL.exec(comment);
                    if (matchIllegal) {
                        this.error(`block comments cannot contain ${matchIllegal[0]}`, {
                            offset: matchIllegal.index,
                            length: matchIllegal[0].length
                        });
                    }
                    // Parse indentation or outdentation as if this block comment didn’t exist.
                    chunk = chunk.replace(`###${here}###`, '');
                    // Remove leading newlines, like `Rewriter::removeLeadingNewlines`, to
                    // avoid the creation of unwanted `TERMINATOR` tokens.
                    chunk = chunk.replace(/^\n+/, '');
                    this.lineToken(chunk);
                    // Pull out the ###-style comment’s content, and format it.
                    content = here;
                    if (indexOf.call(content, '\n') >= 0) {
                        content = content.replace(RegExp(`\\n${repeat(' ', this.indent)}`, "g"), '\n');
                    }
                    contents = [content];
                }
                else {
                    // The `COMMENT` regex captures successive line comments as one token.
                    // Remove any leading newlines before the first comment, but preserve
                    // blank lines between line comments.
                    content = comment.replace(/^(\n*)/, '');
                    content = content.replace(/^([ |\t]*)#/gm, '');
                    contents = content.split('\n');
                }
                commentAttachments = (function () {
                    var j, len, results;
                    results = [];
                    for (i = j = 0, len = contents.length; j < len; i = ++j) {
                        content = contents[i];
                        results.push({
                            content: content,
                            here: here != null,
                            newLine: newLine || i !== 0 // Line comments after the first one start new lines, by definition.
                        });
                    }
                    return results;
                })();
                prev = this.prev();
                if (!prev) {
                    // If there’s no previous token, create a placeholder token to attach
                    // this comment to; and follow with a newline.
                    commentAttachments[0].newLine = true;
                    this.lineToken(this.chunk.slice(comment.length));
                    placeholderToken = this.makeToken('JS', '');
                    placeholderToken.generated = true;
                    placeholderToken.comments = commentAttachments;
                    this.tokens.push(placeholderToken);
                    this.newlineToken(0);
                }
                else {
                    attachCommentsToNode(commentAttachments, prev);
                }
                return comment.length;
            }
            // Matches JavaScript interpolated directly into the source via backticks.
            jsToken() {
                var match, script;
                if (!(this.chunk.charAt(0) === '`' && (match = HERE_JSTOKEN.exec(this.chunk) || JSTOKEN.exec(this.chunk)))) {
                    return 0;
                }
                // Convert escaped backticks to backticks, and escaped backslashes
                // just before escaped backticks to backslashes
                script = match[1].replace(/\\+(`|$)/g, function (string) {
                    // `string` is always a value like '\`', '\\\`', '\\\\\`', etc.
                    // By reducing it to its latter half, we turn '\`' to '`', '\\\`' to '\`', etc.
                    return string.slice(-Math.ceil(string.length / 2));
                });
                this.token('JS', script, 0, match[0].length);
                return match[0].length;
            }
            // Matches regular expression literals, as well as multiline extended ones.
            // Lexing regular expressions is difficult to distinguish from division, so we
            // borrow some basic heuristics from JavaScript and Ruby.
            regexToken() {
                var body, closed, comment, comments, end, flags, index, j, len, match, origin, prev, ref, ref1, regex, tokens;
                switch (false) {
                    case !(match = REGEX_ILLEGAL.exec(this.chunk)):
                        this.error(`regular expressions cannot begin with ${match[2]}`, {
                            offset: match.index + match[1].length
                        });
                        break;
                    case !(match = this.matchWithInterpolations(HEREGEX, '///')):
                        ({ tokens, index } = match);
                        comments = this.chunk.slice(0, index).match(/\s+(#(?!{).*)/g);
                        if (comments) {
                            for (j = 0, len = comments.length; j < len; j++) {
                                comment = comments[j];
                                this.commentToken(comment);
                            }
                        }
                        break;
                    case !(match = REGEX.exec(this.chunk)):
                        [regex, body, closed] = match;
                        this.validateEscapes(body, {
                            isRegex: true,
                            offsetInChunk: 1
                        });
                        index = regex.length;
                        prev = this.prev();
                        if (prev) {
                            if (prev.spaced && (ref = prev[0], indexOf.call(CALLABLE, ref) >= 0)) {
                                if (!closed || POSSIBLY_DIVISION.test(regex)) {
                                    return 0;
                                }
                            }
                            else if (ref1 = prev[0], indexOf.call(NOT_REGEX, ref1) >= 0) {
                                return 0;
                            }
                        }
                        if (!closed) {
                            this.error('missing / (unclosed regex)');
                        }
                        break;
                    default:
                        return 0;
                }
                [flags] = REGEX_FLAGS.exec(this.chunk.slice(index));
                end = index + flags.length;
                origin = this.makeToken('REGEX', null, 0, end);
                switch (false) {
                    case !!VALID_FLAGS.test(flags):
                        this.error(`invalid regular expression flags ${flags}`, {
                            offset: index,
                            length: flags.length
                        });
                        break;
                    case !(regex || tokens.length === 1):
                        if (body) {
                            body = this.formatRegex(body, {
                                flags,
                                delimiter: '/'
                            });
                        }
                        else {
                            body = this.formatHeregex(tokens[0][1], { flags });
                        }
                        this.token('REGEX', `${this.makeDelimitedLiteral(body, {
                            delimiter: '/'
                        })}${flags}`, 0, end, origin);
                        break;
                    default:
                        this.token('REGEX_START', '(', 0, 0, origin);
                        this.token('IDENTIFIER', 'RegExp', 0, 0);
                        this.token('CALL_START', '(', 0, 0);
                        this.mergeInterpolationTokens(tokens, {
                            delimiter: '"',
                            double: true
                        }, (str) => {
                            return this.formatHeregex(str, { flags });
                        });
                        if (flags) {
                            this.token(',', ',', index - 1, 0);
                            this.token('STRING', '"' + flags + '"', index - 1, flags.length);
                        }
                        this.token(')', ')', end - 1, 0);
                        this.token('REGEX_END', ')', end - 1, 0);
                }
                return end;
            }
            // Matches newlines, indents, and outdents, and determines which is which.
            // If we can detect that the current line is continued onto the next line,
            // then the newline is suppressed:
            //     elements
            //       .each( ... )
            //       .map( ... )
            // Keeps track of the level of indentation, because a single outdent token
            // can close multiple indents, so we need to know how far in we happen to be.
            lineToken(chunk = this.chunk) {
                var backslash, diff, indent, match, minLiteralLength, newIndentLiteral, noNewlines, prev, size;
                if (!(match = MULTI_DENT.exec(chunk))) {
                    return 0;
                }
                indent = match[0];
                prev = this.prev();
                backslash = (prev != null ? prev[0] : void 0) === '\\';
                if (!(backslash && this.seenFor)) {
                    this.seenFor = false;
                }
                if (!((backslash && this.seenImport) || this.importSpecifierList)) {
                    this.seenImport = false;
                }
                if (!((backslash && this.seenExport) || this.exportSpecifierList)) {
                    this.seenExport = false;
                }
                size = indent.length - 1 - indent.lastIndexOf('\n');
                noNewlines = this.unfinished();
                newIndentLiteral = size > 0 ? indent.slice(-size) : '';
                if (!/^(.?)\1*$/.exec(newIndentLiteral)) {
                    this.error('mixed indentation', {
                        offset: indent.length
                    });
                    return indent.length;
                }
                minLiteralLength = Math.min(newIndentLiteral.length, this.indentLiteral.length);
                if (newIndentLiteral.slice(0, minLiteralLength) !== this.indentLiteral.slice(0, minLiteralLength)) {
                    this.error('indentation mismatch', {
                        offset: indent.length
                    });
                    return indent.length;
                }
                if (size - this.indebt === this.indent) {
                    if (noNewlines) {
                        this.suppressNewlines();
                    }
                    else {
                        this.newlineToken(0);
                    }
                    return indent.length;
                }
                if (size > this.indent) {
                    if (noNewlines) {
                        if (!backslash) {
                            this.indebt = size - this.indent;
                        }
                        this.suppressNewlines();
                        return indent.length;
                    }
                    if (!this.tokens.length) {
                        this.baseIndent = this.indent = size;
                        this.indentLiteral = newIndentLiteral;
                        return indent.length;
                    }
                    diff = size - this.indent + this.outdebt;
                    this.token('INDENT', diff, indent.length - size, size);
                    this.indents.push(diff);
                    this.ends.push({
                        tag: 'OUTDENT'
                    });
                    this.outdebt = this.indebt = 0;
                    this.indent = size;
                    this.indentLiteral = newIndentLiteral;
                }
                else if (size < this.baseIndent) {
                    this.error('missing indentation', {
                        offset: indent.length
                    });
                }
                else {
                    this.indebt = 0;
                    this.outdentToken(this.indent - size, noNewlines, indent.length);
                }
                return indent.length;
            }
            // Record an outdent token or multiple tokens, if we happen to be moving back
            // inwards past several recorded indents. Sets new @indent value.
            outdentToken(moveOut, noNewlines, outdentLength) {
                var decreasedIndent, dent, lastIndent, ref;
                decreasedIndent = this.indent - moveOut;
                while (moveOut > 0) {
                    lastIndent = this.indents[this.indents.length - 1];
                    if (!lastIndent) {
                        this.outdebt = moveOut = 0;
                    }
                    else if (this.outdebt && moveOut <= this.outdebt) {
                        this.outdebt -= moveOut;
                        moveOut = 0;
                    }
                    else {
                        dent = this.indents.pop() + this.outdebt;
                        if (outdentLength && (ref = this.chunk[outdentLength], indexOf.call(INDENTABLE_CLOSERS, ref) >= 0)) {
                            decreasedIndent -= dent - moveOut;
                            moveOut = dent;
                        }
                        this.outdebt = 0;
                        // pair might call outdentToken, so preserve decreasedIndent
                        this.pair('OUTDENT');
                        this.token('OUTDENT', moveOut, 0, outdentLength);
                        moveOut -= dent;
                    }
                }
                if (dent) {
                    this.outdebt -= moveOut;
                }
                this.suppressSemicolons();
                if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
                    this.token('TERMINATOR', '\n', outdentLength, 0);
                }
                this.indent = decreasedIndent;
                this.indentLiteral = this.indentLiteral.slice(0, decreasedIndent);
                return this;
            }
            // Matches and consumes non-meaningful whitespace. Tag the previous token
            // as being “spaced”, because there are some cases where it makes a difference.
            whitespaceToken() {
                var match, nline, prev;
                if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
                    return 0;
                }
                prev = this.prev();
                if (prev) {
                    prev[match ? 'spaced' : 'newLine'] = true;
                }
                if (match) {
                    return match[0].length;
                }
                else {
                    return 0;
                }
            }
            // Generate a newline token. Consecutive newlines get merged together.
            newlineToken(offset) {
                this.suppressSemicolons();
                if (this.tag() !== 'TERMINATOR') {
                    this.token('TERMINATOR', '\n', offset, 0);
                }
                return this;
            }
            // Use a `\` at a line-ending to suppress the newline.
            // The slash is removed here once its job is done.
            suppressNewlines() {
                var prev;
                prev = this.prev();
                if (prev[1] === '\\') {
                    if (prev.comments && this.tokens.length > 1) {
                        // `@tokens.length` should be at least 2 (some code, then `\`).
                        // If something puts a `\` after nothing, they deserve to lose any
                        // comments that trail it.
                        attachCommentsToNode(prev.comments, this.tokens[this.tokens.length - 2]);
                    }
                    this.tokens.pop();
                }
                return this;
            }
            // CSX is like JSX but for CoffeeScript.
            csxToken() {
                var afterTag, colon, csxTag, end, firstChar, id, input, match, origin, prev, prevChar, ref, token, tokens;
                firstChar = this.chunk[0];
                // Check the previous token to detect if attribute is spread.
                prevChar = this.tokens.length > 0 ? this.tokens[this.tokens.length - 1][0] : '';
                if (firstChar === '<') {
                    match = CSX_IDENTIFIER.exec(this.chunk.slice(1)) || CSX_FRAGMENT_IDENTIFIER.exec(this.chunk.slice(1));
                    // Not the right hand side of an unspaced comparison (i.e. `a<b`).
                    if (!(match && (this.csxDepth > 0 || !(prev = this.prev()) || prev.spaced || (ref = prev[0], indexOf.call(COMPARABLE_LEFT_SIDE, ref) < 0)))) {
                        return 0;
                    }
                    [input, id, colon] = match;
                    origin = this.token('CSX_TAG', id, 1, id.length);
                    this.token('CALL_START', '(');
                    this.token('[', '[');
                    this.ends.push({
                        tag: '/>',
                        origin: origin,
                        name: id
                    });
                    this.csxDepth++;
                    return id.length + 1;
                }
                else if (csxTag = this.atCSXTag()) {
                    if (this.chunk.slice(0, 2) === '/>') {
                        this.pair('/>');
                        this.token(']', ']', 0, 2);
                        this.token('CALL_END', ')', 0, 2);
                        this.csxDepth--;
                        return 2;
                    }
                    else if (firstChar === '{') {
                        if (prevChar === ':') {
                            token = this.token('(', '(');
                            this.csxObjAttribute[this.csxDepth] = false;
                        }
                        else {
                            token = this.token('{', '{');
                            this.csxObjAttribute[this.csxDepth] = true;
                        }
                        this.ends.push({
                            tag: '}',
                            origin: token
                        });
                        return 1;
                    }
                    else if (firstChar === '>') {
                        // Ignore terminators inside a tag.
                        this.pair('/>'); // As if the current tag was self-closing.
                        origin = this.token(']', ']');
                        this.token(',', ',');
                        ({
                            tokens,
                            index: end
                        } = this.matchWithInterpolations(INSIDE_CSX, '>', '</', CSX_INTERPOLATION));
                        this.mergeInterpolationTokens(tokens, {
                            delimiter: '"'
                        }, (value, i) => {
                            return this.formatString(value, {
                                delimiter: '>'
                            });
                        });
                        match = CSX_IDENTIFIER.exec(this.chunk.slice(end)) || CSX_FRAGMENT_IDENTIFIER.exec(this.chunk.slice(end));
                        if (!match || match[1] !== csxTag.name) {
                            this.error(`expected corresponding CSX closing tag for ${csxTag.name}`, csxTag.origin[2]);
                        }
                        afterTag = end + csxTag.name.length;
                        if (this.chunk[afterTag] !== '>') {
                            this.error("missing closing > after tag name", {
                                offset: afterTag,
                                length: 1
                            });
                        }
                        // +1 for the closing `>`.
                        this.token('CALL_END', ')', end, csxTag.name.length + 1);
                        this.csxDepth--;
                        return afterTag + 1;
                    }
                    else {
                        return 0;
                    }
                }
                else if (this.atCSXTag(1)) {
                    if (firstChar === '}') {
                        this.pair(firstChar);
                        if (this.csxObjAttribute[this.csxDepth]) {
                            this.token('}', '}');
                            this.csxObjAttribute[this.csxDepth] = false;
                        }
                        else {
                            this.token(')', ')');
                        }
                        this.token(',', ',');
                        return 1;
                    }
                    else {
                        return 0;
                    }
                }
                else {
                    return 0;
                }
            }
            atCSXTag(depth = 0) {
                var i, last, ref;
                if (this.csxDepth === 0) {
                    return false;
                }
                i = this.ends.length - 1;
                while (((ref = this.ends[i]) != null ? ref.tag : void 0) === 'OUTDENT' || depth-- > 0) { // Ignore indents.
                    i--;
                }
                last = this.ends[i];
                return (last != null ? last.tag : void 0) === '/>' && last;
            }
            // We treat all other single characters as a token. E.g.: `( ) , . !`
            // Multi-character operators are also literal tokens, so that Jison can assign
            // the proper order of operations. There are some symbols that we tag specially
            // here. `;` and newlines are both treated as a `TERMINATOR`, we distinguish
            // parentheses that indicate a method call from regular parentheses, and so on.
            literalToken() {
                var match, message, origin, prev, ref, ref1, ref2, ref3, ref4, skipToken, tag, token, value;
                if (match = OPERATOR.exec(this.chunk)) {
                    [value] = match;
                    if (CODE.test(value)) {
                        this.tagParameters();
                    }
                }
                else {
                    value = this.chunk.charAt(0);
                }
                tag = value;
                prev = this.prev();
                if (prev && indexOf.call(['=', ...COMPOUND_ASSIGN], value) >= 0) {
                    skipToken = false;
                    if (value === '=' && ((ref = prev[1]) === '||' || ref === '&&') && !prev.spaced) {
                        prev[0] = 'COMPOUND_ASSIGN';
                        prev[1] += '=';
                        prev = this.tokens[this.tokens.length - 2];
                        skipToken = true;
                    }
                    if (prev && prev[0] !== 'PROPERTY') {
                        origin = (ref1 = prev.origin) != null ? ref1 : prev;
                        message = isUnassignable(prev[1], origin[1]);
                        if (message) {
                            this.error(message, origin[2]);
                        }
                    }
                    if (skipToken) {
                        return value.length;
                    }
                }
                if (value === '{' && this.seenImport) {
                    this.importSpecifierList = true;
                }
                else if (this.importSpecifierList && value === '}') {
                    this.importSpecifierList = false;
                }
                else if (value === '{' && (prev != null ? prev[0] : void 0) === 'EXPORT') {
                    this.exportSpecifierList = true;
                }
                else if (this.exportSpecifierList && value === '}') {
                    this.exportSpecifierList = false;
                }
                if (value === ';') {
                    if (ref2 = prev != null ? prev[0] : void 0, indexOf.call(['=', ...UNFINISHED], ref2) >= 0) {
                        this.error('unexpected ;');
                    }
                    this.seenFor = this.seenImport = this.seenExport = false;
                    tag = 'TERMINATOR';
                }
                else if (value === '*' && (prev != null ? prev[0] : void 0) === 'EXPORT') {
                    tag = 'EXPORT_ALL';
                }
                else if (indexOf.call(MATH, value) >= 0) {
                    tag = 'MATH';
                }
                else if (indexOf.call(COMPARE, value) >= 0) {
                    tag = 'COMPARE';
                }
                else if (indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
                    tag = 'COMPOUND_ASSIGN';
                }
                else if (indexOf.call(UNARY, value) >= 0) {
                    tag = 'UNARY';
                }
                else if (indexOf.call(UNARY_MATH, value) >= 0) {
                    tag = 'UNARY_MATH';
                }
                else if (indexOf.call(SHIFT, value) >= 0) {
                    tag = 'SHIFT';
                }
                else if (value === '?' && (prev != null ? prev.spaced : void 0)) {
                    tag = 'BIN?';
                }
                else if (prev) {
                    if (value === '(' && !prev.spaced && (ref3 = prev[0], indexOf.call(CALLABLE, ref3) >= 0)) {
                        if (prev[0] === '?') {
                            prev[0] = 'FUNC_EXIST';
                        }
                        tag = 'CALL_START';
                    }
                    else if (value === '[' && (((ref4 = prev[0], indexOf.call(INDEXABLE, ref4) >= 0) && !prev.spaced) || (prev[0] === '::'))) { // `.prototype` can’t be a method you can call.
                        tag = 'INDEX_START';
                        switch (prev[0]) {
                            case '?':
                                prev[0] = 'INDEX_SOAK';
                        }
                    }
                }
                token = this.makeToken(tag, value);
                switch (value) {
                    case '(':
                    case '{':
                    case '[':
                        this.ends.push({
                            tag: INVERSES[value],
                            origin: token
                        });
                        break;
                    case ')':
                    case '}':
                    case ']':
                        this.pair(value);
                }
                this.tokens.push(this.makeToken(tag, value));
                return value.length;
            }
            // Token Manipulators
            // ------------------
            // A source of ambiguity in our grammar used to be parameter lists in function
            // definitions versus argument lists in function calls. Walk backwards, tagging
            // parameters specially in order to make things easier for the parser.
            tagParameters() {
                var i, paramEndToken, stack, tok, tokens;
                if (this.tag() !== ')') {
                    return this;
                }
                stack = [];
                ({ tokens } = this);
                i = tokens.length;
                paramEndToken = tokens[--i];
                paramEndToken[0] = 'PARAM_END';
                while (tok = tokens[--i]) {
                    switch (tok[0]) {
                        case ')':
                            stack.push(tok);
                            break;
                        case '(':
                        case 'CALL_START':
                            if (stack.length) {
                                stack.pop();
                            }
                            else if (tok[0] === '(') {
                                tok[0] = 'PARAM_START';
                                return this;
                            }
                            else {
                                paramEndToken[0] = 'CALL_END';
                                return this;
                            }
                    }
                }
                return this;
            }
            // Close up all remaining open blocks at the end of the file.
            closeIndentation() {
                return this.outdentToken(this.indent);
            }
            // Match the contents of a delimited token and expand variables and expressions
            // inside it using Ruby-like notation for substitution of arbitrary
            // expressions.
            //     "Hello #{name.capitalize()}."
            // If it encounters an interpolation, this method will recursively create a new
            // Lexer and tokenize until the `{` of `#{` is balanced with a `}`.
            //  - `regex` matches the contents of a token (but not `delimiter`, and not
            //    `#{` if interpolations are desired).
            //  - `delimiter` is the delimiter of the token. Examples are `'`, `"`, `'''`,
            //    `"""` and `///`.
            //  - `closingDelimiter` is different from `delimiter` only in CSX
            //  - `interpolators` matches the start of an interpolation, for CSX it's both
            //    `{` and `<` (i.e. nested CSX tag)
            // This method allows us to have strings within interpolations within strings,
            // ad infinitum.
            matchWithInterpolations(regex, delimiter, closingDelimiter, interpolators) {
                var braceInterpolator, close, column, firstToken, index, interpolationOffset, interpolator, lastToken, line, match, nested, offsetInChunk, open, ref, rest, str, strPart, tokens;
                if (closingDelimiter == null) {
                    closingDelimiter = delimiter;
                }
                if (interpolators == null) {
                    interpolators = /^#\{/;
                }
                tokens = [];
                offsetInChunk = delimiter.length;
                if (this.chunk.slice(0, offsetInChunk) !== delimiter) {
                    return null;
                }
                str = this.chunk.slice(offsetInChunk);
                while (true) {
                    [strPart] = regex.exec(str);
                    this.validateEscapes(strPart, {
                        isRegex: delimiter.charAt(0) === '/',
                        offsetInChunk
                    });
                    // Push a fake `'NEOSTRING'` token, which will get turned into a real string later.
                    tokens.push(this.makeToken('NEOSTRING', strPart, offsetInChunk));
                    str = str.slice(strPart.length);
                    offsetInChunk += strPart.length;
                    if (!(match = interpolators.exec(str))) {
                        break;
                    }
                    [interpolator] = match;
                    // To remove the `#` in `#{`.
                    interpolationOffset = interpolator.length - 1;
                    [line, column] = this.getLineAndColumnFromChunk(offsetInChunk + interpolationOffset);
                    rest = str.slice(interpolationOffset);
                    ({
                        tokens: nested,
                        index
                    } = new Lexer().tokenize(rest, {
                        line: line,
                        column: column,
                        untilBalanced: true
                    }));
                    // Account for the `#` in `#{`
                    index += interpolationOffset;
                    braceInterpolator = str[index - 1] === '}';
                    if (braceInterpolator) {
                        // Turn the leading and trailing `{` and `}` into parentheses. Unnecessary
                        // parentheses will be removed later.
                        [open] = nested, [close] = slice.call(nested, -1);
                        open[0] = open[1] = '(';
                        close[0] = close[1] = ')';
                        close.origin = ['', 'end of interpolation', close[2]];
                    }
                    if (((ref = nested[1]) != null ? ref[0] : void 0) === 'TERMINATOR') {
                        // Remove leading `'TERMINATOR'` (if any).
                        nested.splice(1, 1);
                    }
                    if (!braceInterpolator) {
                        // We are not using `{` and `}`, so wrap the interpolated tokens instead.
                        open = this.makeToken('(', '(', offsetInChunk, 0);
                        close = this.makeToken(')', ')', offsetInChunk + index, 0);
                        nested = [open, ...nested, close];
                    }
                    // Push a fake `'TOKENS'` token, which will get turned into real tokens later.
                    tokens.push(['TOKENS', nested]);
                    str = str.slice(index);
                    offsetInChunk += index;
                }
                if (str.slice(0, closingDelimiter.length) !== closingDelimiter) {
                    this.error(`missing ${closingDelimiter}`, {
                        length: delimiter.length
                    });
                }
                [firstToken] = tokens, [lastToken] = slice.call(tokens, -1);
                firstToken[2].first_column -= delimiter.length;
                if (lastToken[1].substr(-1) === '\n') {
                    lastToken[2].last_line += 1;
                    lastToken[2].last_column = closingDelimiter.length - 1;
                }
                else {
                    lastToken[2].last_column += closingDelimiter.length;
                }
                if (lastToken[1].length === 0) {
                    lastToken[2].last_column -= 1;
                }
                return {
                    tokens,
                    index: offsetInChunk + closingDelimiter.length
                };
            }
            // Merge the array `tokens` of the fake token types `'TOKENS'` and `'NEOSTRING'`
            // (as returned by `matchWithInterpolations`) into the token stream. The value
            // of `'NEOSTRING'`s are converted using `fn` and turned into strings using
            // `options` first.
            mergeInterpolationTokens(tokens, options, fn) {
                var converted, firstEmptyStringIndex, firstIndex, i, j, k, lastToken, len, len1, locationToken, lparen, placeholderToken, plusToken, rparen, tag, token, tokensToPush, val, value;
                if (tokens.length > 1) {
                    lparen = this.token('STRING_START', '(', 0, 0);
                }
                firstIndex = this.tokens.length;
                for (i = j = 0, len = tokens.length; j < len; i = ++j) {
                    token = tokens[i];
                    [tag, value] = token;
                    switch (tag) {
                        case 'TOKENS':
                            if (value.length === 2) {
                                if (!(value[0].comments || value[1].comments)) {
                                    // Optimize out empty interpolations (an empty pair of parentheses).
                                    continue;
                                }
                                // There are comments (and nothing else) in this interpolation.
                                if (this.csxDepth === 0) {
                                    // This is an interpolated string, not a CSX tag; and for whatever
                                    // reason `` `a${/*test*/}b` `` is invalid JS. So compile to
                                    // `` `a${/*test*/''}b` `` instead.
                                    placeholderToken = this.makeToken('STRING', "''");
                                }
                                else {
                                    placeholderToken = this.makeToken('JS', '');
                                }
                                // Use the same location data as the first parenthesis.
                                placeholderToken[2] = value[0][2];
                                for (k = 0, len1 = value.length; k < len1; k++) {
                                    val = value[k];
                                    if (!val.comments) {
                                        continue;
                                    }
                                    if (placeholderToken.comments == null) {
                                        placeholderToken.comments = [];
                                    }
                                    placeholderToken.comments.push(...val.comments);
                                }
                                value.splice(1, 0, placeholderToken);
                            }
                            // Push all the tokens in the fake `'TOKENS'` token. These already have
                            // sane location data.
                            locationToken = value[0];
                            tokensToPush = value;
                            break;
                        case 'NEOSTRING':
                            // Convert `'NEOSTRING'` into `'STRING'`.
                            converted = fn.call(this, token[1], i);
                            // Optimize out empty strings. We ensure that the tokens stream always
                            // starts with a string token, though, to make sure that the result
                            // really is a string.
                            if (converted.length === 0) {
                                if (i === 0) {
                                    firstEmptyStringIndex = this.tokens.length;
                                }
                                else {
                                    continue;
                                }
                            }
                            // However, there is one case where we can optimize away a starting
                            // empty string.
                            if (i === 2 && (firstEmptyStringIndex != null)) {
                                this.tokens.splice(firstEmptyStringIndex, 2); // Remove empty string and the plus.
                            }
                            token[0] = 'STRING';
                            token[1] = this.makeDelimitedLiteral(converted, options);
                            locationToken = token;
                            tokensToPush = [token];
                    }
                    if (this.tokens.length > firstIndex) {
                        // Create a 0-length "+" token.
                        plusToken = this.token('+', '+');
                        plusToken[2] = {
                            first_line: locationToken[2].first_line,
                            first_column: locationToken[2].first_column,
                            last_line: locationToken[2].first_line,
                            last_column: locationToken[2].first_column
                        };
                    }
                    this.tokens.push(...tokensToPush);
                }
                if (lparen) {
                    [lastToken] = slice.call(tokens, -1);
                    lparen.origin = [
                        'STRING',
                        null,
                        {
                            first_line: lparen[2].first_line,
                            first_column: lparen[2].first_column,
                            last_line: lastToken[2].last_line,
                            last_column: lastToken[2].last_column
                        }
                    ];
                    lparen[2] = lparen.origin[2];
                    rparen = this.token('STRING_END', ')');
                    return rparen[2] = {
                        first_line: lastToken[2].last_line,
                        first_column: lastToken[2].last_column,
                        last_line: lastToken[2].last_line,
                        last_column: lastToken[2].last_column
                    };
                }
            }
            // Pairs up a closing token, ensuring that all listed pairs of tokens are
            // correctly balanced throughout the course of the token stream.
            pair(tag) {
                var lastIndent, prev, ref, ref1, wanted;
                ref = this.ends, [prev] = slice.call(ref, -1);
                if (tag !== (wanted = prev != null ? prev.tag : void 0)) {
                    if ('OUTDENT' !== wanted) {
                        this.error(`unmatched ${tag}`);
                    }
                    // Auto-close `INDENT` to support syntax like this:
                    //     el.click((event) ->
                    //       el.hide())
                    ref1 = this.indents, [lastIndent] = slice.call(ref1, -1);
                    this.outdentToken(lastIndent, true);
                    return this.pair(tag);
                }
                return this.ends.pop();
            }
            // Helpers
            // -------
            // Returns the line and column number from an offset into the current chunk.
            // `offset` is a number of characters into `@chunk`.
            getLineAndColumnFromChunk(offset) {
                var column, lastLine, lineCount, ref, string;
                if (offset === 0) {
                    return [this.chunkLine, this.chunkColumn];
                }
                if (offset >= this.chunk.length) {
                    string = this.chunk;
                }
                else {
                    string = this.chunk.slice(0, +(offset - 1) + 1 || 9e9);
                }
                lineCount = count(string, '\n');
                column = this.chunkColumn;
                if (lineCount > 0) {
                    ref = string.split('\n'), [lastLine] = slice.call(ref, -1);
                    column = lastLine.length;
                }
                else {
                    column += string.length;
                }
                return [this.chunkLine + lineCount, column];
            }
            // Same as `token`, except this just returns the token without adding it
            // to the results.
            makeToken(tag, value, offsetInChunk = 0, length = value.length) {
                var lastCharacter, locationData, token;
                locationData = {};
                [locationData.first_line, locationData.first_column] = this.getLineAndColumnFromChunk(offsetInChunk);
                // Use length - 1 for the final offset - we're supplying the last_line and the last_column,
                // so if last_column == first_column, then we're looking at a character of length 1.
                lastCharacter = length > 0 ? length - 1 : 0;
                [locationData.last_line, locationData.last_column] = this.getLineAndColumnFromChunk(offsetInChunk + lastCharacter);
                token = [tag, value, locationData];
                return token;
            }
            // Add a token to the results.
            // `offset` is the offset into the current `@chunk` where the token starts.
            // `length` is the length of the token in the `@chunk`, after the offset.  If
            // not specified, the length of `value` will be used.
            // Returns the new token.
            token(tag, value, offsetInChunk, length, origin) {
                var token;
                token = this.makeToken(tag, value, offsetInChunk, length);
                if (origin) {
                    token.origin = origin;
                }
                this.tokens.push(token);
                return token;
            }
            // Peek at the last tag in the token stream.
            tag() {
                var ref, token;
                ref = this.tokens, [token] = slice.call(ref, -1);
                return token != null ? token[0] : void 0;
            }
            // Peek at the last value in the token stream.
            value(useOrigin = false) {
                var ref, ref1, token;
                ref = this.tokens, [token] = slice.call(ref, -1);
                if (useOrigin && ((token != null ? token.origin : void 0) != null)) {
                    return (ref1 = token.origin) != null ? ref1[1] : void 0;
                }
                else {
                    return token != null ? token[1] : void 0;
                }
            }
            // Get the previous token in the token stream.
            prev() {
                return this.tokens[this.tokens.length - 1];
            }
            // Are we in the midst of an unfinished expression?
            unfinished() {
                var ref;
                return LINE_CONTINUER.test(this.chunk) || (ref = this.tag(), indexOf.call(UNFINISHED, ref) >= 0);
            }
            formatString(str, options) {
                return this.replaceUnicodeCodePointEscapes(str.replace(STRING_OMIT, '$1'), options);
            }
            formatHeregex(str, options) {
                return this.formatRegex(str.replace(HEREGEX_OMIT, '$1$2'), merge(options, {
                    delimiter: '///'
                }));
            }
            formatRegex(str, options) {
                return this.replaceUnicodeCodePointEscapes(str, options);
            }
            unicodeCodePointToUnicodeEscapes(codePoint) {
                var high, low, toUnicodeEscape;
                toUnicodeEscape = function (val) {
                    var str;
                    str = val.toString(16);
                    return `\\u${repeat('0', 4 - str.length)}${str}`;
                };
                if (codePoint < 0x10000) {
                    return toUnicodeEscape(codePoint);
                }
                // surrogate pair
                high = Math.floor((codePoint - 0x10000) / 0x400) + 0xD800;
                low = (codePoint - 0x10000) % 0x400 + 0xDC00;
                return `${toUnicodeEscape(high)}${toUnicodeEscape(low)}`;
            }
            // Replace `\u{...}` with `\uxxxx[\uxxxx]` in regexes without `u` flag
            replaceUnicodeCodePointEscapes(str, options) {
                var shouldReplace;
                shouldReplace = (options.flags != null) && indexOf.call(options.flags, 'u') < 0;
                return str.replace(UNICODE_CODE_POINT_ESCAPE, (match, escapedBackslash, codePointHex, offset) => {
                    var codePointDecimal;
                    if (escapedBackslash) {
                        return escapedBackslash;
                    }
                    codePointDecimal = parseInt(codePointHex, 16);
                    if (codePointDecimal > 0x10ffff) {
                        this.error("unicode code point escapes greater than \\u{10ffff} are not allowed", {
                            offset: offset + options.delimiter.length,
                            length: codePointHex.length + 4
                        });
                    }
                    if (!shouldReplace) {
                        return match;
                    }
                    return this.unicodeCodePointToUnicodeEscapes(codePointDecimal);
                });
            }
            // Validates escapes in strings and regexes.
            validateEscapes(str, options = {}) {
                var before, hex, invalidEscape, invalidEscapeRegex, match, message, octal, ref, unicode, unicodeCodePoint;
                invalidEscapeRegex = options.isRegex ? REGEX_INVALID_ESCAPE : STRING_INVALID_ESCAPE;
                match = invalidEscapeRegex.exec(str);
                if (!match) {
                    return;
                }
                match[0], before = match[1], octal = match[2], hex = match[3], unicodeCodePoint = match[4], unicode = match[5];
                message = octal ? "octal escape sequences are not allowed" : "invalid escape sequence";
                invalidEscape = `\\${octal || hex || unicodeCodePoint || unicode}`;
                return this.error(`${message} ${invalidEscape}`, {
                    offset: ((ref = options.offsetInChunk) != null ? ref : 0) + match.index + before.length,
                    length: invalidEscape.length
                });
            }
            // Constructs a string or regex by escaping certain characters.
            makeDelimitedLiteral(body, options = {}) {
                var regex;
                if (body === '' && options.delimiter === '/') {
                    body = '(?:)';
                }
                regex = RegExp(`(\\\\\\\\)|(\\\\0(?=[1-7]))|\\\\?(${options.delimiter // Escaped backslash.
                // Null character mistaken as octal escape.
                // (Possibly escaped) delimiter.
                // (Possibly escaped) newlines.
                // Other escapes.
                })|\\\\?(?:(\\n)|(\\r)|(\\u2028)|(\\u2029))|(\\\\.)`, "g");
                body = body.replace(regex, function (match, backslash, nul, delimiter, lf, cr, ls, ps, other) {
                    switch (false) {
                        // Ignore escaped backslashes.
                        case !backslash:
                            if (options.double) {
                                return backslash + backslash;
                            }
                            else {
                                return backslash;
                            }
                        case !nul:
                            return '\\x00';
                        case !delimiter:
                            return `\\${delimiter}`;
                        case !lf:
                            return '\\n';
                        case !cr:
                            return '\\r';
                        case !ls:
                            return '\\u2028';
                        case !ps:
                            return '\\u2029';
                        case !other:
                            if (options.double) {
                                return `\\${other}`;
                            }
                            else {
                                return other;
                            }
                    }
                });
                return `${options.delimiter}${body}${options.delimiter}`;
            }
            suppressSemicolons() {
                var ref, ref1, results;
                results = [];
                while (this.value() === ';') {
                    this.tokens.pop();
                    if (ref = (ref1 = this.prev()) != null ? ref1[0] : void 0, indexOf.call(['=', ...UNFINISHED], ref) >= 0) {
                        results.push(this.error('unexpected ;'));
                    }
                    else {
                        results.push(void 0);
                    }
                }
                return results;
            }
            // Throws an error at either a given offset from the current chunk or at the
            // location of a token (`token[2]`).
            error(message, options = {}) {
                var first_column, first_line, location, ref, ref1;
                location = 'first_line' in options ? options : ([first_line, first_column] = this.getLineAndColumnFromChunk((ref = options.offset) != null ? ref : 0), {
                    first_line,
                    first_column,
                    last_column: first_column + ((ref1 = options.length) != null ? ref1 : 1) - 1
                });
                return throwSyntaxError(message, location);
            }
        };
        // Helper functions
        // ----------------
        isUnassignable = function (name, displayName = name) {
            switch (false) {
                case indexOf.call([...JS_KEYWORDS, ...COFFEE_KEYWORDS], name) < 0:
                    return `keyword '${displayName}' can't be assigned`;
                case indexOf.call(STRICT_PROSCRIBED, name) < 0:
                    return `'${displayName}' can't be assigned`;
                case indexOf.call(RESERVED, name) < 0:
                    return `reserved word '${displayName}' can't be assigned`;
                default:
                    return false;
            }
        };
        exports.isUnassignable = isUnassignable;
        // `from` isn’t a CoffeeScript keyword, but it behaves like one in `import` and
        // `export` statements (handled above) and in the declaration line of a `for`
        // loop. Try to detect when `from` is a variable identifier and when it is this
        // “sometimes” keyword.
        isForFrom = function (prev) {
            var ref;
            if (prev[0] === 'IDENTIFIER') {
                // `for i from from`, `for from from iterable`
                if (prev[1] === 'from') {
                    prev[1][0] = 'IDENTIFIER';
                    true;
                }
                // `for i from iterable`
                return true;
                // `for from…`
            }
            else if (prev[0] === 'FOR') {
                return false;
                // `for {from}…`, `for [from]…`, `for {a, from}…`, `for {a: from}…`
            }
            else if ((ref = prev[1]) === '{' || ref === '[' || ref === ',' || ref === ':') {
                return false;
            }
            else {
                return true;
            }
        };
        // Constants
        // ---------
        // Keywords that CoffeeScript shares in common with JavaScript.
        JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'yield', 'await', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super', 'import', 'export', 'default'];
        // CoffeeScript-only keywords.
        COFFEE_KEYWORDS = ['undefined', 'Infinity', 'NaN', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
        COFFEE_ALIAS_MAP = {
            and: '&&',
            or: '||',
            is: '==',
            isnt: '!=',
            not: '!',
            yes: 'true',
            no: 'false',
            on: 'true',
            off: 'false'
        };
        COFFEE_ALIASES = (function () {
            var results;
            results = [];
            for (key in COFFEE_ALIAS_MAP) {
                results.push(key);
            }
            return results;
        })();
        COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
        // The list of keywords that are reserved by JavaScript, but not used, or are
        // used by CoffeeScript internally. We throw an error when these are encountered,
        // to avoid having a JavaScript error at runtime.
        RESERVED = ['case', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'native', 'implements', 'interface', 'package', 'private', 'protected', 'public', 'static'];
        STRICT_PROSCRIBED = ['arguments', 'eval'];
        // The superset of both JavaScript keywords and reserved words, none of which may
        // be used as identifiers or properties.
        exports.JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);
        // The character code of the nasty Microsoft madness otherwise known as the BOM.
        BOM = 65279;
        // Token matching regexes.
        IDENTIFIER = /^(?!\d)((?:(?!\s)[$\w\x7f-\uffff])+)([^\n\S]*:(?!:))?/; // Is this a property name?
        CSX_IDENTIFIER = /^(?![\d<])((?:(?!\s)[\.\-$\w\x7f-\uffff])+)/; // Must not start with `<`.
        // Like `IDENTIFIER`, but includes `-`s and `.`s.
        // Fragment: <></>
        CSX_FRAGMENT_IDENTIFIER = /^()>/; // Ends immediately with `>`.
        CSX_ATTRIBUTE = /^(?!\d)((?:(?!\s)[\-$\w\x7f-\uffff])+)([^\S]*=(?!=))?/; // Like `IDENTIFIER`, but includes `-`s.
        // Is this an attribute with a value?
        NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; // binary
        // octal
        // hex
        // decimal
        OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>*\/%])\2=?|\?(\.|::)|\.{2,3})/; // function
        // compound assign / compare
        // zero-fill right shift
        // doubles
        // logic / shift / power / floor division / modulo
        // soak access
        // range or splat
        WHITESPACE = /^[^\n\S]+/;
        COMMENT = /^\s*###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/;
        CODE = /^[-=]>/;
        MULTI_DENT = /^(?:\n[^\n\S]*)+/;
        JSTOKEN = /^`(?!``)((?:[^`\\]|\\[\s\S])*)`/;
        HERE_JSTOKEN = /^```((?:[^`\\]|\\[\s\S]|`(?!``))*)```/;
        // String-matching-regexes.
        STRING_START = /^(?:'''|"""|'|")/;
        STRING_SINGLE = /^(?:[^\\']|\\[\s\S])*/;
        STRING_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|\#(?!\{))*/;
        HEREDOC_SINGLE = /^(?:[^\\']|\\[\s\S]|'(?!''))*/;
        HEREDOC_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|"(?!"")|\#(?!\{))*/;
        INSIDE_CSX = /^(?:[^\{<])*/; // Start of CoffeeScript interpolation. // Similar to `HEREDOC_DOUBLE` but there is no escaping.
        // Maybe CSX tag (`<` not allowed even if bare).
        CSX_INTERPOLATION = /^(?:\{|<(?!\/))/; // CoffeeScript interpolation.
        // CSX opening tag.
        STRING_OMIT = /((?:\\\\)+)|\\[^\S\n]*\n\s*/g; // Consume (and preserve) an even number of backslashes.
        // Remove escaped newlines.
        SIMPLE_STRING_OMIT = /\s*\n\s*/g;
        HEREDOC_INDENT = /\n+([^\n\S]*)(?=\S)/g;
        // Regex-matching-regexes.
        REGEX = /^\/(?!\/)((?:[^[\/\n\\]|\\[^\n]|\[(?:\\[^\n]|[^\]\n\\])*\])*)(\/)?/; // Every other thing.
        // Anything but newlines escaped.
        // Character class.
        REGEX_FLAGS = /^\w*/;
        VALID_FLAGS = /^(?!.*(.).*\1)[gimsuy]*$/;
        // Match any character, except those that need special handling below.
        // Match `\` followed by any character.
        // Match any `/` except `///`.
        // Match `#` which is not part of interpolation, e.g. `#{}`.
        // Comments consume everything until the end of the line, including `///`.
        HEREGEX = /^(?:[^\\\/#\s]|\\[\s\S]|\/(?!\/\/)|\#(?!\{)|\s+(?:#(?!\{).*)?)*/;
        HEREGEX_OMIT = /((?:\\\\)+)|\\(\s)|\s+(?:#.*)?/g; // Consume (and preserve) an even number of backslashes.
        // Preserve escaped whitespace.
        // Remove whitespace and comments.
        REGEX_ILLEGAL = /^(\/|\/{3}\s*)(\*)/;
        POSSIBLY_DIVISION = /^\/=?\s/;
        // Other regexes.
        HERECOMMENT_ILLEGAL = /\*\//;
        LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;
        STRING_INVALID_ESCAPE = /((?:^|[^\\])(?:\\\\)*)\\(?:(0[0-7]|[1-7])|(x(?![\da-fA-F]{2}).{0,2})|(u\{(?![\da-fA-F]{1,}\})[^}]*\}?)|(u(?!\{|[\da-fA-F]{4}).{0,4}))/; // Make sure the escape isn’t escaped.
        // octal escape
        // hex escape
        // unicode code point escape
        // unicode escape
        REGEX_INVALID_ESCAPE = /((?:^|[^\\])(?:\\\\)*)\\(?:(0[0-7])|(x(?![\da-fA-F]{2}).{0,2})|(u\{(?![\da-fA-F]{1,}\})[^}]*\}?)|(u(?!\{|[\da-fA-F]{4}).{0,4}))/; // Make sure the escape isn’t escaped.
        // octal escape
        // hex escape
        // unicode code point escape
        // unicode escape
        UNICODE_CODE_POINT_ESCAPE = /(\\\\)|\\u\{([\da-fA-F]+)\}/g; // Make sure the escape isn’t escaped.
        LEADING_BLANK_LINE = /^[^\n\S]*\n/;
        TRAILING_BLANK_LINE = /\n[^\n\S]*$/;
        TRAILING_SPACES = /\s+$/;
        // Compound assignment tokens.
        COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=', '**=', '//=', '%%='];
        // Unary tokens.
        UNARY = ['NEW', 'TYPEOF', 'DELETE', 'DO'];
        UNARY_MATH = ['!', '~'];
        // Bit-shifting tokens.
        SHIFT = ['<<', '>>', '>>>'];
        // Comparison tokens.
        COMPARE = ['==', '!=', '<', '>', '<=', '>='];
        // Mathematical tokens.
        MATH = ['*', '/', '%', '//', '%%'];
        // Relational tokens that are negatable with `not` prefix.
        RELATION = ['IN', 'OF', 'INSTANCEOF'];
        // Boolean tokens.
        BOOL = ['TRUE', 'FALSE'];
        // Tokens which could legitimately be invoked or indexed. An opening
        // parentheses or bracket following these tokens will be recorded as the start
        // of a function invocation or indexing operation.
        CALLABLE = ['IDENTIFIER', 'PROPERTY', ')', ']', '?', '@', 'THIS', 'SUPER'];
        INDEXABLE = CALLABLE.concat(['NUMBER', 'INFINITY', 'NAN', 'STRING', 'STRING_END', 'REGEX', 'REGEX_END', 'BOOL', 'NULL', 'UNDEFINED', '}', '::']);
        // Tokens which can be the left-hand side of a less-than comparison, i.e. `a<b`.
        COMPARABLE_LEFT_SIDE = ['IDENTIFIER', ')', ']', 'NUMBER'];
        // Tokens which a regular expression will never immediately follow (except spaced
        // CALLABLEs in some cases), but which a division operator can.
        // See: http://www-archive.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
        NOT_REGEX = INDEXABLE.concat(['++', '--']);
        // Tokens that, when immediately preceding a `WHEN`, indicate that the `WHEN`
        // occurs at the start of a line. We disambiguate these from trailing whens to
        // avoid an ambiguity in the grammar.
        LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
        // Additional indent in front of these is ignored.
        INDENTABLE_CLOSERS = [')', '}', ']'];
        // Tokens that, when appearing at the end of a line, suppress a following TERMINATOR/INDENT token
        UNFINISHED = ['\\', '.', '?.', '?::', 'UNARY', 'MATH', 'UNARY_MATH', '+', '-', '**', 'SHIFT', 'RELATION', 'COMPARE', '&', '^', '|', '&&', '||', 'BIN?', 'EXTENDS'];
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/nodes */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // `nodes.coffee` contains all of the node classes for the syntax tree. Most
        // nodes are created as the result of actions in the [grammar](grammar.html),
        // but some are created by other nodes as a method of code generation. To convert
        // the syntax tree into a string of JavaScript code, call `compile()` on the root.
        var Access, Arr, Assign, AwaitReturn, Base, Block, BooleanLiteral, CSXTag, Call, Class, Code, CodeFragment, ComputedPropertyName, Elision, ExecutableClassBody, Existence, Expansion, ExportAllDeclaration, ExportDeclaration, ExportDefaultDeclaration, ExportNamedDeclaration, ExportSpecifier, ExportSpecifierList, Extends, For, FuncGlyph, HereComment, HoistTarget, IdentifierLiteral, If, ImportClause, ImportDeclaration, ImportDefaultSpecifier, ImportNamespaceSpecifier, ImportSpecifier, ImportSpecifierList, In, Index, InfinityLiteral, JS_FORBIDDEN, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, LineComment, Literal, ModuleDeclaration, ModuleSpecifier, ModuleSpecifierList, NEGATE, NO, NaNLiteral, NullLiteral, NumberLiteral, Obj, Op, Param, Parens, PassthroughLiteral, PropertyName, Range, RegexLiteral, RegexWithInterpolations, Return, SIMPLENUM, Scope, Slice, Splat, StatementLiteral, StringLiteral, StringWithInterpolations, Super, SuperCall, Switch, TAB, THIS, TaggedTemplateCall, ThisLiteral, Throw, Try, UTILITIES, UndefinedLiteral, Value, While, YES, YieldReturn, addDataToNode, attachCommentsToNode, compact, del, ends, extend, flatten, fragmentsToText, hasLineComments, indentInitial, isLiteralArguments, isLiteralThis, isUnassignable, locationDataToString, merge, moveComments, multident, shouldCacheOrIsAssignable, some, starts, throwSyntaxError, unfoldSoak, unshiftAfterComments, utility, indexOf = [].indexOf, splice = [].splice, slice1 = [].slice;
        Error.stackTraceLimit = 2e308;
        ({ Scope } = require(83) /* ./scope */);
        ({ isUnassignable, JS_FORBIDDEN } = require(78) /* ./lexer */);
        // Import the helpers we plan to use.
        ({ compact, flatten, extend, merge, del, starts, ends, some, addDataToNode, attachCommentsToNode, locationDataToString, throwSyntaxError } = require(76) /* ./helpers */);
        // Functions required by parser.
        exports.extend = extend;
        exports.addDataToNode = addDataToNode;
        // Constant functions for nodes that don’t need customization.
        YES = function () {
            return true;
        };
        NO = function () {
            return false;
        };
        THIS = function () {
            return this;
        };
        NEGATE = function () {
            this.negated = !this.negated;
            return this;
        };
        //### CodeFragment
        // The various nodes defined below all compile to a collection of **CodeFragment** objects.
        // A CodeFragments is a block of generated code, and the location in the source file where the code
        // came from. CodeFragments can be assembled together into working code just by catting together
        // all the CodeFragments' `code` snippets, in order.
        exports.CodeFragment = CodeFragment = class CodeFragment {
            constructor(parent, code) {
                var ref1;
                this.code = `${code}`;
                this.type = (parent != null ? (ref1 = parent.constructor) != null ? ref1.name : void 0 : void 0) || 'unknown';
                this.locationData = parent != null ? parent.locationData : void 0;
                this.comments = parent != null ? parent.comments : void 0;
            }
            toString() {
                // This is only intended for debugging.
                return `${this.code}${(this.locationData ? ": " + locationDataToString(this.locationData) : '')}`;
            }
        };
        // Convert an array of CodeFragments into a string.
        fragmentsToText = function (fragments) {
            var fragment;
            return ((function () {
                var j, len1, results;
                results = [];
                for (j = 0, len1 = fragments.length; j < len1; j++) {
                    fragment = fragments[j];
                    results.push(fragment.code);
                }
                return results;
            })()).join('');
        };
        //### Base
        // The **Base** is the abstract base class for all nodes in the syntax tree.
        // Each subclass implements the `compileNode` method, which performs the
        // code generation for that node. To compile a node to JavaScript,
        // call `compile` on it, which wraps `compileNode` in some generic extra smarts,
        // to know when the generated code needs to be wrapped up in a closure.
        // An options hash is passed and cloned throughout, containing information about
        // the environment from higher in the tree (such as if a returned value is
        // being requested by the surrounding function), information about the current
        // scope, and indentation level.
        exports.Base = Base = (function () {
            class Base {
                compile(o, lvl) {
                    return fragmentsToText(this.compileToFragments(o, lvl));
                }
                // Occasionally a node is compiled multiple times, for example to get the name
                // of a variable to add to scope tracking. When we know that a “premature”
                // compilation won’t result in comments being output, set those comments aside
                // so that they’re preserved for a later `compile` call that will result in
                // the comments being included in the output.
                compileWithoutComments(o, lvl, method = 'compile') {
                    var fragments, unwrapped;
                    if (this.comments) {
                        this.ignoreTheseCommentsTemporarily = this.comments;
                        delete this.comments;
                    }
                    unwrapped = this.unwrapAll();
                    if (unwrapped.comments) {
                        unwrapped.ignoreTheseCommentsTemporarily = unwrapped.comments;
                        delete unwrapped.comments;
                    }
                    fragments = this[method](o, lvl);
                    if (this.ignoreTheseCommentsTemporarily) {
                        this.comments = this.ignoreTheseCommentsTemporarily;
                        delete this.ignoreTheseCommentsTemporarily;
                    }
                    if (unwrapped.ignoreTheseCommentsTemporarily) {
                        unwrapped.comments = unwrapped.ignoreTheseCommentsTemporarily;
                        delete unwrapped.ignoreTheseCommentsTemporarily;
                    }
                    return fragments;
                }
                compileNodeWithoutComments(o, lvl) {
                    return this.compileWithoutComments(o, lvl, 'compileNode');
                }
                // Common logic for determining whether to wrap this node in a closure before
                // compiling it, or to compile directly. We need to wrap if this node is a
                // *statement*, and it's not a *pureStatement*, and we're not at
                // the top level of a block (which would be unnecessary), and we haven't
                // already been asked to return the result (because statements know how to
                // return results).
                compileToFragments(o, lvl) {
                    var fragments, node;
                    o = extend({}, o);
                    if (lvl) {
                        o.level = lvl;
                    }
                    node = this.unfoldSoak(o) || this;
                    node.tab = o.indent;
                    fragments = o.level === LEVEL_TOP || !node.isStatement(o) ? node.compileNode(o) : node.compileClosure(o);
                    this.compileCommentFragments(o, node, fragments);
                    return fragments;
                }
                compileToFragmentsWithoutComments(o, lvl) {
                    return this.compileWithoutComments(o, lvl, 'compileToFragments');
                }
                // Statements converted into expressions via closure-wrapping share a scope
                // object with their parent closure, to preserve the expected lexical scope.
                compileClosure(o) {
                    var args, argumentsNode, func, jumpNode, meth, parts, ref1, ref2;
                    if (jumpNode = this.jumps()) {
                        jumpNode.error('cannot use a pure statement in an expression');
                    }
                    o.sharedScope = true;
                    func = new Code([], Block.wrap([this]));
                    args = [];
                    if (this.contains((function (node) {
                        return node instanceof SuperCall;
                    }))) {
                        func.bound = true;
                    }
                    else if ((argumentsNode = this.contains(isLiteralArguments)) || this.contains(isLiteralThis)) {
                        args = [new ThisLiteral];
                        if (argumentsNode) {
                            meth = 'apply';
                            args.push(new IdentifierLiteral('arguments'));
                        }
                        else {
                            meth = 'call';
                        }
                        func = new Value(func, [new Access(new PropertyName(meth))]);
                    }
                    parts = (new Call(func, args)).compileNode(o);
                    switch (false) {
                        case !(func.isGenerator || ((ref1 = func.base) != null ? ref1.isGenerator : void 0)):
                            parts.unshift(this.makeCode("(yield* "));
                            parts.push(this.makeCode(")"));
                            break;
                        case !(func.isAsync || ((ref2 = func.base) != null ? ref2.isAsync : void 0)):
                            parts.unshift(this.makeCode("(await "));
                            parts.push(this.makeCode(")"));
                    }
                    return parts;
                }
                compileCommentFragments(o, node, fragments) {
                    var base1, base2, comment, commentFragment, j, len1, ref1, unshiftCommentFragment;
                    if (!node.comments) {
                        return fragments;
                    }
                    // This is where comments, that are attached to nodes as a `comments`
                    // property, become `CodeFragment`s. “Inline block comments,” e.g.
                    // `/* */`-delimited comments that are interspersed within code on a line,
                    // are added to the current `fragments` stream. All other fragments are
                    // attached as properties to the nearest preceding or following fragment,
                    // to remain stowaways until they get properly output in `compileComments`
                    // later on.
                    unshiftCommentFragment = function (commentFragment) {
                        var precedingFragment;
                        if (commentFragment.unshift) {
                            // Find the first non-comment fragment and insert `commentFragment`
                            // before it.
                            return unshiftAfterComments(fragments, commentFragment);
                        }
                        else {
                            if (fragments.length !== 0) {
                                precedingFragment = fragments[fragments.length - 1];
                                if (commentFragment.newLine && precedingFragment.code !== '' && !/\n\s*$/.test(precedingFragment.code)) {
                                    commentFragment.code = `\n${commentFragment.code}`;
                                }
                            }
                            return fragments.push(commentFragment);
                        }
                    };
                    ref1 = node.comments;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        comment = ref1[j];
                        if (!(indexOf.call(this.compiledComments, comment) < 0)) {
                            continue;
                        }
                        this.compiledComments.push(comment); // Don’t output this comment twice.
                        // For block/here comments, denoted by `###`, that are inline comments
                        // like `1 + ### comment ### 2`, create fragments and insert them into
                        // the fragments array.
                        // Otherwise attach comment fragments to their closest fragment for now,
                        // so they can be inserted into the output later after all the newlines
                        // have been added.
                        if (comment.here) { // Block comment, delimited by `###`.
                            commentFragment = new HereComment(comment).compileNode(o); // Line comment, delimited by `#`.
                        }
                        else {
                            commentFragment = new LineComment(comment).compileNode(o);
                        }
                        if ((commentFragment.isHereComment && !commentFragment.newLine) || node.includeCommentFragments()) {
                            // Inline block comments, like `1 + /* comment */ 2`, or a node whose
                            // `compileToFragments` method has logic for outputting comments.
                            unshiftCommentFragment(commentFragment);
                        }
                        else {
                            if (fragments.length === 0) {
                                fragments.push(this.makeCode(''));
                            }
                            if (commentFragment.unshift) {
                                if ((base1 = fragments[0]).precedingComments == null) {
                                    base1.precedingComments = [];
                                }
                                fragments[0].precedingComments.push(commentFragment);
                            }
                            else {
                                if ((base2 = fragments[fragments.length - 1]).followingComments == null) {
                                    base2.followingComments = [];
                                }
                                fragments[fragments.length - 1].followingComments.push(commentFragment);
                            }
                        }
                    }
                    return fragments;
                }
                // If the code generation wishes to use the result of a complex expression
                // in multiple places, ensure that the expression is only ever evaluated once,
                // by assigning it to a temporary variable. Pass a level to precompile.
                // If `level` is passed, then returns `[val, ref]`, where `val` is the compiled value, and `ref`
                // is the compiled reference. If `level` is not passed, this returns `[val, ref]` where
                // the two values are raw nodes which have not been compiled.
                cache(o, level, shouldCache) {
                    var complex, ref, sub;
                    complex = shouldCache != null ? shouldCache(this) : this.shouldCache();
                    if (complex) {
                        ref = new IdentifierLiteral(o.scope.freeVariable('ref'));
                        sub = new Assign(ref, this);
                        if (level) {
                            return [sub.compileToFragments(o, level), [this.makeCode(ref.value)]];
                        }
                        else {
                            return [sub, ref];
                        }
                    }
                    else {
                        ref = level ? this.compileToFragments(o, level) : this;
                        return [ref, ref];
                    }
                }
                // Occasionally it may be useful to make an expression behave as if it was 'hoisted', whereby the
                // result of the expression is available before its location in the source, but the expression's
                // variable scope corresponds the source position. This is used extensively to deal with executable
                // class bodies in classes.
                // Calling this method mutates the node, proxying the `compileNode` and `compileToFragments`
                // methods to store their result for later replacing the `target` node, which is returned by the
                // call.
                hoist() {
                    var compileNode, compileToFragments, target;
                    this.hoisted = true;
                    target = new HoistTarget(this);
                    compileNode = this.compileNode;
                    compileToFragments = this.compileToFragments;
                    this.compileNode = function (o) {
                        return target.update(compileNode, o);
                    };
                    this.compileToFragments = function (o) {
                        return target.update(compileToFragments, o);
                    };
                    return target;
                }
                cacheToCodeFragments(cacheValues) {
                    return [fragmentsToText(cacheValues[0]), fragmentsToText(cacheValues[1])];
                }
                // Construct a node that returns the current node's result.
                // Note that this is overridden for smarter behavior for
                // many statement nodes (e.g. If, For)...
                makeReturn(res) {
                    var me;
                    me = this.unwrapAll();
                    if (res) {
                        return new Call(new Literal(`${res}.push`), [me]);
                    }
                    else {
                        return new Return(me);
                    }
                }
                // Does this node, or any of its children, contain a node of a certain kind?
                // Recursively traverses down the *children* nodes and returns the first one
                // that verifies `pred`. Otherwise return undefined. `contains` does not cross
                // scope boundaries.
                contains(pred) {
                    var node;
                    node = void 0;
                    this.traverseChildren(false, function (n) {
                        if (pred(n)) {
                            node = n;
                            return false;
                        }
                    });
                    return node;
                }
                // Pull out the last node of a node list.
                lastNode(list) {
                    if (list.length === 0) {
                        return null;
                    }
                    else {
                        return list[list.length - 1];
                    }
                }
                // `toString` representation of the node, for inspecting the parse tree.
                // This is what `coffee --nodes` prints out.
                toString(idt = '', name = this.constructor.name) {
                    var tree;
                    tree = '\n' + idt + name;
                    if (this.soak) {
                        tree += '?';
                    }
                    this.eachChild(function (node) {
                        return tree += node.toString(idt + TAB);
                    });
                    return tree;
                }
                // Passes each child to a function, breaking when the function returns `false`.
                eachChild(func) {
                    var attr, child, j, k, len1, len2, ref1, ref2;
                    if (!this.children) {
                        return this;
                    }
                    ref1 = this.children;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        attr = ref1[j];
                        if (this[attr]) {
                            ref2 = flatten([this[attr]]);
                            for (k = 0, len2 = ref2.length; k < len2; k++) {
                                child = ref2[k];
                                if (func(child) === false) {
                                    return this;
                                }
                            }
                        }
                    }
                    return this;
                }
                traverseChildren(crossScope, func) {
                    return this.eachChild(function (child) {
                        var recur;
                        recur = func(child);
                        if (recur !== false) {
                            return child.traverseChildren(crossScope, func);
                        }
                    });
                }
                // `replaceInContext` will traverse children looking for a node for which `match` returns
                // true. Once found, the matching node will be replaced by the result of calling `replacement`.
                replaceInContext(match, replacement) {
                    var attr, child, children, i, j, k, len1, len2, ref1, ref2;
                    if (!this.children) {
                        return false;
                    }
                    ref1 = this.children;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        attr = ref1[j];
                        if (children = this[attr]) {
                            if (Array.isArray(children)) {
                                for (i = k = 0, len2 = children.length; k < len2; i = ++k) {
                                    child = children[i];
                                    if (match(child)) {
                                        splice.apply(children, [i, i - i + 1].concat(ref2 = replacement(child, this))), ref2;
                                        return true;
                                    }
                                    else {
                                        if (child.replaceInContext(match, replacement)) {
                                            return true;
                                        }
                                    }
                                }
                            }
                            else if (match(children)) {
                                this[attr] = replacement(children, this);
                                return true;
                            }
                            else {
                                if (children.replaceInContext(match, replacement)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
                invert() {
                    return new Op('!', this);
                }
                unwrapAll() {
                    var node;
                    node = this;
                    while (node !== (node = node.unwrap())) {
                        continue;
                    }
                    return node;
                }
                // For this node and all descendents, set the location data to `locationData`
                // if the location data is not already set.
                updateLocationDataIfMissing(locationData) {
                    if (this.locationData && !this.forceUpdateLocation) {
                        return this;
                    }
                    delete this.forceUpdateLocation;
                    this.locationData = locationData;
                    return this.eachChild(function (child) {
                        return child.updateLocationDataIfMissing(locationData);
                    });
                }
                // Throw a SyntaxError associated with this node’s location.
                error(message) {
                    return throwSyntaxError(message, this.locationData);
                }
                makeCode(code) {
                    return new CodeFragment(this, code);
                }
                wrapInParentheses(fragments) {
                    return [this.makeCode('('), ...fragments, this.makeCode(')')];
                }
                wrapInBraces(fragments) {
                    return [this.makeCode('{'), ...fragments, this.makeCode('}')];
                }
                // `fragmentsList` is an array of arrays of fragments. Each array in fragmentsList will be
                // concatenated together, with `joinStr` added in between each, to produce a final flat array
                // of fragments.
                joinFragmentArrays(fragmentsList, joinStr) {
                    var answer, fragments, i, j, len1;
                    answer = [];
                    for (i = j = 0, len1 = fragmentsList.length; j < len1; i = ++j) {
                        fragments = fragmentsList[i];
                        if (i) {
                            answer.push(this.makeCode(joinStr));
                        }
                        answer = answer.concat(fragments);
                    }
                    return answer;
                }
            }
            ;
            // Default implementations of the common node properties and methods. Nodes
            // will override these with custom logic, if needed.
            // `children` are the properties to recurse into when tree walking. The
            // `children` list *is* the structure of the AST. The `parent` pointer, and
            // the pointer to the `children` are how you can traverse the tree.
            Base.prototype.children = [];
            // `isStatement` has to do with “everything is an expression”. A few things
            // can’t be expressions, such as `break`. Things that `isStatement` returns
            // `true` for are things that can’t be used as expressions. There are some
            // error messages that come from `nodes.coffee` due to statements ending up
            // in expression position.
            Base.prototype.isStatement = NO;
            // Track comments that have been compiled into fragments, to avoid outputting
            // them twice.
            Base.prototype.compiledComments = [];
            // `includeCommentFragments` lets `compileCommentFragments` know whether this node
            // has special awareness of how to handle comments within its output.
            Base.prototype.includeCommentFragments = NO;
            // `jumps` tells you if an expression, or an internal part of an expression
            // has a flow control construct (like `break`, or `continue`, or `return`,
            // or `throw`) that jumps out of the normal flow of control and can’t be
            // used as a value. This is important because things like this make no sense;
            // we have to disallow them.
            Base.prototype.jumps = NO;
            // If `node.shouldCache() is false`, it is safe to use `node` more than once.
            // Otherwise you need to store the value of `node` in a variable and output
            // that variable several times instead. Kind of like this: `5` need not be
            // cached. `returnFive()`, however, could have side effects as a result of
            // evaluating it more than once, and therefore we need to cache it. The
            // parameter is named `shouldCache` rather than `mustCache` because there are
            // also cases where we might not need to cache but where we want to, for
            // example a long expression that may well be idempotent but we want to cache
            // for brevity.
            Base.prototype.shouldCache = YES;
            Base.prototype.isChainable = NO;
            Base.prototype.isAssignable = NO;
            Base.prototype.isNumber = NO;
            Base.prototype.unwrap = THIS;
            Base.prototype.unfoldSoak = NO;
            // Is this node used to assign a certain variable?
            Base.prototype.assigns = NO;
            return Base;
        }).call(this);
        //### HoistTarget
        // A **HoistTargetNode** represents the output location in the node tree for a hoisted node.
        // See Base#hoist.
        exports.HoistTarget = HoistTarget = class HoistTarget extends Base {
            // Expands hoisted fragments in the given array
            static expand(fragments) {
                var fragment, i, j, ref1;
                for (i = j = fragments.length - 1; j >= 0; i = j += -1) {
                    fragment = fragments[i];
                    if (fragment.fragments) {
                        splice.apply(fragments, [i, i - i + 1].concat(ref1 = this.expand(fragment.fragments))), ref1;
                    }
                }
                return fragments;
            }
            constructor(source1) {
                super();
                this.source = source1;
                // Holds presentational options to apply when the source node is compiled.
                this.options = {};
                // Placeholder fragments to be replaced by the source node’s compilation.
                this.targetFragments = {
                    fragments: []
                };
            }
            isStatement(o) {
                return this.source.isStatement(o);
            }
            // Update the target fragments with the result of compiling the source.
            // Calls the given compile function with the node and options (overriden with the target
            // presentational options).
            update(compile, o) {
                return this.targetFragments.fragments = compile.call(this.source, merge(o, this.options));
            }
            // Copies the target indent and level, and returns the placeholder fragments
            compileToFragments(o, level) {
                this.options.indent = o.indent;
                this.options.level = level != null ? level : o.level;
                return [this.targetFragments];
            }
            compileNode(o) {
                return this.compileToFragments(o);
            }
            compileClosure(o) {
                return this.compileToFragments(o);
            }
        };
        //### Block
        // The block is the list of expressions that forms the body of an
        // indented block of code -- the implementation of a function, a clause in an
        // `if`, `switch`, or `try`, and so on...
        exports.Block = Block = (function () {
            class Block extends Base {
                constructor(nodes) {
                    super();
                    this.expressions = compact(flatten(nodes || []));
                }
                // Tack an expression on to the end of this expression list.
                push(node) {
                    this.expressions.push(node);
                    return this;
                }
                // Remove and return the last expression of this expression list.
                pop() {
                    return this.expressions.pop();
                }
                // Add an expression at the beginning of this expression list.
                unshift(node) {
                    this.expressions.unshift(node);
                    return this;
                }
                // If this Block consists of just a single node, unwrap it by pulling
                // it back out.
                unwrap() {
                    if (this.expressions.length === 1) {
                        return this.expressions[0];
                    }
                    else {
                        return this;
                    }
                }
                // Is this an empty block of code?
                isEmpty() {
                    return !this.expressions.length;
                }
                isStatement(o) {
                    var exp, j, len1, ref1;
                    ref1 = this.expressions;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        exp = ref1[j];
                        if (exp.isStatement(o)) {
                            return true;
                        }
                    }
                    return false;
                }
                jumps(o) {
                    var exp, j, jumpNode, len1, ref1;
                    ref1 = this.expressions;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        exp = ref1[j];
                        if (jumpNode = exp.jumps(o)) {
                            return jumpNode;
                        }
                    }
                }
                // A Block node does not return its entire body, rather it
                // ensures that the final expression is returned.
                makeReturn(res) {
                    var expr, len;
                    len = this.expressions.length;
                    while (len--) {
                        expr = this.expressions[len];
                        this.expressions[len] = expr.makeReturn(res);
                        if (expr instanceof Return && !expr.expression) {
                            this.expressions.splice(len, 1);
                        }
                        break;
                    }
                    return this;
                }
                // A **Block** is the only node that can serve as the root.
                compileToFragments(o = {}, level) {
                    if (o.scope) {
                        return super.compileToFragments(o, level);
                    }
                    else {
                        return this.compileRoot(o);
                    }
                }
                // Compile all expressions within the **Block** body. If we need to return
                // the result, and it’s an expression, simply return it. If it’s a statement,
                // ask the statement to do so.
                compileNode(o) {
                    var answer, compiledNodes, fragments, index, j, lastFragment, len1, node, ref1, top;
                    this.tab = o.indent;
                    top = o.level === LEVEL_TOP;
                    compiledNodes = [];
                    ref1 = this.expressions;
                    for (index = j = 0, len1 = ref1.length; j < len1; index = ++j) {
                        node = ref1[index];
                        if (node.hoisted) {
                            // This is a hoisted expression.
                            // We want to compile this and ignore the result.
                            node.compileToFragments(o);
                            continue;
                        }
                        node = node.unfoldSoak(o) || node;
                        if (node instanceof Block) {
                            // This is a nested block. We don’t do anything special here like
                            // enclose it in a new scope; we just compile the statements in this
                            // block along with our own.
                            compiledNodes.push(node.compileNode(o));
                        }
                        else if (top) {
                            node.front = true;
                            fragments = node.compileToFragments(o);
                            if (!node.isStatement(o)) {
                                fragments = indentInitial(fragments, this);
                                [lastFragment] = slice1.call(fragments, -1);
                                if (!(lastFragment.code === '' || lastFragment.isComment)) {
                                    fragments.push(this.makeCode(';'));
                                }
                            }
                            compiledNodes.push(fragments);
                        }
                        else {
                            compiledNodes.push(node.compileToFragments(o, LEVEL_LIST));
                        }
                    }
                    if (top) {
                        if (this.spaced) {
                            return [].concat(this.joinFragmentArrays(compiledNodes, '\n\n'), this.makeCode('\n'));
                        }
                        else {
                            return this.joinFragmentArrays(compiledNodes, '\n');
                        }
                    }
                    if (compiledNodes.length) {
                        answer = this.joinFragmentArrays(compiledNodes, ', ');
                    }
                    else {
                        answer = [this.makeCode('void 0')];
                    }
                    if (compiledNodes.length > 1 && o.level >= LEVEL_LIST) {
                        return this.wrapInParentheses(answer);
                    }
                    else {
                        return answer;
                    }
                }
                // If we happen to be the top-level **Block**, wrap everything in a safety
                // closure, unless requested not to. It would be better not to generate them
                // in the first place, but for now, clean up obvious double-parentheses.
                compileRoot(o) {
                    var fragments, j, len1, name, ref1, ref2;
                    o.indent = o.bare ? '' : TAB;
                    o.level = LEVEL_TOP;
                    this.spaced = true;
                    o.scope = new Scope(null, this, null, (ref1 = o.referencedVars) != null ? ref1 : []);
                    ref2 = o.locals || [];
                    for (j = 0, len1 = ref2.length; j < len1; j++) {
                        name = ref2[j];
                        // Mark given local variables in the root scope as parameters so they don’t
                        // end up being declared on this block.
                        o.scope.parameter(name);
                    }
                    fragments = this.compileWithDeclarations(o);
                    HoistTarget.expand(fragments);
                    fragments = this.compileComments(fragments);
                    if (o.bare) {
                        return fragments;
                    }
                    return [].concat(this.makeCode("(function() {\n"), fragments, this.makeCode("\n}).call(this);\n"));
                }
                // Compile the expressions body for the contents of a function, with
                // declarations of all inner variables pushed up to the top.
                compileWithDeclarations(o) {
                    var assigns, declaredVariable, declaredVariables, declaredVariablesIndex, declars, exp, fragments, i, j, k, len1, len2, post, ref1, rest, scope, spaced;
                    fragments = [];
                    post = [];
                    ref1 = this.expressions;
                    for (i = j = 0, len1 = ref1.length; j < len1; i = ++j) {
                        exp = ref1[i];
                        exp = exp.unwrap();
                        if (!(exp instanceof Literal)) {
                            break;
                        }
                    }
                    o = merge(o, {
                        level: LEVEL_TOP
                    });
                    if (i) {
                        rest = this.expressions.splice(i, 9e9);
                        [spaced, this.spaced] = [this.spaced, false];
                        [fragments, this.spaced] = [this.compileNode(o), spaced];
                        this.expressions = rest;
                    }
                    post = this.compileNode(o);
                    ({ scope } = o);
                    if (scope.expressions === this) {
                        declars = o.scope.hasDeclarations();
                        assigns = scope.hasAssignments;
                        if (declars || assigns) {
                            if (i) {
                                fragments.push(this.makeCode('\n'));
                            }
                            fragments.push(this.makeCode(`${this.tab}var `));
                            if (declars) {
                                declaredVariables = scope.declaredVariables();
                                for (declaredVariablesIndex = k = 0, len2 = declaredVariables.length; k < len2; declaredVariablesIndex = ++k) {
                                    declaredVariable = declaredVariables[declaredVariablesIndex];
                                    fragments.push(this.makeCode(declaredVariable));
                                    if (Object.prototype.hasOwnProperty.call(o.scope.comments, declaredVariable)) {
                                        fragments.push(...o.scope.comments[declaredVariable]);
                                    }
                                    if (declaredVariablesIndex !== declaredVariables.length - 1) {
                                        fragments.push(this.makeCode(', '));
                                    }
                                }
                            }
                            if (assigns) {
                                if (declars) {
                                    fragments.push(this.makeCode(`,\n${this.tab + TAB}`));
                                }
                                fragments.push(this.makeCode(scope.assignedVariables().join(`,\n${this.tab + TAB}`)));
                            }
                            fragments.push(this.makeCode(`;\n${(this.spaced ? '\n' : '')}`));
                        }
                        else if (fragments.length && post.length) {
                            fragments.push(this.makeCode("\n"));
                        }
                    }
                    return fragments.concat(post);
                }
                compileComments(fragments) {
                    var code, commentFragment, fragment, fragmentIndent, fragmentIndex, indent, j, k, l, len1, len2, len3, newLineIndex, onNextLine, p, pastFragment, pastFragmentIndex, q, ref1, ref2, ref3, ref4, trail, upcomingFragment, upcomingFragmentIndex;
                    for (fragmentIndex = j = 0, len1 = fragments.length; j < len1; fragmentIndex = ++j) {
                        fragment = fragments[fragmentIndex];
                        // Insert comments into the output at the next or previous newline.
                        // If there are no newlines at which to place comments, create them.
                        if (fragment.precedingComments) {
                            // Determine the indentation level of the fragment that we are about
                            // to insert comments before, and use that indentation level for our
                            // inserted comments. At this point, the fragments’ `code` property
                            // is the generated output JavaScript, and CoffeeScript always
                            // generates output indented by two spaces; so all we need to do is
                            // search for a `code` property that begins with at least two spaces.
                            fragmentIndent = '';
                            ref1 = fragments.slice(0, (fragmentIndex + 1));
                            for (k = ref1.length - 1; k >= 0; k += -1) {
                                pastFragment = ref1[k];
                                indent = /^ {2,}/m.exec(pastFragment.code);
                                if (indent) {
                                    fragmentIndent = indent[0];
                                    break;
                                }
                                else if (indexOf.call(pastFragment.code, '\n') >= 0) {
                                    break;
                                }
                            }
                            code = `\n${fragmentIndent}` + ((function () {
                                var l, len2, ref2, results;
                                ref2 = fragment.precedingComments;
                                results = [];
                                for (l = 0, len2 = ref2.length; l < len2; l++) {
                                    commentFragment = ref2[l];
                                    if (commentFragment.isHereComment && commentFragment.multiline) {
                                        results.push(multident(commentFragment.code, fragmentIndent, false));
                                    }
                                    else {
                                        results.push(commentFragment.code);
                                    }
                                }
                                return results;
                            })()).join(`\n${fragmentIndent}`).replace(/^(\s*)$/gm, '');
                            ref2 = fragments.slice(0, (fragmentIndex + 1));
                            for (pastFragmentIndex = l = ref2.length - 1; l >= 0; pastFragmentIndex = l += -1) {
                                pastFragment = ref2[pastFragmentIndex];
                                newLineIndex = pastFragment.code.lastIndexOf('\n');
                                if (newLineIndex === -1) {
                                    // Keep searching previous fragments until we can’t go back any
                                    // further, either because there are no fragments left or we’ve
                                    // discovered that we’re in a code block that is interpolated
                                    // inside a string.
                                    if (pastFragmentIndex === 0) {
                                        pastFragment.code = '\n' + pastFragment.code;
                                        newLineIndex = 0;
                                    }
                                    else if (pastFragment.isStringWithInterpolations && pastFragment.code === '{') {
                                        code = code.slice(1) + '\n'; // Move newline to end.
                                        newLineIndex = 1;
                                    }
                                    else {
                                        continue;
                                    }
                                }
                                delete fragment.precedingComments;
                                pastFragment.code = pastFragment.code.slice(0, newLineIndex) + code + pastFragment.code.slice(newLineIndex);
                                break;
                            }
                        }
                        // Yes, this is awfully similar to the previous `if` block, but if you
                        // look closely you’ll find lots of tiny differences that make this
                        // confusing if it were abstracted into a function that both blocks share.
                        if (fragment.followingComments) {
                            // Does the first trailing comment follow at the end of a line of code,
                            // like `; // Comment`, or does it start a new line after a line of code?
                            trail = fragment.followingComments[0].trail;
                            fragmentIndent = '';
                            // Find the indent of the next line of code, if we have any non-trailing
                            // comments to output. We need to first find the next newline, as these
                            // comments will be output after that; and then the indent of the line
                            // that follows the next newline.
                            if (!(trail && fragment.followingComments.length === 1)) {
                                onNextLine = false;
                                ref3 = fragments.slice(fragmentIndex);
                                for (p = 0, len2 = ref3.length; p < len2; p++) {
                                    upcomingFragment = ref3[p];
                                    if (!onNextLine) {
                                        if (indexOf.call(upcomingFragment.code, '\n') >= 0) {
                                            onNextLine = true;
                                        }
                                        else {
                                            continue;
                                        }
                                    }
                                    else {
                                        indent = /^ {2,}/m.exec(upcomingFragment.code);
                                        if (indent) {
                                            fragmentIndent = indent[0];
                                            break;
                                        }
                                        else if (indexOf.call(upcomingFragment.code, '\n') >= 0) {
                                            break;
                                        }
                                    }
                                }
                            }
                            // Is this comment following the indent inserted by bare mode?
                            // If so, there’s no need to indent this further.
                            code = fragmentIndex === 1 && /^\s+$/.test(fragments[0].code) ? '' : trail ? ' ' : `\n${fragmentIndent}`;
                            // Assemble properly indented comments.
                            code += ((function () {
                                var len3, q, ref4, results;
                                ref4 = fragment.followingComments;
                                results = [];
                                for (q = 0, len3 = ref4.length; q < len3; q++) {
                                    commentFragment = ref4[q];
                                    if (commentFragment.isHereComment && commentFragment.multiline) {
                                        results.push(multident(commentFragment.code, fragmentIndent, false));
                                    }
                                    else {
                                        results.push(commentFragment.code);
                                    }
                                }
                                return results;
                            })()).join(`\n${fragmentIndent}`).replace(/^(\s*)$/gm, '');
                            ref4 = fragments.slice(fragmentIndex);
                            for (upcomingFragmentIndex = q = 0, len3 = ref4.length; q < len3; upcomingFragmentIndex = ++q) {
                                upcomingFragment = ref4[upcomingFragmentIndex];
                                newLineIndex = upcomingFragment.code.indexOf('\n');
                                if (newLineIndex === -1) {
                                    // Keep searching upcoming fragments until we can’t go any
                                    // further, either because there are no fragments left or we’ve
                                    // discovered that we’re in a code block that is interpolated
                                    // inside a string.
                                    if (upcomingFragmentIndex === fragments.length - 1) {
                                        upcomingFragment.code = upcomingFragment.code + '\n';
                                        newLineIndex = upcomingFragment.code.length;
                                    }
                                    else if (upcomingFragment.isStringWithInterpolations && upcomingFragment.code === '}') {
                                        code = `${code}\n`;
                                        newLineIndex = 0;
                                    }
                                    else {
                                        continue;
                                    }
                                }
                                delete fragment.followingComments;
                                if (upcomingFragment.code === '\n') {
                                    // Avoid inserting extra blank lines.
                                    code = code.replace(/^\n/, '');
                                }
                                upcomingFragment.code = upcomingFragment.code.slice(0, newLineIndex) + code + upcomingFragment.code.slice(newLineIndex);
                                break;
                            }
                        }
                    }
                    return fragments;
                }
                // Wrap up the given nodes as a **Block**, unless it already happens
                // to be one.
                static wrap(nodes) {
                    if (nodes.length === 1 && nodes[0] instanceof Block) {
                        return nodes[0];
                    }
                    return new Block(nodes);
                }
            }
            ;
            Block.prototype.children = ['expressions'];
            return Block;
        }).call(this);
        //### Literal
        // `Literal` is a base class for static values that can be passed through
        // directly into JavaScript without translation, such as: strings, numbers,
        // `true`, `false`, `null`...
        exports.Literal = Literal = (function () {
            class Literal extends Base {
                constructor(value1) {
                    super();
                    this.value = value1;
                }
                assigns(name) {
                    return name === this.value;
                }
                compileNode(o) {
                    return [this.makeCode(this.value)];
                }
                toString() {
                    // This is only intended for debugging.
                    return ` ${(this.isStatement() ? super.toString() : this.constructor.name)}: ${this.value}`;
                }
            }
            ;
            Literal.prototype.shouldCache = NO;
            return Literal;
        }).call(this);
        exports.NumberLiteral = NumberLiteral = class NumberLiteral extends Literal {
        };
        exports.InfinityLiteral = InfinityLiteral = class InfinityLiteral extends NumberLiteral {
            compileNode() {
                return [this.makeCode('2e308')];
            }
        };
        exports.NaNLiteral = NaNLiteral = class NaNLiteral extends NumberLiteral {
            constructor() {
                super('NaN');
            }
            compileNode(o) {
                var code;
                code = [this.makeCode('0/0')];
                if (o.level >= LEVEL_OP) {
                    return this.wrapInParentheses(code);
                }
                else {
                    return code;
                }
            }
        };
        exports.StringLiteral = StringLiteral = class StringLiteral extends Literal {
            compileNode(o) {
                var res;
                return res = this.csx ? [this.makeCode(this.unquote(true, true))] : super.compileNode();
            }
            unquote(doubleQuote = false, newLine = false) {
                var unquoted;
                unquoted = this.value.slice(1, -1);
                if (doubleQuote) {
                    unquoted = unquoted.replace(/\\"/g, '"');
                }
                if (newLine) {
                    unquoted = unquoted.replace(/\\n/g, '\n');
                }
                return unquoted;
            }
        };
        exports.RegexLiteral = RegexLiteral = class RegexLiteral extends Literal {
        };
        exports.PassthroughLiteral = PassthroughLiteral = class PassthroughLiteral extends Literal {
        };
        exports.IdentifierLiteral = IdentifierLiteral = (function () {
            class IdentifierLiteral extends Literal {
                eachName(iterator) {
                    return iterator(this);
                }
            }
            ;
            IdentifierLiteral.prototype.isAssignable = YES;
            return IdentifierLiteral;
        }).call(this);
        exports.CSXTag = CSXTag = class CSXTag extends IdentifierLiteral {
        };
        exports.PropertyName = PropertyName = (function () {
            class PropertyName extends Literal {
            }
            ;
            PropertyName.prototype.isAssignable = YES;
            return PropertyName;
        }).call(this);
        exports.ComputedPropertyName = ComputedPropertyName = class ComputedPropertyName extends PropertyName {
            compileNode(o) {
                return [this.makeCode('['), ...this.value.compileToFragments(o, LEVEL_LIST), this.makeCode(']')];
            }
        };
        exports.StatementLiteral = StatementLiteral = (function () {
            class StatementLiteral extends Literal {
                jumps(o) {
                    if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) {
                        return this;
                    }
                    if (this.value === 'continue' && !(o != null ? o.loop : void 0)) {
                        return this;
                    }
                }
                compileNode(o) {
                    return [this.makeCode(`${this.tab}${this.value};`)];
                }
            }
            ;
            StatementLiteral.prototype.isStatement = YES;
            StatementLiteral.prototype.makeReturn = THIS;
            return StatementLiteral;
        }).call(this);
        exports.ThisLiteral = ThisLiteral = class ThisLiteral extends Literal {
            constructor() {
                super('this');
            }
            compileNode(o) {
                var code, ref1;
                code = ((ref1 = o.scope.method) != null ? ref1.bound : void 0) ? o.scope.method.context : this.value;
                return [this.makeCode(code)];
            }
        };
        exports.UndefinedLiteral = UndefinedLiteral = class UndefinedLiteral extends Literal {
            constructor() {
                super('undefined');
            }
            compileNode(o) {
                return [this.makeCode(o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0')];
            }
        };
        exports.NullLiteral = NullLiteral = class NullLiteral extends Literal {
            constructor() {
                super('null');
            }
        };
        exports.BooleanLiteral = BooleanLiteral = class BooleanLiteral extends Literal {
        };
        //### Return
        // A `return` is a *pureStatement*—wrapping it in a closure wouldn’t make sense.
        exports.Return = Return = (function () {
            class Return extends Base {
                constructor(expression1) {
                    super();
                    this.expression = expression1;
                }
                compileToFragments(o, level) {
                    var expr, ref1;
                    expr = (ref1 = this.expression) != null ? ref1.makeReturn() : void 0;
                    if (expr && !(expr instanceof Return)) {
                        return expr.compileToFragments(o, level);
                    }
                    else {
                        return super.compileToFragments(o, level);
                    }
                }
                compileNode(o) {
                    var answer, fragment, j, len1;
                    answer = [];
                    // TODO: If we call `expression.compile()` here twice, we’ll sometimes
                    // get back different results!
                    if (this.expression) {
                        answer = this.expression.compileToFragments(o, LEVEL_PAREN);
                        unshiftAfterComments(answer, this.makeCode(`${this.tab}return `));
                        // Since the `return` got indented by `@tab`, preceding comments that are
                        // multiline need to be indented.
                        for (j = 0, len1 = answer.length; j < len1; j++) {
                            fragment = answer[j];
                            if (fragment.isHereComment && indexOf.call(fragment.code, '\n') >= 0) {
                                fragment.code = multident(fragment.code, this.tab);
                            }
                            else if (fragment.isLineComment) {
                                fragment.code = `${this.tab}${fragment.code}`;
                            }
                            else {
                                break;
                            }
                        }
                    }
                    else {
                        answer.push(this.makeCode(`${this.tab}return`));
                    }
                    answer.push(this.makeCode(';'));
                    return answer;
                }
            }
            ;
            Return.prototype.children = ['expression'];
            Return.prototype.isStatement = YES;
            Return.prototype.makeReturn = THIS;
            Return.prototype.jumps = THIS;
            return Return;
        }).call(this);
        // `yield return` works exactly like `return`, except that it turns the function
        // into a generator.
        exports.YieldReturn = YieldReturn = class YieldReturn extends Return {
            compileNode(o) {
                if (o.scope.parent == null) {
                    this.error('yield can only occur inside functions');
                }
                return super.compileNode(o);
            }
        };
        exports.AwaitReturn = AwaitReturn = class AwaitReturn extends Return {
            compileNode(o) {
                if (o.scope.parent == null) {
                    this.error('await can only occur inside functions');
                }
                return super.compileNode(o);
            }
        };
        //### Value
        // A value, variable or literal or parenthesized, indexed or dotted into,
        // or vanilla.
        exports.Value = Value = (function () {
            class Value extends Base {
                constructor(base, props, tag, isDefaultValue = false) {
                    var ref1, ref2;
                    super();
                    if (!props && base instanceof Value) {
                        return base;
                    }
                    this.base = base;
                    this.properties = props || [];
                    if (tag) {
                        this[tag] = true;
                    }
                    this.isDefaultValue = isDefaultValue;
                    // If this is a `@foo =` assignment, if there are comments on `@` move them
                    // to be on `foo`.
                    if (((ref1 = this.base) != null ? ref1.comments : void 0) && this.base instanceof ThisLiteral && (((ref2 = this.properties[0]) != null ? ref2.name : void 0) != null)) {
                        moveComments(this.base, this.properties[0].name);
                    }
                }
                // Add a property (or *properties* ) `Access` to the list.
                add(props) {
                    this.properties = this.properties.concat(props);
                    this.forceUpdateLocation = true;
                    return this;
                }
                hasProperties() {
                    return this.properties.length !== 0;
                }
                bareLiteral(type) {
                    return !this.properties.length && this.base instanceof type;
                }
                // Some boolean checks for the benefit of other nodes.
                isArray() {
                    return this.bareLiteral(Arr);
                }
                isRange() {
                    return this.bareLiteral(Range);
                }
                shouldCache() {
                    return this.hasProperties() || this.base.shouldCache();
                }
                isAssignable() {
                    return this.hasProperties() || this.base.isAssignable();
                }
                isNumber() {
                    return this.bareLiteral(NumberLiteral);
                }
                isString() {
                    return this.bareLiteral(StringLiteral);
                }
                isRegex() {
                    return this.bareLiteral(RegexLiteral);
                }
                isUndefined() {
                    return this.bareLiteral(UndefinedLiteral);
                }
                isNull() {
                    return this.bareLiteral(NullLiteral);
                }
                isBoolean() {
                    return this.bareLiteral(BooleanLiteral);
                }
                isAtomic() {
                    var j, len1, node, ref1;
                    ref1 = this.properties.concat(this.base);
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        node = ref1[j];
                        if (node.soak || node instanceof Call) {
                            return false;
                        }
                    }
                    return true;
                }
                isNotCallable() {
                    return this.isNumber() || this.isString() || this.isRegex() || this.isArray() || this.isRange() || this.isSplice() || this.isObject() || this.isUndefined() || this.isNull() || this.isBoolean();
                }
                isStatement(o) {
                    return !this.properties.length && this.base.isStatement(o);
                }
                assigns(name) {
                    return !this.properties.length && this.base.assigns(name);
                }
                jumps(o) {
                    return !this.properties.length && this.base.jumps(o);
                }
                isObject(onlyGenerated) {
                    if (this.properties.length) {
                        return false;
                    }
                    return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated);
                }
                isElision() {
                    if (!(this.base instanceof Arr)) {
                        return false;
                    }
                    return this.base.hasElision();
                }
                isSplice() {
                    var lastProp, ref1;
                    ref1 = this.properties, [lastProp] = slice1.call(ref1, -1);
                    return lastProp instanceof Slice;
                }
                looksStatic(className) {
                    var ref1;
                    return (this.this || this.base instanceof ThisLiteral || this.base.value === className) && this.properties.length === 1 && ((ref1 = this.properties[0].name) != null ? ref1.value : void 0) !== 'prototype';
                }
                // The value can be unwrapped as its inner node, if there are no attached
                // properties.
                unwrap() {
                    if (this.properties.length) {
                        return this;
                    }
                    else {
                        return this.base;
                    }
                }
                // A reference has base part (`this` value) and name part.
                // We cache them separately for compiling complex expressions.
                // `a()[b()] ?= c` -> `(_base = a())[_name = b()] ? _base[_name] = c`
                cacheReference(o) {
                    var base, bref, name, nref, ref1;
                    ref1 = this.properties, [name] = slice1.call(ref1, -1);
                    if (this.properties.length < 2 && !this.base.shouldCache() && !(name != null ? name.shouldCache() : void 0)) {
                        return [this, this]; // `a` `a.b`
                    }
                    base = new Value(this.base, this.properties.slice(0, -1));
                    if (base.shouldCache()) { // `a().b`
                        bref = new IdentifierLiteral(o.scope.freeVariable('base'));
                        base = new Value(new Parens(new Assign(bref, base)));
                    }
                    if (!name) { // `a()`
                        return [base, bref];
                    }
                    if (name.shouldCache()) { // `a[b()]`
                        nref = new IdentifierLiteral(o.scope.freeVariable('name'));
                        name = new Index(new Assign(nref, name.index));
                        nref = new Index(nref);
                    }
                    return [base.add(name), new Value(bref || base.base, [nref || name])];
                }
                // We compile a value to JavaScript by compiling and joining each property.
                // Things get much more interesting if the chain of properties has *soak*
                // operators `?.` interspersed. Then we have to take care not to accidentally
                // evaluate anything twice when building the soak chain.
                compileNode(o) {
                    var fragments, j, len1, prop, props;
                    this.base.front = this.front;
                    props = this.properties;
                    if (props.length && (this.base.cached != null)) {
                        // Cached fragments enable correct order of the compilation,
                        // and reuse of variables in the scope.
                        // Example:
                        // `a(x = 5).b(-> x = 6)` should compile in the same order as
                        // `a(x = 5); b(-> x = 6)`
                        // (see issue #4437, https://github.com/jashkenas/coffeescript/issues/4437)
                        fragments = this.base.cached;
                    }
                    else {
                        fragments = this.base.compileToFragments(o, (props.length ? LEVEL_ACCESS : null));
                    }
                    if (props.length && SIMPLENUM.test(fragmentsToText(fragments))) {
                        fragments.push(this.makeCode('.'));
                    }
                    for (j = 0, len1 = props.length; j < len1; j++) {
                        prop = props[j];
                        fragments.push(...(prop.compileToFragments(o)));
                    }
                    return fragments;
                }
                // Unfold a soak into an `If`: `a?.b` -> `a.b if a?`
                unfoldSoak(o) {
                    return this.unfoldedSoak != null ? this.unfoldedSoak : this.unfoldedSoak = (() => {
                        var fst, i, ifn, j, len1, prop, ref, ref1, snd;
                        ifn = this.base.unfoldSoak(o);
                        if (ifn) {
                            ifn.body.properties.push(...this.properties);
                            return ifn;
                        }
                        ref1 = this.properties;
                        for (i = j = 0, len1 = ref1.length; j < len1; i = ++j) {
                            prop = ref1[i];
                            if (!prop.soak) {
                                continue;
                            }
                            prop.soak = false;
                            fst = new Value(this.base, this.properties.slice(0, i));
                            snd = new Value(this.base, this.properties.slice(i));
                            if (fst.shouldCache()) {
                                ref = new IdentifierLiteral(o.scope.freeVariable('ref'));
                                fst = new Parens(new Assign(ref, fst));
                                snd.base = ref;
                            }
                            return new If(new Existence(fst), snd, {
                                soak: true
                            });
                        }
                        return false;
                    })();
                }
                eachName(iterator) {
                    if (this.hasProperties()) {
                        return iterator(this);
                    }
                    else if (this.base.isAssignable()) {
                        return this.base.eachName(iterator);
                    }
                    else {
                        return this.error('tried to assign to unassignable value');
                    }
                }
            }
            ;
            Value.prototype.children = ['base', 'properties'];
            return Value;
        }).call(this);
        //### HereComment
        // Comment delimited by `###` (becoming `/* */`).
        exports.HereComment = HereComment = class HereComment extends Base {
            constructor({ content: content1, newLine: newLine1, unshift }) {
                super();
                this.content = content1;
                this.newLine = newLine1;
                this.unshift = unshift;
            }
            compileNode(o) {
                var fragment, hasLeadingMarks, j, largestIndent, leadingWhitespace, len1, line, multiline, ref1;
                multiline = indexOf.call(this.content, '\n') >= 0;
                hasLeadingMarks = /\n\s*[#|\*]/.test(this.content);
                if (hasLeadingMarks) {
                    this.content = this.content.replace(/^([ \t]*)#(?=\s)/gm, ' *');
                }
                // Unindent multiline comments. They will be reindented later.
                if (multiline) {
                    largestIndent = '';
                    ref1 = this.content.split('\n');
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        line = ref1[j];
                        leadingWhitespace = /^\s*/.exec(line)[0];
                        if (leadingWhitespace.length > largestIndent.length) {
                            largestIndent = leadingWhitespace;
                        }
                    }
                    this.content = this.content.replace(RegExp(`^(${leadingWhitespace})`, "gm"), '');
                }
                this.content = `/*${this.content}${(hasLeadingMarks ? ' ' : '')}*/`;
                fragment = this.makeCode(this.content);
                fragment.newLine = this.newLine;
                fragment.unshift = this.unshift;
                fragment.multiline = multiline;
                // Don’t rely on `fragment.type`, which can break when the compiler is minified.
                fragment.isComment = fragment.isHereComment = true;
                return fragment;
            }
        };
        //### LineComment
        // Comment running from `#` to the end of a line (becoming `//`).
        exports.LineComment = LineComment = class LineComment extends Base {
            constructor({ content: content1, newLine: newLine1, unshift }) {
                super();
                this.content = content1;
                this.newLine = newLine1;
                this.unshift = unshift;
            }
            compileNode(o) {
                var fragment;
                fragment = this.makeCode(/^\s*$/.test(this.content) ? '' : `//${this.content}`);
                fragment.newLine = this.newLine;
                fragment.unshift = this.unshift;
                fragment.trail = !this.newLine && !this.unshift;
                // Don’t rely on `fragment.type`, which can break when the compiler is minified.
                fragment.isComment = fragment.isLineComment = true;
                return fragment;
            }
        };
        //### Call
        // Node for a function invocation.
        exports.Call = Call = (function () {
            class Call extends Base {
                constructor(variable1, args1 = [], soak1, token1) {
                    var ref1;
                    super();
                    this.variable = variable1;
                    this.args = args1;
                    this.soak = soak1;
                    this.token = token1;
                    this.isNew = false;
                    if (this.variable instanceof Value && this.variable.isNotCallable()) {
                        this.variable.error("literal is not a function");
                    }
                    this.csx = this.variable.base instanceof CSXTag;
                    // `@variable` never gets output as a result of this node getting created as
                    // part of `RegexWithInterpolations`, so for that case move any comments to
                    // the `args` property that gets passed into `RegexWithInterpolations` via
                    // the grammar.
                    if (((ref1 = this.variable.base) != null ? ref1.value : void 0) === 'RegExp' && this.args.length !== 0) {
                        moveComments(this.variable, this.args[0]);
                    }
                }
                // When setting the location, we sometimes need to update the start location to
                // account for a newly-discovered `new` operator to the left of us. This
                // expands the range on the left, but not the right.
                updateLocationDataIfMissing(locationData) {
                    var base, ref1;
                    if (this.locationData && this.needsUpdatedStartLocation) {
                        this.locationData.first_line = locationData.first_line;
                        this.locationData.first_column = locationData.first_column;
                        base = ((ref1 = this.variable) != null ? ref1.base : void 0) || this.variable;
                        if (base.needsUpdatedStartLocation) {
                            this.variable.locationData.first_line = locationData.first_line;
                            this.variable.locationData.first_column = locationData.first_column;
                            base.updateLocationDataIfMissing(locationData);
                        }
                        delete this.needsUpdatedStartLocation;
                    }
                    return super.updateLocationDataIfMissing(locationData);
                }
                // Tag this invocation as creating a new instance.
                newInstance() {
                    var base, ref1;
                    base = ((ref1 = this.variable) != null ? ref1.base : void 0) || this.variable;
                    if (base instanceof Call && !base.isNew) {
                        base.newInstance();
                    }
                    else {
                        this.isNew = true;
                    }
                    this.needsUpdatedStartLocation = true;
                    return this;
                }
                // Soaked chained invocations unfold into if/else ternary structures.
                unfoldSoak(o) {
                    var call, ifn, j, left, len1, list, ref1, rite;
                    if (this.soak) {
                        if (this.variable instanceof Super) {
                            left = new Literal(this.variable.compile(o));
                            rite = new Value(left);
                            if (this.variable.accessor == null) {
                                this.variable.error("Unsupported reference to 'super'");
                            }
                        }
                        else {
                            if (ifn = unfoldSoak(o, this, 'variable')) {
                                return ifn;
                            }
                            [left, rite] = new Value(this.variable).cacheReference(o);
                        }
                        rite = new Call(rite, this.args);
                        rite.isNew = this.isNew;
                        left = new Literal(`typeof ${left.compile(o)} === "function"`);
                        return new If(left, new Value(rite), {
                            soak: true
                        });
                    }
                    call = this;
                    list = [];
                    while (true) {
                        if (call.variable instanceof Call) {
                            list.push(call);
                            call = call.variable;
                            continue;
                        }
                        if (!(call.variable instanceof Value)) {
                            break;
                        }
                        list.push(call);
                        if (!((call = call.variable.base) instanceof Call)) {
                            break;
                        }
                    }
                    ref1 = list.reverse();
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        call = ref1[j];
                        if (ifn) {
                            if (call.variable instanceof Call) {
                                call.variable = ifn;
                            }
                            else {
                                call.variable.base = ifn;
                            }
                        }
                        ifn = unfoldSoak(o, call, 'variable');
                    }
                    return ifn;
                }
                // Compile a vanilla function call.
                compileNode(o) {
                    var arg, argCode, argIndex, cache, compiledArgs, fragments, j, len1, ref1, ref2, ref3, ref4, varAccess;
                    if (this.csx) {
                        return this.compileCSX(o);
                    }
                    if ((ref1 = this.variable) != null) {
                        ref1.front = this.front;
                    }
                    compiledArgs = [];
                    // If variable is `Accessor` fragments are cached and used later
                    // in `Value::compileNode` to ensure correct order of the compilation,
                    // and reuse of variables in the scope.
                    // Example:
                    // `a(x = 5).b(-> x = 6)` should compile in the same order as
                    // `a(x = 5); b(-> x = 6)`
                    // (see issue #4437, https://github.com/jashkenas/coffeescript/issues/4437)
                    varAccess = ((ref2 = this.variable) != null ? (ref3 = ref2.properties) != null ? ref3[0] : void 0 : void 0) instanceof Access;
                    argCode = (function () {
                        var j, len1, ref4, results;
                        ref4 = this.args || [];
                        results = [];
                        for (j = 0, len1 = ref4.length; j < len1; j++) {
                            arg = ref4[j];
                            if (arg instanceof Code) {
                                results.push(arg);
                            }
                        }
                        return results;
                    }).call(this);
                    if (argCode.length > 0 && varAccess && !this.variable.base.cached) {
                        [cache] = this.variable.base.cache(o, LEVEL_ACCESS, function () {
                            return false;
                        });
                        this.variable.base.cached = cache;
                    }
                    ref4 = this.args;
                    for (argIndex = j = 0, len1 = ref4.length; j < len1; argIndex = ++j) {
                        arg = ref4[argIndex];
                        if (argIndex) {
                            compiledArgs.push(this.makeCode(", "));
                        }
                        compiledArgs.push(...(arg.compileToFragments(o, LEVEL_LIST)));
                    }
                    fragments = [];
                    if (this.isNew) {
                        if (this.variable instanceof Super) {
                            this.variable.error("Unsupported reference to 'super'");
                        }
                        fragments.push(this.makeCode('new '));
                    }
                    fragments.push(...this.variable.compileToFragments(o, LEVEL_ACCESS));
                    fragments.push(this.makeCode('('), ...compiledArgs, this.makeCode(')'));
                    return fragments;
                }
                compileCSX(o) {
                    var attr, attrProps, attributes, content, fragments, j, len1, obj, ref1, tag;
                    [attributes, content] = this.args;
                    attributes.base.csx = true;
                    if (content != null) {
                        content.base.csx = true;
                    }
                    fragments = [this.makeCode('<')];
                    fragments.push(...(tag = this.variable.compileToFragments(o, LEVEL_ACCESS)));
                    if (attributes.base instanceof Arr) {
                        ref1 = attributes.base.objects;
                        for (j = 0, len1 = ref1.length; j < len1; j++) {
                            obj = ref1[j];
                            attr = obj.base;
                            attrProps = (attr != null ? attr.properties : void 0) || [];
                            // Catch invalid CSX attributes: <div {a:"b", props} {props} "value" />
                            if (!(attr instanceof Obj || attr instanceof IdentifierLiteral) || (attr instanceof Obj && !attr.generated && (attrProps.length > 1 || !(attrProps[0] instanceof Splat)))) {
                                obj.error("Unexpected token. Allowed CSX attributes are: id=\"val\", src={source}, {props...} or attribute.");
                            }
                            if (obj.base instanceof Obj) {
                                obj.base.csx = true;
                            }
                            fragments.push(this.makeCode(' '));
                            fragments.push(...obj.compileToFragments(o, LEVEL_PAREN));
                        }
                    }
                    if (content) {
                        fragments.push(this.makeCode('>'));
                        fragments.push(...content.compileNode(o, LEVEL_LIST));
                        fragments.push(...[this.makeCode('</'), ...tag, this.makeCode('>')]);
                    }
                    else {
                        fragments.push(this.makeCode(' />'));
                    }
                    return fragments;
                }
            }
            ;
            Call.prototype.children = ['variable', 'args'];
            return Call;
        }).call(this);
        //### Super
        // Takes care of converting `super()` calls into calls against the prototype's
        // function of the same name.
        // When `expressions` are set the call will be compiled in such a way that the
        // expressions are evaluated without altering the return value of the `SuperCall`
        // expression.
        exports.SuperCall = SuperCall = (function () {
            class SuperCall extends Call {
                isStatement(o) {
                    var ref1;
                    return ((ref1 = this.expressions) != null ? ref1.length : void 0) && o.level === LEVEL_TOP;
                }
                compileNode(o) {
                    var ref, ref1, replacement, superCall;
                    if (!((ref1 = this.expressions) != null ? ref1.length : void 0)) {
                        return super.compileNode(o);
                    }
                    superCall = new Literal(fragmentsToText(super.compileNode(o)));
                    replacement = new Block(this.expressions.slice());
                    if (o.level > LEVEL_TOP) {
                        // If we might be in an expression we need to cache and return the result
                        [superCall, ref] = superCall.cache(o, null, YES);
                        replacement.push(ref);
                    }
                    replacement.unshift(superCall);
                    return replacement.compileToFragments(o, o.level === LEVEL_TOP ? o.level : LEVEL_LIST);
                }
            }
            ;
            SuperCall.prototype.children = Call.prototype.children.concat(['expressions']);
            return SuperCall;
        }).call(this);
        exports.Super = Super = (function () {
            class Super extends Base {
                constructor(accessor) {
                    super();
                    this.accessor = accessor;
                }
                compileNode(o) {
                    var fragments, method, name, nref, ref1, ref2, salvagedComments, variable;
                    method = o.scope.namedMethod();
                    if (!(method != null ? method.isMethod : void 0)) {
                        this.error('cannot use super outside of an instance method');
                    }
                    if (!((method.ctor != null) || (this.accessor != null))) {
                        ({ name, variable } = method);
                        if (name.shouldCache() || (name instanceof Index && name.index.isAssignable())) {
                            nref = new IdentifierLiteral(o.scope.parent.freeVariable('name'));
                            name.index = new Assign(nref, name.index);
                        }
                        this.accessor = nref != null ? new Index(nref) : name;
                    }
                    if ((ref1 = this.accessor) != null ? (ref2 = ref1.name) != null ? ref2.comments : void 0 : void 0) {
                        // A `super()` call gets compiled to e.g. `super.method()`, which means
                        // the `method` property name gets compiled for the first time here, and
                        // again when the `method:` property of the class gets compiled. Since
                        // this compilation happens first, comments attached to `method:` would
                        // get incorrectly output near `super.method()`, when we want them to
                        // get output on the second pass when `method:` is output. So set them
                        // aside during this compilation pass, and put them back on the object so
                        // that they’re there for the later compilation.
                        salvagedComments = this.accessor.name.comments;
                        delete this.accessor.name.comments;
                    }
                    fragments = (new Value(new Literal('super'), this.accessor ? [this.accessor] : [])).compileToFragments(o);
                    if (salvagedComments) {
                        attachCommentsToNode(salvagedComments, this.accessor.name);
                    }
                    return fragments;
                }
            }
            ;
            Super.prototype.children = ['accessor'];
            return Super;
        }).call(this);
        //### RegexWithInterpolations
        // Regexes with interpolations are in fact just a variation of a `Call` (a
        // `RegExp()` call to be precise) with a `StringWithInterpolations` inside.
        exports.RegexWithInterpolations = RegexWithInterpolations = class RegexWithInterpolations extends Call {
            constructor(args = []) {
                super(new Value(new IdentifierLiteral('RegExp')), args, false);
            }
        };
        //### TaggedTemplateCall
        exports.TaggedTemplateCall = TaggedTemplateCall = class TaggedTemplateCall extends Call {
            constructor(variable, arg, soak) {
                if (arg instanceof StringLiteral) {
                    arg = new StringWithInterpolations(Block.wrap([new Value(arg)]));
                }
                super(variable, [arg], soak);
            }
            compileNode(o) {
                return this.variable.compileToFragments(o, LEVEL_ACCESS).concat(this.args[0].compileToFragments(o, LEVEL_LIST));
            }
        };
        //### Extends
        // Node to extend an object's prototype with an ancestor object.
        // After `goog.inherits` from the
        // [Closure Library](https://github.com/google/closure-library/blob/master/closure/goog/base.js).
        exports.Extends = Extends = (function () {
            class Extends extends Base {
                constructor(child1, parent1) {
                    super();
                    this.child = child1;
                    this.parent = parent1;
                }
                // Hooks one constructor into another's prototype chain.
                compileToFragments(o) {
                    return new Call(new Value(new Literal(utility('extend', o))), [this.child, this.parent]).compileToFragments(o);
                }
            }
            ;
            Extends.prototype.children = ['child', 'parent'];
            return Extends;
        }).call(this);
        //### Access
        // A `.` access into a property of a value, or the `::` shorthand for
        // an access into the object's prototype.
        exports.Access = Access = (function () {
            class Access extends Base {
                constructor(name1, tag) {
                    super();
                    this.name = name1;
                    this.soak = tag === 'soak';
                }
                compileToFragments(o) {
                    var name, node;
                    name = this.name.compileToFragments(o);
                    node = this.name.unwrap();
                    if (node instanceof PropertyName) {
                        return [this.makeCode('.'), ...name];
                    }
                    else {
                        return [this.makeCode('['), ...name, this.makeCode(']')];
                    }
                }
            }
            ;
            Access.prototype.children = ['name'];
            Access.prototype.shouldCache = NO;
            return Access;
        }).call(this);
        //### Index
        // A `[ ... ]` indexed access into an array or object.
        exports.Index = Index = (function () {
            class Index extends Base {
                constructor(index1) {
                    super();
                    this.index = index1;
                }
                compileToFragments(o) {
                    return [].concat(this.makeCode("["), this.index.compileToFragments(o, LEVEL_PAREN), this.makeCode("]"));
                }
                shouldCache() {
                    return this.index.shouldCache();
                }
            }
            ;
            Index.prototype.children = ['index'];
            return Index;
        }).call(this);
        //### Range
        // A range literal. Ranges can be used to extract portions (slices) of arrays,
        // to specify a range for comprehensions, or as a value, to be expanded into the
        // corresponding array of integers at runtime.
        exports.Range = Range = (function () {
            class Range extends Base {
                constructor(from1, to1, tag) {
                    super();
                    this.from = from1;
                    this.to = to1;
                    this.exclusive = tag === 'exclusive';
                    this.equals = this.exclusive ? '' : '=';
                }
                // Compiles the range's source variables -- where it starts and where it ends.
                // But only if they need to be cached to avoid double evaluation.
                compileVariables(o) {
                    var shouldCache, step;
                    o = merge(o, {
                        top: true
                    });
                    shouldCache = del(o, 'shouldCache');
                    [this.fromC, this.fromVar] = this.cacheToCodeFragments(this.from.cache(o, LEVEL_LIST, shouldCache));
                    [this.toC, this.toVar] = this.cacheToCodeFragments(this.to.cache(o, LEVEL_LIST, shouldCache));
                    if (step = del(o, 'step')) {
                        [this.step, this.stepVar] = this.cacheToCodeFragments(step.cache(o, LEVEL_LIST, shouldCache));
                    }
                    this.fromNum = this.from.isNumber() ? Number(this.fromVar) : null;
                    this.toNum = this.to.isNumber() ? Number(this.toVar) : null;
                    return this.stepNum = (step != null ? step.isNumber() : void 0) ? Number(this.stepVar) : null;
                }
                // When compiled normally, the range returns the contents of the *for loop*
                // needed to iterate over the values in the range. Used by comprehensions.
                compileNode(o) {
                    var cond, condPart, from, gt, idx, idxName, known, lowerBound, lt, namedIndex, ref1, ref2, stepCond, stepNotZero, stepPart, to, upperBound, varPart;
                    if (!this.fromVar) {
                        this.compileVariables(o);
                    }
                    if (!o.index) {
                        return this.compileArray(o);
                    }
                    // Set up endpoints.
                    known = (this.fromNum != null) && (this.toNum != null);
                    idx = del(o, 'index');
                    idxName = del(o, 'name');
                    namedIndex = idxName && idxName !== idx;
                    varPart = known && !namedIndex ? `var ${idx} = ${this.fromC}` : `${idx} = ${this.fromC}`;
                    if (this.toC !== this.toVar) {
                        varPart += `, ${this.toC}`;
                    }
                    if (this.step !== this.stepVar) {
                        varPart += `, ${this.step}`;
                    }
                    [lt, gt] = [`${idx} <${this.equals}`, `${idx} >${this.equals}`];
                    // Generate the condition.
                    [from, to] = [this.fromNum, this.toNum];
                    // Always check if the `step` isn't zero to avoid the infinite loop.
                    stepNotZero = `${(ref1 = this.stepNum) != null ? ref1 : this.stepVar} !== 0`;
                    stepCond = `${(ref2 = this.stepNum) != null ? ref2 : this.stepVar} > 0`;
                    lowerBound = `${lt} ${(known ? to : this.toVar)}`;
                    upperBound = `${gt} ${(known ? to : this.toVar)}`;
                    condPart = this.step != null ? (this.stepNum != null) && this.stepNum !== 0 ? this.stepNum > 0 ? `${lowerBound}` : `${upperBound}` : `${stepNotZero} && (${stepCond} ? ${lowerBound} : ${upperBound})` : known ? `${(from <= to ? lt : gt)} ${to}` : `(${this.fromVar} <= ${this.toVar} ? ${lowerBound} : ${upperBound})`;
                    cond = this.stepVar ? `${this.stepVar} > 0` : `${this.fromVar} <= ${this.toVar}`;
                    // Generate the step.
                    stepPart = this.stepVar ? `${idx} += ${this.stepVar}` : known ? namedIndex ? from <= to ? `++${idx}` : `--${idx}` : from <= to ? `${idx}++` : `${idx}--` : namedIndex ? `${cond} ? ++${idx} : --${idx}` : `${cond} ? ${idx}++ : ${idx}--`;
                    if (namedIndex) {
                        varPart = `${idxName} = ${varPart}`;
                    }
                    if (namedIndex) {
                        stepPart = `${idxName} = ${stepPart}`;
                    }
                    // The final loop body.
                    return [this.makeCode(`${varPart}; ${condPart}; ${stepPart}`)];
                }
                // When used as a value, expand the range into the equivalent array.
                compileArray(o) {
                    var args, body, cond, hasArgs, i, idt, known, post, pre, range, ref1, ref2, result, vars;
                    known = (this.fromNum != null) && (this.toNum != null);
                    if (known && Math.abs(this.fromNum - this.toNum) <= 20) {
                        range = (function () {
                            var results = [];
                            for (var j = ref1 = this.fromNum, ref2 = this.toNum; ref1 <= ref2 ? j <= ref2 : j >= ref2; ref1 <= ref2 ? j++ : j--) {
                                results.push(j);
                            }
                            return results;
                        }).apply(this);
                        if (this.exclusive) {
                            range.pop();
                        }
                        return [this.makeCode(`[${range.join(', ')}]`)];
                    }
                    idt = this.tab + TAB;
                    i = o.scope.freeVariable('i', {
                        single: true,
                        reserve: false
                    });
                    result = o.scope.freeVariable('results', {
                        reserve: false
                    });
                    pre = `\n${idt}var ${result} = [];`;
                    if (known) {
                        o.index = i;
                        body = fragmentsToText(this.compileNode(o));
                    }
                    else {
                        vars = `${i} = ${this.fromC}` + (this.toC !== this.toVar ? `, ${this.toC}` : '');
                        cond = `${this.fromVar} <= ${this.toVar}`;
                        body = `var ${vars}; ${cond} ? ${i} <${this.equals} ${this.toVar} : ${i} >${this.equals} ${this.toVar}; ${cond} ? ${i}++ : ${i}--`;
                    }
                    post = `{ ${result}.push(${i}); }\n${idt}return ${result};\n${o.indent}`;
                    hasArgs = function (node) {
                        return node != null ? node.contains(isLiteralArguments) : void 0;
                    };
                    if (hasArgs(this.from) || hasArgs(this.to)) {
                        args = ', arguments';
                    }
                    return [this.makeCode(`(function() {${pre}\n${idt}for (${body})${post}}).apply(this${args != null ? args : ''})`)];
                }
            }
            ;
            Range.prototype.children = ['from', 'to'];
            return Range;
        }).call(this);
        //### Slice
        // An array slice literal. Unlike JavaScript's `Array#slice`, the second parameter
        // specifies the index of the end of the slice, just as the first parameter
        // is the index of the beginning.
        exports.Slice = Slice = (function () {
            class Slice extends Base {
                constructor(range1) {
                    super();
                    this.range = range1;
                }
                // We have to be careful when trying to slice through the end of the array,
                // `9e9` is used because not all implementations respect `undefined` or `1/0`.
                // `9e9` should be safe because `9e9` > `2**32`, the max array length.
                compileNode(o) {
                    var compiled, compiledText, from, fromCompiled, to, toStr;
                    ({ to, from } = this.range);
                    // Handle an expression in the property access, e.g. `a[!b in c..]`.
                    if (from != null ? from.shouldCache() : void 0) {
                        from = new Value(new Parens(from));
                    }
                    if (to != null ? to.shouldCache() : void 0) {
                        to = new Value(new Parens(to));
                    }
                    fromCompiled = (from != null ? from.compileToFragments(o, LEVEL_PAREN) : void 0) || [this.makeCode('0')];
                    if (to) {
                        compiled = to.compileToFragments(o, LEVEL_PAREN);
                        compiledText = fragmentsToText(compiled);
                        if (!(!this.range.exclusive && +compiledText === -1)) {
                            toStr = ', ' + (this.range.exclusive ? compiledText : to.isNumber() ? `${+compiledText + 1}` : (compiled = to.compileToFragments(o, LEVEL_ACCESS), `+${fragmentsToText(compiled)} + 1 || 9e9`));
                        }
                    }
                    return [this.makeCode(`.slice(${fragmentsToText(fromCompiled)}${toStr || ''})`)];
                }
            }
            ;
            Slice.prototype.children = ['range'];
            return Slice;
        }).call(this);
        //### Obj
        // An object literal, nothing fancy.
        exports.Obj = Obj = (function () {
            class Obj extends Base {
                constructor(props, generated = false, lhs1 = false) {
                    super();
                    this.generated = generated;
                    this.lhs = lhs1;
                    this.objects = this.properties = props || [];
                }
                isAssignable() {
                    var j, len1, message, prop, ref1, ref2;
                    ref1 = this.properties;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        prop = ref1[j];
                        // Check for reserved words.
                        message = isUnassignable(prop.unwrapAll().value);
                        if (message) {
                            prop.error(message);
                        }
                        if (prop instanceof Assign && prop.context === 'object' && !(((ref2 = prop.value) != null ? ref2.base : void 0) instanceof Arr)) {
                            prop = prop.value;
                        }
                        if (!prop.isAssignable()) {
                            return false;
                        }
                    }
                    return true;
                }
                shouldCache() {
                    return !this.isAssignable();
                }
                // Check if object contains splat.
                hasSplat() {
                    var j, len1, prop, ref1;
                    ref1 = this.properties;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        prop = ref1[j];
                        if (prop instanceof Splat) {
                            return true;
                        }
                    }
                    return false;
                }
                // Move rest property to the end of the list.
                // `{a, rest..., b} = obj` -> `{a, b, rest...} = obj`
                // `foo = ({a, rest..., b}) ->` -> `foo = {a, b, rest...}) ->`
                reorderProperties() {
                    var i, prop, props, splatProp, splatProps;
                    props = this.properties;
                    splatProps = (function () {
                        var j, len1, results;
                        results = [];
                        for (i = j = 0, len1 = props.length; j < len1; i = ++j) {
                            prop = props[i];
                            if (prop instanceof Splat) {
                                results.push(i);
                            }
                        }
                        return results;
                    })();
                    if ((splatProps != null ? splatProps.length : void 0) > 1) {
                        props[splatProps[1]].error("multiple spread elements are disallowed");
                    }
                    splatProp = props.splice(splatProps[0], 1);
                    return this.objects = this.properties = [].concat(props, splatProp);
                }
                compileNode(o) {
                    var answer, i, idt, indent, isCompact, j, join, k, key, l, lastNode, len1, len2, len3, len4, node, p, prop, props, ref1, unwrappedVal, value;
                    if (this.hasSplat() && this.lhs) {
                        this.reorderProperties();
                    }
                    props = this.properties;
                    if (this.generated) {
                        for (j = 0, len1 = props.length; j < len1; j++) {
                            node = props[j];
                            if (node instanceof Value) {
                                node.error('cannot have an implicit value in an implicit object');
                            }
                        }
                    }
                    idt = o.indent += TAB;
                    lastNode = this.lastNode(this.properties);
                    if (this.csx) {
                        // CSX attributes <div id="val" attr={aaa} {props...} />
                        return this.compileCSXAttributes(o);
                    }
                    // If this object is the left-hand side of an assignment, all its children
                    // are too.
                    if (this.lhs) {
                        for (k = 0, len2 = props.length; k < len2; k++) {
                            prop = props[k];
                            if (!(prop instanceof Assign)) {
                                continue;
                            }
                            ({ value } = prop);
                            unwrappedVal = value.unwrapAll();
                            if (unwrappedVal instanceof Arr || unwrappedVal instanceof Obj) {
                                unwrappedVal.lhs = true;
                            }
                            else if (unwrappedVal instanceof Assign) {
                                unwrappedVal.nestedLhs = true;
                            }
                        }
                    }
                    isCompact = true;
                    ref1 = this.properties;
                    for (l = 0, len3 = ref1.length; l < len3; l++) {
                        prop = ref1[l];
                        if (prop instanceof Assign && prop.context === 'object') {
                            isCompact = false;
                        }
                    }
                    answer = [];
                    answer.push(this.makeCode(isCompact ? '' : '\n'));
                    for (i = p = 0, len4 = props.length; p < len4; i = ++p) {
                        prop = props[i];
                        join = i === props.length - 1 ? '' : isCompact ? ', ' : prop === lastNode ? '\n' : ',\n';
                        indent = isCompact ? '' : idt;
                        key = prop instanceof Assign && prop.context === 'object' ? prop.variable : prop instanceof Assign ? (!this.lhs ? prop.operatorToken.error(`unexpected ${prop.operatorToken.value}`) : void 0, prop.variable) : prop;
                        if (key instanceof Value && key.hasProperties()) {
                            if (prop.context === 'object' || !key.this) {
                                key.error('invalid object key');
                            }
                            key = key.properties[0].name;
                            prop = new Assign(key, prop, 'object');
                        }
                        if (key === prop) {
                            if (prop.shouldCache()) {
                                [key, value] = prop.base.cache(o);
                                if (key instanceof IdentifierLiteral) {
                                    key = new PropertyName(key.value);
                                }
                                prop = new Assign(key, value, 'object');
                            }
                            else if (key instanceof Value && key.base instanceof ComputedPropertyName) {
                                // `{ [foo()] }` output as `{ [ref = foo()]: ref }`.
                                if (prop.base.value.shouldCache()) {
                                    [key, value] = prop.base.value.cache(o);
                                    if (key instanceof IdentifierLiteral) {
                                        key = new ComputedPropertyName(key.value);
                                    }
                                    prop = new Assign(key, value, 'object');
                                }
                                else {
                                    // `{ [expression] }` output as `{ [expression]: expression }`.
                                    prop = new Assign(key, prop.base.value, 'object');
                                }
                            }
                            else if (!(typeof prop.bareLiteral === "function" ? prop.bareLiteral(IdentifierLiteral) : void 0) && !(prop instanceof Splat)) {
                                prop = new Assign(prop, prop, 'object');
                            }
                        }
                        if (indent) {
                            answer.push(this.makeCode(indent));
                        }
                        answer.push(...prop.compileToFragments(o, LEVEL_TOP));
                        if (join) {
                            answer.push(this.makeCode(join));
                        }
                    }
                    answer.push(this.makeCode(isCompact ? '' : `\n${this.tab}`));
                    answer = this.wrapInBraces(answer);
                    if (this.front) {
                        return this.wrapInParentheses(answer);
                    }
                    else {
                        return answer;
                    }
                }
                assigns(name) {
                    var j, len1, prop, ref1;
                    ref1 = this.properties;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        prop = ref1[j];
                        if (prop.assigns(name)) {
                            return true;
                        }
                    }
                    return false;
                }
                eachName(iterator) {
                    var j, len1, prop, ref1, results;
                    ref1 = this.properties;
                    results = [];
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        prop = ref1[j];
                        if (prop instanceof Assign && prop.context === 'object') {
                            prop = prop.value;
                        }
                        prop = prop.unwrapAll();
                        if (prop.eachName != null) {
                            results.push(prop.eachName(iterator));
                        }
                        else {
                            results.push(void 0);
                        }
                    }
                    return results;
                }
                compileCSXAttributes(o) {
                    var answer, i, j, join, len1, prop, props;
                    props = this.properties;
                    answer = [];
                    for (i = j = 0, len1 = props.length; j < len1; i = ++j) {
                        prop = props[i];
                        prop.csx = true;
                        join = i === props.length - 1 ? '' : ' ';
                        if (prop instanceof Splat) {
                            prop = new Literal(`{${prop.compile(o)}}`);
                        }
                        answer.push(...prop.compileToFragments(o, LEVEL_TOP));
                        answer.push(this.makeCode(join));
                    }
                    if (this.front) {
                        return this.wrapInParentheses(answer);
                    }
                    else {
                        return answer;
                    }
                }
            }
            ;
            Obj.prototype.children = ['properties'];
            return Obj;
        }).call(this);
        //### Arr
        // An array literal.
        exports.Arr = Arr = (function () {
            class Arr extends Base {
                constructor(objs, lhs1 = false) {
                    super();
                    this.lhs = lhs1;
                    this.objects = objs || [];
                }
                hasElision() {
                    var j, len1, obj, ref1;
                    ref1 = this.objects;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        obj = ref1[j];
                        if (obj instanceof Elision) {
                            return true;
                        }
                    }
                    return false;
                }
                isAssignable() {
                    var i, j, len1, obj, ref1;
                    if (!this.objects.length) {
                        return false;
                    }
                    ref1 = this.objects;
                    for (i = j = 0, len1 = ref1.length; j < len1; i = ++j) {
                        obj = ref1[i];
                        if (obj instanceof Splat && i + 1 !== this.objects.length) {
                            return false;
                        }
                        if (!(obj.isAssignable() && (!obj.isAtomic || obj.isAtomic()))) {
                            return false;
                        }
                    }
                    return true;
                }
                shouldCache() {
                    return !this.isAssignable();
                }
                compileNode(o) {
                    var answer, compiledObjs, fragment, fragmentIndex, fragmentIsElision, fragments, includesLineCommentsOnNonFirstElement, index, j, k, l, len1, len2, len3, len4, len5, obj, objIndex, olen, p, passedElision, q, ref1, unwrappedObj;
                    if (!this.objects.length) {
                        return [this.makeCode('[]')];
                    }
                    o.indent += TAB;
                    fragmentIsElision = function (fragment) {
                        return fragmentsToText(fragment).trim() === ',';
                    };
                    // Detect if `Elisions` at the beginning of the array are processed (e.g. [, , , a]).
                    passedElision = false;
                    answer = [];
                    ref1 = this.objects;
                    for (objIndex = j = 0, len1 = ref1.length; j < len1; objIndex = ++j) {
                        obj = ref1[objIndex];
                        unwrappedObj = obj.unwrapAll();
                        // Let `compileCommentFragments` know to intersperse block comments
                        // into the fragments created when compiling this array.
                        if (unwrappedObj.comments && unwrappedObj.comments.filter(function (comment) {
                            return !comment.here;
                        }).length === 0) {
                            unwrappedObj.includeCommentFragments = YES;
                        }
                        // If this array is the left-hand side of an assignment, all its children
                        // are too.
                        if (this.lhs) {
                            if (unwrappedObj instanceof Arr || unwrappedObj instanceof Obj) {
                                unwrappedObj.lhs = true;
                            }
                        }
                    }
                    compiledObjs = (function () {
                        var k, len2, ref2, results;
                        ref2 = this.objects;
                        results = [];
                        for (k = 0, len2 = ref2.length; k < len2; k++) {
                            obj = ref2[k];
                            results.push(obj.compileToFragments(o, LEVEL_LIST));
                        }
                        return results;
                    }).call(this);
                    olen = compiledObjs.length;
                    // If `compiledObjs` includes newlines, we will output this as a multiline
                    // array (i.e. with a newline and indentation after the `[`). If an element
                    // contains line comments, that should also trigger multiline output since
                    // by definition line comments will introduce newlines into our output.
                    // The exception is if only the first element has line comments; in that
                    // case, output as the compact form if we otherwise would have, so that the
                    // first element’s line comments get output before or after the array.
                    includesLineCommentsOnNonFirstElement = false;
                    for (index = k = 0, len2 = compiledObjs.length; k < len2; index = ++k) {
                        fragments = compiledObjs[index];
                        for (l = 0, len3 = fragments.length; l < len3; l++) {
                            fragment = fragments[l];
                            if (fragment.isHereComment) {
                                fragment.code = fragment.code.trim();
                            }
                            else if (index !== 0 && includesLineCommentsOnNonFirstElement === false && hasLineComments(fragment)) {
                                includesLineCommentsOnNonFirstElement = true;
                            }
                        }
                        // Add ', ' if all `Elisions` from the beginning of the array are processed (e.g. [, , , a]) and
                        // element isn't `Elision` or last element is `Elision` (e.g. [a,,b,,])
                        if (index !== 0 && passedElision && (!fragmentIsElision(fragments) || index === olen - 1)) {
                            answer.push(this.makeCode(', '));
                        }
                        passedElision = passedElision || !fragmentIsElision(fragments);
                        answer.push(...fragments);
                    }
                    if (includesLineCommentsOnNonFirstElement || indexOf.call(fragmentsToText(answer), '\n') >= 0) {
                        for (fragmentIndex = p = 0, len4 = answer.length; p < len4; fragmentIndex = ++p) {
                            fragment = answer[fragmentIndex];
                            if (fragment.isHereComment) {
                                fragment.code = `${multident(fragment.code, o.indent, false)}\n${o.indent}`;
                            }
                            else if (fragment.code === ', ' && !(fragment != null ? fragment.isElision : void 0)) {
                                fragment.code = `,\n${o.indent}`;
                            }
                        }
                        answer.unshift(this.makeCode(`[\n${o.indent}`));
                        answer.push(this.makeCode(`\n${this.tab}]`));
                    }
                    else {
                        for (q = 0, len5 = answer.length; q < len5; q++) {
                            fragment = answer[q];
                            if (fragment.isHereComment) {
                                fragment.code = `${fragment.code} `;
                            }
                        }
                        answer.unshift(this.makeCode('['));
                        answer.push(this.makeCode(']'));
                    }
                    return answer;
                }
                assigns(name) {
                    var j, len1, obj, ref1;
                    ref1 = this.objects;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        obj = ref1[j];
                        if (obj.assigns(name)) {
                            return true;
                        }
                    }
                    return false;
                }
                eachName(iterator) {
                    var j, len1, obj, ref1, results;
                    ref1 = this.objects;
                    results = [];
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        obj = ref1[j];
                        obj = obj.unwrapAll();
                        results.push(obj.eachName(iterator));
                    }
                    return results;
                }
            }
            ;
            Arr.prototype.children = ['objects'];
            return Arr;
        }).call(this);
        //### Class
        // The CoffeeScript class definition.
        // Initialize a **Class** with its name, an optional superclass, and a body.
        exports.Class = Class = (function () {
            class Class extends Base {
                constructor(variable1, parent1, body1 = new Block) {
                    super();
                    this.variable = variable1;
                    this.parent = parent1;
                    this.body = body1;
                }
                compileNode(o) {
                    var executableBody, node, parentName;
                    this.name = this.determineName();
                    executableBody = this.walkBody();
                    if (this.parent instanceof Value && !this.parent.hasProperties()) {
                        // Special handling to allow `class expr.A extends A` declarations
                        parentName = this.parent.base.value;
                    }
                    this.hasNameClash = (this.name != null) && this.name === parentName;
                    node = this;
                    if (executableBody || this.hasNameClash) {
                        node = new ExecutableClassBody(node, executableBody);
                    }
                    else if ((this.name == null) && o.level === LEVEL_TOP) {
                        // Anonymous classes are only valid in expressions
                        node = new Parens(node);
                    }
                    if (this.boundMethods.length && this.parent) {
                        if (this.variable == null) {
                            this.variable = new IdentifierLiteral(o.scope.freeVariable('_class'));
                        }
                        if (this.variableRef == null) {
                            [this.variable, this.variableRef] = this.variable.cache(o);
                        }
                    }
                    if (this.variable) {
                        node = new Assign(this.variable, node, null, { moduleDeclaration: this.moduleDeclaration });
                    }
                    this.compileNode = this.compileClassDeclaration;
                    try {
                        return node.compileToFragments(o);
                    }
                    finally {
                        delete this.compileNode;
                    }
                }
                compileClassDeclaration(o) {
                    var ref1, ref2, result;
                    if (this.externalCtor || this.boundMethods.length) {
                        if (this.ctor == null) {
                            this.ctor = this.makeDefaultConstructor();
                        }
                    }
                    if ((ref1 = this.ctor) != null) {
                        ref1.noReturn = true;
                    }
                    if (this.boundMethods.length) {
                        this.proxyBoundMethods();
                    }
                    o.indent += TAB;
                    result = [];
                    result.push(this.makeCode("class "));
                    if (this.name) {
                        result.push(this.makeCode(this.name));
                    }
                    if (((ref2 = this.variable) != null ? ref2.comments : void 0) != null) {
                        this.compileCommentFragments(o, this.variable, result);
                    }
                    if (this.name) {
                        result.push(this.makeCode(' '));
                    }
                    if (this.parent) {
                        result.push(this.makeCode('extends '), ...this.parent.compileToFragments(o), this.makeCode(' '));
                    }
                    result.push(this.makeCode('{'));
                    if (!this.body.isEmpty()) {
                        this.body.spaced = true;
                        result.push(this.makeCode('\n'));
                        result.push(...this.body.compileToFragments(o, LEVEL_TOP));
                        result.push(this.makeCode(`\n${this.tab}`));
                    }
                    result.push(this.makeCode('}'));
                    return result;
                }
                // Figure out the appropriate name for this class
                determineName() {
                    var message, name, node, ref1, tail;
                    if (!this.variable) {
                        return null;
                    }
                    ref1 = this.variable.properties, [tail] = slice1.call(ref1, -1);
                    node = tail ? tail instanceof Access && tail.name : this.variable.base;
                    if (!(node instanceof IdentifierLiteral || node instanceof PropertyName)) {
                        return null;
                    }
                    name = node.value;
                    if (!tail) {
                        message = isUnassignable(name);
                        if (message) {
                            this.variable.error(message);
                        }
                    }
                    if (indexOf.call(JS_FORBIDDEN, name) >= 0) {
                        return `_${name}`;
                    }
                    else {
                        return name;
                    }
                }
                walkBody() {
                    var assign, end, executableBody, expression, expressions, exprs, i, initializer, initializerExpression, j, k, len1, len2, method, properties, pushSlice, ref1, start;
                    this.ctor = null;
                    this.boundMethods = [];
                    executableBody = null;
                    initializer = [];
                    ({ expressions } = this.body);
                    i = 0;
                    ref1 = expressions.slice();
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        expression = ref1[j];
                        if (expression instanceof Value && expression.isObject(true)) {
                            ({ properties } = expression.base);
                            exprs = [];
                            end = 0;
                            start = 0;
                            pushSlice = function () {
                                if (end > start) {
                                    return exprs.push(new Value(new Obj(properties.slice(start, end), true)));
                                }
                            };
                            while (assign = properties[end]) {
                                if (initializerExpression = this.addInitializerExpression(assign)) {
                                    pushSlice();
                                    exprs.push(initializerExpression);
                                    initializer.push(initializerExpression);
                                    start = end + 1;
                                }
                                end++;
                            }
                            pushSlice();
                            splice.apply(expressions, [i, i - i + 1].concat(exprs)), exprs;
                            i += exprs.length;
                        }
                        else {
                            if (initializerExpression = this.addInitializerExpression(expression)) {
                                initializer.push(initializerExpression);
                                expressions[i] = initializerExpression;
                            }
                            i += 1;
                        }
                    }
                    for (k = 0, len2 = initializer.length; k < len2; k++) {
                        method = initializer[k];
                        if (method instanceof Code) {
                            if (method.ctor) {
                                if (this.ctor) {
                                    method.error('Cannot define more than one constructor in a class');
                                }
                                this.ctor = method;
                            }
                            else if (method.isStatic && method.bound) {
                                method.context = this.name;
                            }
                            else if (method.bound) {
                                this.boundMethods.push(method);
                            }
                        }
                    }
                    if (initializer.length !== expressions.length) {
                        this.body.expressions = (function () {
                            var l, len3, results;
                            results = [];
                            for (l = 0, len3 = initializer.length; l < len3; l++) {
                                expression = initializer[l];
                                results.push(expression.hoist());
                            }
                            return results;
                        })();
                        return new Block(expressions);
                    }
                }
                // Add an expression to the class initializer
                // This is the key method for determining whether an expression in a class
                // body should appear in the initializer or the executable body. If the given
                // `node` is valid in a class body the method will return a (new, modified,
                // or identical) node for inclusion in the class initializer, otherwise
                // nothing will be returned and the node will appear in the executable body.
                // At time of writing, only methods (instance and static) are valid in ES
                // class initializers. As new ES class features (such as class fields) reach
                // Stage 4, this method will need to be updated to support them. We
                // additionally allow `PassthroughLiteral`s (backticked expressions) in the
                // initializer as an escape hatch for ES features that are not implemented
                // (e.g. getters and setters defined via the `get` and `set` keywords as
                // opposed to the `Object.defineProperty` method).
                addInitializerExpression(node) {
                    if (node.unwrapAll() instanceof PassthroughLiteral) {
                        return node;
                    }
                    else if (this.validInitializerMethod(node)) {
                        return this.addInitializerMethod(node);
                    }
                    else {
                        return null;
                    }
                }
                // Checks if the given node is a valid ES class initializer method.
                validInitializerMethod(node) {
                    if (!(node instanceof Assign && node.value instanceof Code)) {
                        return false;
                    }
                    if (node.context === 'object' && !node.variable.hasProperties()) {
                        return true;
                    }
                    return node.variable.looksStatic(this.name) && (this.name || !node.value.bound);
                }
                // Returns a configured class initializer method
                addInitializerMethod(assign) {
                    var method, methodName, variable;
                    ({
                        variable,
                        value: method
                    } = assign);
                    method.isMethod = true;
                    method.isStatic = variable.looksStatic(this.name);
                    if (method.isStatic) {
                        method.name = variable.properties[0];
                    }
                    else {
                        methodName = variable.base;
                        method.name = new (methodName.shouldCache() ? Index : Access)(methodName);
                        method.name.updateLocationDataIfMissing(methodName.locationData);
                        if (methodName.value === 'constructor') {
                            method.ctor = (this.parent ? 'derived' : 'base');
                        }
                        if (method.bound && method.ctor) {
                            method.error('Cannot define a constructor as a bound (fat arrow) function');
                        }
                    }
                    return method;
                }
                makeDefaultConstructor() {
                    var applyArgs, applyCtor, ctor;
                    ctor = this.addInitializerMethod(new Assign(new Value(new PropertyName('constructor')), new Code));
                    this.body.unshift(ctor);
                    if (this.parent) {
                        ctor.body.push(new SuperCall(new Super, [new Splat(new IdentifierLiteral('arguments'))]));
                    }
                    if (this.externalCtor) {
                        applyCtor = new Value(this.externalCtor, [new Access(new PropertyName('apply'))]);
                        applyArgs = [new ThisLiteral, new IdentifierLiteral('arguments')];
                        ctor.body.push(new Call(applyCtor, applyArgs));
                        ctor.body.makeReturn();
                    }
                    return ctor;
                }
                proxyBoundMethods() {
                    var method, name;
                    this.ctor.thisAssignments = (function () {
                        var j, len1, ref1, results;
                        ref1 = this.boundMethods;
                        results = [];
                        for (j = 0, len1 = ref1.length; j < len1; j++) {
                            method = ref1[j];
                            if (this.parent) {
                                method.classVariable = this.variableRef;
                            }
                            name = new Value(new ThisLiteral, [method.name]);
                            results.push(new Assign(name, new Call(new Value(name, [new Access(new PropertyName('bind'))]), [new ThisLiteral])));
                        }
                        return results;
                    }).call(this);
                    return null;
                }
            }
            ;
            Class.prototype.children = ['variable', 'parent', 'body'];
            return Class;
        }).call(this);
        exports.ExecutableClassBody = ExecutableClassBody = (function () {
            class ExecutableClassBody extends Base {
                constructor(_class, body1 = new Block) {
                    super();
                    this.class = _class;
                    this.body = body1;
                }
                compileNode(o) {
                    var args, argumentsNode, directives, externalCtor, ident, jumpNode, klass, params, parent, ref1, wrapper;
                    if (jumpNode = this.body.jumps()) {
                        jumpNode.error('Class bodies cannot contain pure statements');
                    }
                    if (argumentsNode = this.body.contains(isLiteralArguments)) {
                        argumentsNode.error("Class bodies shouldn't reference arguments");
                    }
                    params = [];
                    args = [new ThisLiteral];
                    wrapper = new Code(params, this.body);
                    klass = new Parens(new Call(new Value(wrapper, [new Access(new PropertyName('call'))]), args));
                    this.body.spaced = true;
                    o.classScope = wrapper.makeScope(o.scope);
                    this.name = (ref1 = this.class.name) != null ? ref1 : o.classScope.freeVariable(this.defaultClassVariableName);
                    ident = new IdentifierLiteral(this.name);
                    directives = this.walkBody();
                    this.setContext();
                    if (this.class.hasNameClash) {
                        parent = new IdentifierLiteral(o.classScope.freeVariable('superClass'));
                        wrapper.params.push(new Param(parent));
                        args.push(this.class.parent);
                        this.class.parent = parent;
                    }
                    if (this.externalCtor) {
                        externalCtor = new IdentifierLiteral(o.classScope.freeVariable('ctor', {
                            reserve: false
                        }));
                        this.class.externalCtor = externalCtor;
                        this.externalCtor.variable.base = externalCtor;
                    }
                    if (this.name !== this.class.name) {
                        this.body.expressions.unshift(new Assign(new IdentifierLiteral(this.name), this.class));
                    }
                    else {
                        this.body.expressions.unshift(this.class);
                    }
                    this.body.expressions.unshift(...directives);
                    this.body.push(ident);
                    return klass.compileToFragments(o);
                }
                // Traverse the class's children and:
                // - Hoist valid ES properties into `@properties`
                // - Hoist static assignments into `@properties`
                // - Convert invalid ES properties into class or prototype assignments
                walkBody() {
                    var directives, expr, index;
                    directives = [];
                    index = 0;
                    while (expr = this.body.expressions[index]) {
                        if (!(expr instanceof Value && expr.isString())) {
                            break;
                        }
                        if (expr.hoisted) {
                            index++;
                        }
                        else {
                            directives.push(...this.body.expressions.splice(index, 1));
                        }
                    }
                    this.traverseChildren(false, (child) => {
                        var cont, i, j, len1, node, ref1;
                        if (child instanceof Class || child instanceof HoistTarget) {
                            return false;
                        }
                        cont = true;
                        if (child instanceof Block) {
                            ref1 = child.expressions;
                            for (i = j = 0, len1 = ref1.length; j < len1; i = ++j) {
                                node = ref1[i];
                                if (node instanceof Value && node.isObject(true)) {
                                    cont = false;
                                    child.expressions[i] = this.addProperties(node.base.properties);
                                }
                                else if (node instanceof Assign && node.variable.looksStatic(this.name)) {
                                    node.value.isStatic = true;
                                }
                            }
                            child.expressions = flatten(child.expressions);
                        }
                        return cont;
                    });
                    return directives;
                }
                setContext() {
                    return this.body.traverseChildren(false, (node) => {
                        if (node instanceof ThisLiteral) {
                            return node.value = this.name;
                        }
                        else if (node instanceof Code && node.bound && node.isStatic) {
                            return node.context = this.name;
                        }
                    });
                }
                // Make class/prototype assignments for invalid ES properties
                addProperties(assigns) {
                    var assign, base, name, prototype, result, value, variable;
                    result = (function () {
                        var j, len1, results;
                        results = [];
                        for (j = 0, len1 = assigns.length; j < len1; j++) {
                            assign = assigns[j];
                            variable = assign.variable;
                            base = variable != null ? variable.base : void 0;
                            value = assign.value;
                            delete assign.context;
                            if (base.value === 'constructor') {
                                if (value instanceof Code) {
                                    base.error('constructors must be defined at the top level of a class body');
                                }
                                // The class scope is not available yet, so return the assignment to update later
                                assign = this.externalCtor = new Assign(new Value, value);
                            }
                            else if (!assign.variable.this) {
                                name = new (base.shouldCache() ? Index : Access)(base);
                                prototype = new Access(new PropertyName('prototype'));
                                variable = new Value(new ThisLiteral(), [prototype, name]);
                                assign.variable = variable;
                            }
                            else if (assign.value instanceof Code) {
                                assign.value.isStatic = true;
                            }
                            results.push(assign);
                        }
                        return results;
                    }).call(this);
                    return compact(result);
                }
            }
            ;
            ExecutableClassBody.prototype.children = ['class', 'body'];
            ExecutableClassBody.prototype.defaultClassVariableName = '_Class';
            return ExecutableClassBody;
        }).call(this);
        //### Import and Export
        exports.ModuleDeclaration = ModuleDeclaration = (function () {
            class ModuleDeclaration extends Base {
                constructor(clause, source1) {
                    super();
                    this.clause = clause;
                    this.source = source1;
                    this.checkSource();
                }
                checkSource() {
                    if ((this.source != null) && this.source instanceof StringWithInterpolations) {
                        return this.source.error('the name of the module to be imported from must be an uninterpolated string');
                    }
                }
                checkScope(o, moduleDeclarationType) {
                    if (o.indent.length !== 0) {
                        return this.error(`${moduleDeclarationType} statements must be at top-level scope`);
                    }
                }
            }
            ;
            ModuleDeclaration.prototype.children = ['clause', 'source'];
            ModuleDeclaration.prototype.isStatement = YES;
            ModuleDeclaration.prototype.jumps = THIS;
            ModuleDeclaration.prototype.makeReturn = THIS;
            return ModuleDeclaration;
        }).call(this);
        exports.ImportDeclaration = ImportDeclaration = class ImportDeclaration extends ModuleDeclaration {
            compileNode(o) {
                var code, ref1;
                this.checkScope(o, 'import');
                o.importedSymbols = [];
                code = [];
                code.push(this.makeCode(`${this.tab}import `));
                if (this.clause != null) {
                    code.push(...this.clause.compileNode(o));
                }
                if (((ref1 = this.source) != null ? ref1.value : void 0) != null) {
                    if (this.clause !== null) {
                        code.push(this.makeCode(' from '));
                    }
                    code.push(this.makeCode(this.source.value));
                }
                code.push(this.makeCode(';'));
                return code;
            }
        };
        exports.ImportClause = ImportClause = (function () {
            class ImportClause extends Base {
                constructor(defaultBinding, namedImports) {
                    super();
                    this.defaultBinding = defaultBinding;
                    this.namedImports = namedImports;
                }
                compileNode(o) {
                    var code;
                    code = [];
                    if (this.defaultBinding != null) {
                        code.push(...this.defaultBinding.compileNode(o));
                        if (this.namedImports != null) {
                            code.push(this.makeCode(', '));
                        }
                    }
                    if (this.namedImports != null) {
                        code.push(...this.namedImports.compileNode(o));
                    }
                    return code;
                }
            }
            ;
            ImportClause.prototype.children = ['defaultBinding', 'namedImports'];
            return ImportClause;
        }).call(this);
        exports.ExportDeclaration = ExportDeclaration = class ExportDeclaration extends ModuleDeclaration {
            compileNode(o) {
                var code, ref1;
                this.checkScope(o, 'export');
                code = [];
                code.push(this.makeCode(`${this.tab}export `));
                if (this instanceof ExportDefaultDeclaration) {
                    code.push(this.makeCode('default '));
                }
                if (!(this instanceof ExportDefaultDeclaration) && (this.clause instanceof Assign || this.clause instanceof Class)) {
                    // Prevent exporting an anonymous class; all exported members must be named
                    if (this.clause instanceof Class && !this.clause.variable) {
                        this.clause.error('anonymous classes cannot be exported');
                    }
                    code.push(this.makeCode('var '));
                    this.clause.moduleDeclaration = 'export';
                }
                if ((this.clause.body != null) && this.clause.body instanceof Block) {
                    code = code.concat(this.clause.compileToFragments(o, LEVEL_TOP));
                }
                else {
                    code = code.concat(this.clause.compileNode(o));
                }
                if (((ref1 = this.source) != null ? ref1.value : void 0) != null) {
                    code.push(this.makeCode(` from ${this.source.value}`));
                }
                code.push(this.makeCode(';'));
                return code;
            }
        };
        exports.ExportNamedDeclaration = ExportNamedDeclaration = class ExportNamedDeclaration extends ExportDeclaration {
        };
        exports.ExportDefaultDeclaration = ExportDefaultDeclaration = class ExportDefaultDeclaration extends ExportDeclaration {
        };
        exports.ExportAllDeclaration = ExportAllDeclaration = class ExportAllDeclaration extends ExportDeclaration {
        };
        exports.ModuleSpecifierList = ModuleSpecifierList = (function () {
            class ModuleSpecifierList extends Base {
                constructor(specifiers) {
                    super();
                    this.specifiers = specifiers;
                }
                compileNode(o) {
                    var code, compiledList, fragments, index, j, len1, specifier;
                    code = [];
                    o.indent += TAB;
                    compiledList = (function () {
                        var j, len1, ref1, results;
                        ref1 = this.specifiers;
                        results = [];
                        for (j = 0, len1 = ref1.length; j < len1; j++) {
                            specifier = ref1[j];
                            results.push(specifier.compileToFragments(o, LEVEL_LIST));
                        }
                        return results;
                    }).call(this);
                    if (this.specifiers.length !== 0) {
                        code.push(this.makeCode(`{\n${o.indent}`));
                        for (index = j = 0, len1 = compiledList.length; j < len1; index = ++j) {
                            fragments = compiledList[index];
                            if (index) {
                                code.push(this.makeCode(`,\n${o.indent}`));
                            }
                            code.push(...fragments);
                        }
                        code.push(this.makeCode("\n}"));
                    }
                    else {
                        code.push(this.makeCode('{}'));
                    }
                    return code;
                }
            }
            ;
            ModuleSpecifierList.prototype.children = ['specifiers'];
            return ModuleSpecifierList;
        }).call(this);
        exports.ImportSpecifierList = ImportSpecifierList = class ImportSpecifierList extends ModuleSpecifierList {
        };
        exports.ExportSpecifierList = ExportSpecifierList = class ExportSpecifierList extends ModuleSpecifierList {
        };
        exports.ModuleSpecifier = ModuleSpecifier = (function () {
            class ModuleSpecifier extends Base {
                constructor(original, alias, moduleDeclarationType1) {
                    var ref1, ref2;
                    super();
                    this.original = original;
                    this.alias = alias;
                    this.moduleDeclarationType = moduleDeclarationType1;
                    if (this.original.comments || ((ref1 = this.alias) != null ? ref1.comments : void 0)) {
                        this.comments = [];
                        if (this.original.comments) {
                            this.comments.push(...this.original.comments);
                        }
                        if ((ref2 = this.alias) != null ? ref2.comments : void 0) {
                            this.comments.push(...this.alias.comments);
                        }
                    }
                    // The name of the variable entering the local scope
                    this.identifier = this.alias != null ? this.alias.value : this.original.value;
                }
                compileNode(o) {
                    var code;
                    o.scope.find(this.identifier, this.moduleDeclarationType);
                    code = [];
                    code.push(this.makeCode(this.original.value));
                    if (this.alias != null) {
                        code.push(this.makeCode(` as ${this.alias.value}`));
                    }
                    return code;
                }
            }
            ;
            ModuleSpecifier.prototype.children = ['original', 'alias'];
            return ModuleSpecifier;
        }).call(this);
        exports.ImportSpecifier = ImportSpecifier = class ImportSpecifier extends ModuleSpecifier {
            constructor(imported, local) {
                super(imported, local, 'import');
            }
            compileNode(o) {
                var ref1;
                // Per the spec, symbols can’t be imported multiple times
                // (e.g. `import { foo, foo } from 'lib'` is invalid)
                if ((ref1 = this.identifier, indexOf.call(o.importedSymbols, ref1) >= 0) || o.scope.check(this.identifier)) {
                    this.error(`'${this.identifier}' has already been declared`);
                }
                else {
                    o.importedSymbols.push(this.identifier);
                }
                return super.compileNode(o);
            }
        };
        exports.ImportDefaultSpecifier = ImportDefaultSpecifier = class ImportDefaultSpecifier extends ImportSpecifier {
        };
        exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier = class ImportNamespaceSpecifier extends ImportSpecifier {
        };
        exports.ExportSpecifier = ExportSpecifier = class ExportSpecifier extends ModuleSpecifier {
            constructor(local, exported) {
                super(local, exported, 'export');
            }
        };
        //### Assign
        // The **Assign** is used to assign a local variable to value, or to set the
        // property of an object -- including within object literals.
        exports.Assign = Assign = (function () {
            class Assign extends Base {
                constructor(variable1, value1, context1, options = {}) {
                    super();
                    this.variable = variable1;
                    this.value = value1;
                    this.context = context1;
                    ({ param: this.param, subpattern: this.subpattern, operatorToken: this.operatorToken, moduleDeclaration: this.moduleDeclaration } = options);
                }
                isStatement(o) {
                    return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && (this.moduleDeclaration || indexOf.call(this.context, "?") >= 0);
                }
                checkAssignability(o, varBase) {
                    if (Object.prototype.hasOwnProperty.call(o.scope.positions, varBase.value) && o.scope.variables[o.scope.positions[varBase.value]].type === 'import') {
                        return varBase.error(`'${varBase.value}' is read-only`);
                    }
                }
                assigns(name) {
                    return this[this.context === 'object' ? 'value' : 'variable'].assigns(name);
                }
                unfoldSoak(o) {
                    return unfoldSoak(o, this, 'variable');
                }
                // Compile an assignment, delegating to `compileDestructuring` or
                // `compileSplice` if appropriate. Keep track of the name of the base object
                // we've been assigned to, for correct internal references. If the variable
                // has not been seen yet within the current scope, declare it.
                compileNode(o) {
                    var answer, compiledName, isValue, name, properties, prototype, ref1, ref2, ref3, ref4, ref5, val, varBase;
                    isValue = this.variable instanceof Value;
                    if (isValue) {
                        // When compiling `@variable`, remember if it is part of a function parameter.
                        this.variable.param = this.param;
                        // If `@variable` is an array or an object, we’re destructuring;
                        // if it’s also `isAssignable()`, the destructuring syntax is supported
                        // in ES and we can output it as is; otherwise we `@compileDestructuring`
                        // and convert this ES-unsupported destructuring into acceptable output.
                        if (this.variable.isArray() || this.variable.isObject()) {
                            // This is the left-hand side of an assignment; let `Arr` and `Obj`
                            // know that, so that those nodes know that they’re assignable as
                            // destructured variables.
                            this.variable.base.lhs = true;
                            if (!this.variable.isAssignable()) {
                                if (this.variable.isObject() && this.variable.base.hasSplat()) {
                                    return this.compileObjectDestruct(o);
                                }
                                else {
                                    return this.compileDestructuring(o);
                                }
                            }
                        }
                        if (this.variable.isSplice()) {
                            return this.compileSplice(o);
                        }
                        if ((ref1 = this.context) === '||=' || ref1 === '&&=' || ref1 === '?=') {
                            return this.compileConditional(o);
                        }
                        if ((ref2 = this.context) === '//=' || ref2 === '%%=') {
                            return this.compileSpecialMath(o);
                        }
                    }
                    if (!this.context || this.context === '**=') {
                        varBase = this.variable.unwrapAll();
                        if (!varBase.isAssignable()) {
                            this.variable.error(`'${this.variable.compile(o)}' can't be assigned`);
                        }
                        varBase.eachName((name) => {
                            var commentFragments, commentsNode, message;
                            if (typeof name.hasProperties === "function" ? name.hasProperties() : void 0) {
                                return;
                            }
                            message = isUnassignable(name.value);
                            if (message) {
                                name.error(message);
                            }
                            // `moduleDeclaration` can be `'import'` or `'export'`.
                            this.checkAssignability(o, name);
                            if (this.moduleDeclaration) {
                                return o.scope.add(name.value, this.moduleDeclaration);
                            }
                            else if (this.param) {
                                return o.scope.add(name.value, this.param === 'alwaysDeclare' ? 'var' : 'param');
                            }
                            else {
                                o.scope.find(name.value);
                                // If this assignment identifier has one or more herecomments
                                // attached, output them as part of the declarations line (unless
                                // other herecomments are already staged there) for compatibility
                                // with Flow typing. Don’t do this if this assignment is for a
                                // class, e.g. `ClassName = class ClassName {`, as Flow requires
                                // the comment to be between the class name and the `{`.
                                if (name.comments && !o.scope.comments[name.value] && !(this.value instanceof Class) && name.comments.every(function (comment) {
                                    return comment.here && !comment.multiline;
                                })) {
                                    commentsNode = new IdentifierLiteral(name.value);
                                    commentsNode.comments = name.comments;
                                    commentFragments = [];
                                    this.compileCommentFragments(o, commentsNode, commentFragments);
                                    return o.scope.comments[name.value] = commentFragments;
                                }
                            }
                        });
                    }
                    if (this.value instanceof Code) {
                        if (this.value.isStatic) {
                            this.value.name = this.variable.properties[0];
                        }
                        else if (((ref3 = this.variable.properties) != null ? ref3.length : void 0) >= 2) {
                            ref4 = this.variable.properties, [...properties] = ref4, [prototype, name] = splice.call(properties, -2);
                            if (((ref5 = prototype.name) != null ? ref5.value : void 0) === 'prototype') {
                                this.value.name = name;
                            }
                        }
                    }
                    if (this.csx) {
                        this.value.base.csxAttribute = true;
                    }
                    val = this.value.compileToFragments(o, LEVEL_LIST);
                    compiledName = this.variable.compileToFragments(o, LEVEL_LIST);
                    if (this.context === 'object') {
                        if (this.variable.shouldCache()) {
                            compiledName.unshift(this.makeCode('['));
                            compiledName.push(this.makeCode(']'));
                        }
                        return compiledName.concat(this.makeCode(this.csx ? '=' : ': '), val);
                    }
                    answer = compiledName.concat(this.makeCode(` ${this.context || '='} `), val);
                    // Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assignment_without_declaration,
                    // if we’re destructuring without declaring, the destructuring assignment must be wrapped in parentheses.
                    // The assignment is wrapped in parentheses if 'o.level' has lower precedence than LEVEL_LIST (3)
                    // (i.e. LEVEL_COND (4), LEVEL_OP (5) or LEVEL_ACCESS (6)), or if we're destructuring object, e.g. {a,b} = obj.
                    if (o.level > LEVEL_LIST || isValue && this.variable.base instanceof Obj && !this.nestedLhs && !(this.param === true)) {
                        return this.wrapInParentheses(answer);
                    }
                    else {
                        return answer;
                    }
                }
                // Object rest property is not assignable: `{{a}...}`
                compileObjectDestruct(o) {
                    var assigns, props, refVal, splat, splatProp;
                    this.variable.base.reorderProperties();
                    ({
                        properties: props
                    } = this.variable.base);
                    [splat] = slice1.call(props, -1);
                    splatProp = splat.name;
                    assigns = [];
                    refVal = new Value(new IdentifierLiteral(o.scope.freeVariable('ref')));
                    props.splice(-1, 1, new Splat(refVal));
                    assigns.push(new Assign(new Value(new Obj(props)), this.value).compileToFragments(o, LEVEL_LIST));
                    assigns.push(new Assign(new Value(splatProp), refVal).compileToFragments(o, LEVEL_LIST));
                    return this.joinFragmentArrays(assigns, ', ');
                }
                // Brief implementation of recursive pattern matching, when assigning array or
                // object literals to a value. Peeks at their properties to assign inner names.
                compileDestructuring(o) {
                    var assignObjects, assigns, code, compSlice, compSplice, complexObjects, expIdx, expans, fragments, hasObjAssigns, i, isExpans, isSplat, leftObjs, loopObjects, obj, objIsUnassignable, objects, olen, processObjects, pushAssign, ref, refExp, restVar, rightObjs, slicer, splatVar, splatVarAssign, splatVarRef, splats, splatsAndExpans, top, value, vvar, vvarText;
                    top = o.level === LEVEL_TOP;
                    ({ value } = this);
                    ({ objects } = this.variable.base);
                    olen = objects.length;
                    // Special-case for `{} = a` and `[] = a` (empty patterns).
                    // Compile to simply `a`.
                    if (olen === 0) {
                        code = value.compileToFragments(o);
                        if (o.level >= LEVEL_OP) {
                            return this.wrapInParentheses(code);
                        }
                        else {
                            return code;
                        }
                    }
                    [obj] = objects;
                    // Disallow `[...] = a` for some reason. (Could be equivalent to `[] = a`?)
                    if (olen === 1 && obj instanceof Expansion) {
                        obj.error('Destructuring assignment has no target');
                    }
                    // Count all `Splats`: [a, b, c..., d, e]
                    splats = (function () {
                        var j, len1, results;
                        results = [];
                        for (i = j = 0, len1 = objects.length; j < len1; i = ++j) {
                            obj = objects[i];
                            if (obj instanceof Splat) {
                                results.push(i);
                            }
                        }
                        return results;
                    })();
                    // Count all `Expansions`: [a, b, ..., c, d]
                    expans = (function () {
                        var j, len1, results;
                        results = [];
                        for (i = j = 0, len1 = objects.length; j < len1; i = ++j) {
                            obj = objects[i];
                            if (obj instanceof Expansion) {
                                results.push(i);
                            }
                        }
                        return results;
                    })();
                    // Combine splats and expansions.
                    splatsAndExpans = [...splats, ...expans];
                    // Show error if there is more than one `Splat`, or `Expansion`.
                    // Examples: [a, b, c..., d, e, f...], [a, b, ..., c, d, ...], [a, b, ..., c, d, e...]
                    if (splatsAndExpans.length > 1) {
                        // Sort 'splatsAndExpans' so we can show error at first disallowed token.
                        objects[splatsAndExpans.sort()[1]].error("multiple splats/expansions are disallowed in an assignment");
                    }
                    isSplat = (splats != null ? splats.length : void 0) > 0;
                    isExpans = (expans != null ? expans.length : void 0) > 0;
                    vvar = value.compileToFragments(o, LEVEL_LIST);
                    vvarText = fragmentsToText(vvar);
                    assigns = [];
                    pushAssign = (variable, val) => {
                        return assigns.push(new Assign(variable, val, null, {
                            param: this.param,
                            subpattern: true
                        }).compileToFragments(o, LEVEL_LIST));
                    };
                    if (isSplat) {
                        splatVar = objects[splats[0]].name.unwrap();
                        if (splatVar instanceof Arr || splatVar instanceof Obj) {
                            splatVarRef = new IdentifierLiteral(o.scope.freeVariable('ref'));
                            objects[splats[0]].name = splatVarRef;
                            splatVarAssign = function () {
                                return pushAssign(new Value(splatVar), splatVarRef);
                            };
                        }
                    }
                    // At this point, there are several things to destructure. So the `fn()` in
                    // `{a, b} = fn()` must be cached, for example. Make vvar into a simple
                    // variable if it isn’t already.
                    if (!(value.unwrap() instanceof IdentifierLiteral) || this.variable.assigns(vvarText)) {
                        ref = o.scope.freeVariable('ref');
                        assigns.push([this.makeCode(ref + ' = '), ...vvar]);
                        vvar = [this.makeCode(ref)];
                        vvarText = ref;
                    }
                    slicer = function (type) {
                        return function (vvar, start, end = false) {
                            var args, slice;
                            if (!(vvar instanceof Value)) {
                                vvar = new IdentifierLiteral(vvar);
                            }
                            args = [vvar, new NumberLiteral(start)];
                            if (end) {
                                args.push(new NumberLiteral(end));
                            }
                            slice = new Value(new IdentifierLiteral(utility(type, o)), [new Access(new PropertyName('call'))]);
                            return new Value(new Call(slice, args));
                        };
                    };
                    // Helper which outputs `[].slice` code.
                    compSlice = slicer("slice");
                    // Helper which outputs `[].splice` code.
                    compSplice = slicer("splice");
                    // Check if `objects` array contains any instance of `Assign`, e.g. {a:1}.
                    hasObjAssigns = function (objs) {
                        var j, len1, results;
                        results = [];
                        for (i = j = 0, len1 = objs.length; j < len1; i = ++j) {
                            obj = objs[i];
                            if (obj instanceof Assign && obj.context === 'object') {
                                results.push(i);
                            }
                        }
                        return results;
                    };
                    // Check if `objects` array contains any unassignable object.
                    objIsUnassignable = function (objs) {
                        var j, len1;
                        for (j = 0, len1 = objs.length; j < len1; j++) {
                            obj = objs[j];
                            if (!obj.isAssignable()) {
                                return true;
                            }
                        }
                        return false;
                    };
                    // `objects` are complex when there is object assign ({a:1}),
                    // unassignable object, or just a single node.
                    complexObjects = function (objs) {
                        return hasObjAssigns(objs).length || objIsUnassignable(objs) || olen === 1;
                    };
                    // "Complex" `objects` are processed in a loop.
                    // Examples: [a, b, {c, r...}, d], [a, ..., {b, r...}, c, d]
                    loopObjects = (objs, vvar, vvarTxt) => {
                        var acc, idx, j, len1, message, results, vval;
                        results = [];
                        for (i = j = 0, len1 = objs.length; j < len1; i = ++j) {
                            obj = objs[i];
                            if (obj instanceof Elision) {
                                // `Elision` can be skipped.
                                continue;
                            }
                            // If `obj` is {a: 1}
                            if (obj instanceof Assign && obj.context === 'object') {
                                ({
                                    variable: {
                                        base: idx
                                    },
                                    value: vvar
                                } = obj);
                                if (vvar instanceof Assign) {
                                    ({
                                        variable: vvar
                                    } = vvar);
                                }
                                idx = vvar.this ? vvar.properties[0].name : new PropertyName(vvar.unwrap().value);
                                acc = idx.unwrap() instanceof PropertyName;
                                vval = new Value(value, [new (acc ? Access : Index)(idx)]);
                            }
                            else {
                                // `obj` is [a...], {a...} or a
                                vvar = (function () {
                                    switch (false) {
                                        case !(obj instanceof Splat):
                                            return new Value(obj.name);
                                        default:
                                            return obj;
                                    }
                                })();
                                vval = (function () {
                                    switch (false) {
                                        case !(obj instanceof Splat):
                                            return compSlice(vvarTxt, i);
                                        default:
                                            return new Value(new Literal(vvarTxt), [new Index(new NumberLiteral(i))]);
                                    }
                                })();
                            }
                            message = isUnassignable(vvar.unwrap().value);
                            if (message) {
                                vvar.error(message);
                            }
                            results.push(pushAssign(vvar, vval));
                        }
                        return results;
                    };
                    // "Simple" `objects` can be split and compiled to arrays, [a, b, c] = arr, [a, b, c...] = arr
                    assignObjects = (objs, vvar, vvarTxt) => {
                        var vval;
                        vvar = new Value(new Arr(objs, true));
                        vval = vvarTxt instanceof Value ? vvarTxt : new Value(new Literal(vvarTxt));
                        return pushAssign(vvar, vval);
                    };
                    processObjects = function (objs, vvar, vvarTxt) {
                        if (complexObjects(objs)) {
                            return loopObjects(objs, vvar, vvarTxt);
                        }
                        else {
                            return assignObjects(objs, vvar, vvarTxt);
                        }
                    };
                    // In case there is `Splat` or `Expansion` in `objects`,
                    // we can split array in two simple subarrays.
                    // `Splat` [a, b, c..., d, e] can be split into  [a, b, c...] and [d, e].
                    // `Expansion` [a, b, ..., c, d] can be split into [a, b] and [c, d].
                    // Examples:
                    // a) `Splat`
                    //   CS: [a, b, c..., d, e] = arr
                    //   JS: [a, b, ...c] = arr, [d, e] = splice.call(c, -2)
                    // b) `Expansion`
                    //   CS: [a, b, ..., d, e] = arr
                    //   JS: [a, b] = arr, [d, e] = slice.call(arr, -2)
                    if (splatsAndExpans.length) {
                        expIdx = splatsAndExpans[0];
                        leftObjs = objects.slice(0, expIdx + (isSplat ? 1 : 0));
                        rightObjs = objects.slice(expIdx + 1);
                        if (leftObjs.length !== 0) {
                            processObjects(leftObjs, vvar, vvarText);
                        }
                        if (rightObjs.length !== 0) {
                            // Slice or splice `objects`.
                            refExp = (function () {
                                switch (false) {
                                    case !isSplat:
                                        return compSplice(new Value(objects[expIdx].name), rightObjs.length * -1);
                                    case !isExpans:
                                        return compSlice(vvarText, rightObjs.length * -1);
                                }
                            })();
                            if (complexObjects(rightObjs)) {
                                restVar = refExp;
                                refExp = o.scope.freeVariable('ref');
                                assigns.push([this.makeCode(refExp + ' = '), ...restVar.compileToFragments(o, LEVEL_LIST)]);
                            }
                            processObjects(rightObjs, vvar, refExp);
                        }
                    }
                    else {
                        // There is no `Splat` or `Expansion` in `objects`.
                        processObjects(objects, vvar, vvarText);
                    }
                    if (typeof splatVarAssign === "function") {
                        splatVarAssign();
                    }
                    if (!(top || this.subpattern)) {
                        assigns.push(vvar);
                    }
                    fragments = this.joinFragmentArrays(assigns, ', ');
                    if (o.level < LEVEL_LIST) {
                        return fragments;
                    }
                    else {
                        return this.wrapInParentheses(fragments);
                    }
                }
                // When compiling a conditional assignment, take care to ensure that the
                // operands are only evaluated once, even though we have to reference them
                // more than once.
                compileConditional(o) {
                    var fragments, left, right;
                    [left, right] = this.variable.cacheReference(o);
                    // Disallow conditional assignment of undefined variables.
                    if (!left.properties.length && left.base instanceof Literal && !(left.base instanceof ThisLiteral) && !o.scope.check(left.base.value)) {
                        this.variable.error(`the variable "${left.base.value}" can't be assigned with ${this.context} because it has not been declared before`);
                    }
                    if (indexOf.call(this.context, "?") >= 0) {
                        o.isExistentialEquals = true;
                        return new If(new Existence(left), right, {
                            type: 'if'
                        }).addElse(new Assign(right, this.value, '=')).compileToFragments(o);
                    }
                    else {
                        fragments = new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compileToFragments(o);
                        if (o.level <= LEVEL_LIST) {
                            return fragments;
                        }
                        else {
                            return this.wrapInParentheses(fragments);
                        }
                    }
                }
                // Convert special math assignment operators like `a //= b` to the equivalent
                // extended form `a = a ** b` and then compiles that.
                compileSpecialMath(o) {
                    var left, right;
                    [left, right] = this.variable.cacheReference(o);
                    return new Assign(left, new Op(this.context.slice(0, -1), right, this.value)).compileToFragments(o);
                }
                // Compile the assignment from an array splice literal, using JavaScript's
                // `Array#splice` method.
                compileSplice(o) {
                    var answer, exclusive, from, fromDecl, fromRef, name, to, unwrappedVar, valDef, valRef;
                    ({
                        range: { from, to, exclusive }
                    } = this.variable.properties.pop());
                    unwrappedVar = this.variable.unwrapAll();
                    if (unwrappedVar.comments) {
                        moveComments(unwrappedVar, this);
                        delete this.variable.comments;
                    }
                    name = this.variable.compile(o);
                    if (from) {
                        [fromDecl, fromRef] = this.cacheToCodeFragments(from.cache(o, LEVEL_OP));
                    }
                    else {
                        fromDecl = fromRef = '0';
                    }
                    if (to) {
                        if ((from != null ? from.isNumber() : void 0) && to.isNumber()) {
                            to = to.compile(o) - fromRef;
                            if (!exclusive) {
                                to += 1;
                            }
                        }
                        else {
                            to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef;
                            if (!exclusive) {
                                to += ' + 1';
                            }
                        }
                    }
                    else {
                        to = "9e9";
                    }
                    [valDef, valRef] = this.value.cache(o, LEVEL_LIST);
                    answer = [].concat(this.makeCode(`${utility('splice', o)}.apply(${name}, [${fromDecl}, ${to}].concat(`), valDef, this.makeCode(")), "), valRef);
                    if (o.level > LEVEL_TOP) {
                        return this.wrapInParentheses(answer);
                    }
                    else {
                        return answer;
                    }
                }
                eachName(iterator) {
                    return this.variable.unwrapAll().eachName(iterator);
                }
            }
            ;
            Assign.prototype.children = ['variable', 'value'];
            Assign.prototype.isAssignable = YES;
            return Assign;
        }).call(this);
        //### FuncGlyph
        exports.FuncGlyph = FuncGlyph = class FuncGlyph extends Base {
            constructor(glyph) {
                super();
                this.glyph = glyph;
            }
        };
        //### Code
        // A function definition. This is the only node that creates a new Scope.
        // When for the purposes of walking the contents of a function body, the Code
        // has no *children* -- they're within the inner scope.
        exports.Code = Code = (function () {
            class Code extends Base {
                constructor(params, body, funcGlyph, paramStart) {
                    var ref1;
                    super();
                    this.funcGlyph = funcGlyph;
                    this.paramStart = paramStart;
                    this.params = params || [];
                    this.body = body || new Block;
                    this.bound = ((ref1 = this.funcGlyph) != null ? ref1.glyph : void 0) === '=>';
                    this.isGenerator = false;
                    this.isAsync = false;
                    this.isMethod = false;
                    this.body.traverseChildren(false, (node) => {
                        if ((node instanceof Op && node.isYield()) || node instanceof YieldReturn) {
                            this.isGenerator = true;
                        }
                        if ((node instanceof Op && node.isAwait()) || node instanceof AwaitReturn) {
                            this.isAsync = true;
                        }
                        if (node instanceof For && node.isAwait()) {
                            return this.isAsync = true;
                        }
                    });
                }
                isStatement() {
                    return this.isMethod;
                }
                makeScope(parentScope) {
                    return new Scope(parentScope, this.body, this);
                }
                // Compilation creates a new scope unless explicitly asked to share with the
                // outer scope. Handles splat parameters in the parameter list by setting
                // such parameters to be the final parameter in the function definition, as
                // required per the ES2015 spec. If the CoffeeScript function definition had
                // parameters after the splat, they are declared via expressions in the
                // function body.
                compileNode(o) {
                    var answer, body, boundMethodCheck, comment, condition, exprs, generatedVariables, haveBodyParam, haveSplatParam, i, ifTrue, j, k, l, len1, len2, len3, m, methodScope, modifiers, name, param, paramNames, paramToAddToScope, params, paramsAfterSplat, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, scopeVariablesCount, signature, splatParamName, thisAssignments, wasEmpty, yieldNode;
                    if (this.ctor) {
                        if (this.isAsync) {
                            this.name.error('Class constructor may not be async');
                        }
                        if (this.isGenerator) {
                            this.name.error('Class constructor may not be a generator');
                        }
                    }
                    if (this.bound) {
                        if ((ref1 = o.scope.method) != null ? ref1.bound : void 0) {
                            this.context = o.scope.method.context;
                        }
                        if (!this.context) {
                            this.context = 'this';
                        }
                    }
                    o.scope = del(o, 'classScope') || this.makeScope(o.scope);
                    o.scope.shared = del(o, 'sharedScope');
                    o.indent += TAB;
                    delete o.bare;
                    delete o.isExistentialEquals;
                    params = [];
                    exprs = [];
                    thisAssignments = (ref2 = (ref3 = this.thisAssignments) != null ? ref3.slice() : void 0) != null ? ref2 : [];
                    paramsAfterSplat = [];
                    haveSplatParam = false;
                    haveBodyParam = false;
                    // Check for duplicate parameters and separate `this` assignments.
                    paramNames = [];
                    this.eachParamName(function (name, node, param, obj) {
                        var replacement, target;
                        if (indexOf.call(paramNames, name) >= 0) {
                            node.error(`multiple parameters named '${name}'`);
                        }
                        paramNames.push(name);
                        if (node.this) {
                            name = node.properties[0].name.value;
                            if (indexOf.call(JS_FORBIDDEN, name) >= 0) {
                                name = `_${name}`;
                            }
                            target = new IdentifierLiteral(o.scope.freeVariable(name, {
                                reserve: false
                            }));
                            // `Param` is object destructuring with a default value: ({@prop = 1}) ->
                            // In a case when the variable name is already reserved, we have to assign
                            // a new variable name to the destructured variable: ({prop:prop1 = 1}) ->
                            replacement = param.name instanceof Obj && obj instanceof Assign && obj.operatorToken.value === '=' ? new Assign(new IdentifierLiteral(name), target, 'object') : target; //, operatorToken: new Literal ':'
                            param.renameParam(node, replacement);
                            return thisAssignments.push(new Assign(node, target));
                        }
                    });
                    ref4 = this.params;
                    // Parse the parameters, adding them to the list of parameters to put in the
                    // function definition; and dealing with splats or expansions, including
                    // adding expressions to the function body to declare all parameter
                    // variables that would have been after the splat/expansion parameter.
                    // If we encounter a parameter that needs to be declared in the function
                    // body for any reason, for example it’s destructured with `this`, also
                    // declare and assign all subsequent parameters in the function body so that
                    // any non-idempotent parameters are evaluated in the correct order.
                    for (i = j = 0, len1 = ref4.length; j < len1; i = ++j) {
                        param = ref4[i];
                        // Was `...` used with this parameter? (Only one such parameter is allowed
                        // per function.) Splat/expansion parameters cannot have default values,
                        // so we need not worry about that.
                        if (param.splat || param instanceof Expansion) {
                            if (haveSplatParam) {
                                param.error('only one splat or expansion parameter is allowed per function definition');
                            }
                            else if (param instanceof Expansion && this.params.length === 1) {
                                param.error('an expansion parameter cannot be the only parameter in a function definition');
                            }
                            haveSplatParam = true;
                            if (param.splat) {
                                if (param.name instanceof Arr || param.name instanceof Obj) {
                                    // Splat arrays are treated oddly by ES; deal with them the legacy
                                    // way in the function body. TODO: Should this be handled in the
                                    // function parameter list, and if so, how?
                                    splatParamName = o.scope.freeVariable('arg');
                                    params.push(ref = new Value(new IdentifierLiteral(splatParamName)));
                                    exprs.push(new Assign(new Value(param.name), ref));
                                }
                                else {
                                    params.push(ref = param.asReference(o));
                                    splatParamName = fragmentsToText(ref.compileNodeWithoutComments(o));
                                }
                                if (param.shouldCache()) {
                                    exprs.push(new Assign(new Value(param.name), ref)); // `param` is an Expansion
                                }
                            }
                            else {
                                splatParamName = o.scope.freeVariable('args');
                                params.push(new Value(new IdentifierLiteral(splatParamName)));
                            }
                            o.scope.parameter(splatParamName);
                        }
                        else {
                            // Parse all other parameters; if a splat paramater has not yet been
                            // encountered, add these other parameters to the list to be output in
                            // the function definition.
                            if (param.shouldCache() || haveBodyParam) {
                                param.assignedInBody = true;
                                haveBodyParam = true;
                                // This parameter cannot be declared or assigned in the parameter
                                // list. So put a reference in the parameter list and add a statement
                                // to the function body assigning it, e.g.
                                // `(arg) => { var a = arg.a; }`, with a default value if it has one.
                                if (param.value != null) {
                                    condition = new Op('===', param, new UndefinedLiteral);
                                    ifTrue = new Assign(new Value(param.name), param.value);
                                    exprs.push(new If(condition, ifTrue));
                                }
                                else {
                                    exprs.push(new Assign(new Value(param.name), param.asReference(o), null, {
                                        param: 'alwaysDeclare'
                                    }));
                                }
                            }
                            // If this parameter comes before the splat or expansion, it will go
                            // in the function definition parameter list.
                            if (!haveSplatParam) {
                                // If this parameter has a default value, and it hasn’t already been
                                // set by the `shouldCache()` block above, define it as a statement in
                                // the function body. This parameter comes after the splat parameter,
                                // so we can’t define its default value in the parameter list.
                                if (param.shouldCache()) {
                                    ref = param.asReference(o);
                                }
                                else {
                                    if ((param.value != null) && !param.assignedInBody) {
                                        ref = new Assign(new Value(param.name), param.value, null, {
                                            param: true
                                        });
                                    }
                                    else {
                                        ref = param;
                                    }
                                }
                                // Add this parameter’s reference(s) to the function scope.
                                if (param.name instanceof Arr || param.name instanceof Obj) {
                                    // This parameter is destructured.
                                    param.name.lhs = true;
                                    if (!param.shouldCache()) {
                                        param.name.eachName(function (prop) {
                                            return o.scope.parameter(prop.value);
                                        });
                                    }
                                }
                                else {
                                    // This compilation of the parameter is only to get its name to add
                                    // to the scope name tracking; since the compilation output here
                                    // isn’t kept for eventual output, don’t include comments in this
                                    // compilation, so that they get output the “real” time this param
                                    // is compiled.
                                    paramToAddToScope = param.value != null ? param : ref;
                                    o.scope.parameter(fragmentsToText(paramToAddToScope.compileToFragmentsWithoutComments(o)));
                                }
                                params.push(ref);
                            }
                            else {
                                paramsAfterSplat.push(param);
                                // If this parameter had a default value, since it’s no longer in the
                                // function parameter list we need to assign its default value
                                // (if necessary) as an expression in the body.
                                if ((param.value != null) && !param.shouldCache()) {
                                    condition = new Op('===', param, new UndefinedLiteral);
                                    ifTrue = new Assign(new Value(param.name), param.value);
                                    exprs.push(new If(condition, ifTrue));
                                }
                                if (((ref5 = param.name) != null ? ref5.value : void 0) != null) {
                                    // Add this parameter to the scope, since it wouldn’t have been added
                                    // yet since it was skipped earlier.
                                    o.scope.add(param.name.value, 'var', true);
                                }
                            }
                        }
                    }
                    // If there were parameters after the splat or expansion parameter, those
                    // parameters need to be assigned in the body of the function.
                    if (paramsAfterSplat.length !== 0) {
                        // Create a destructured assignment, e.g. `[a, b, c] = [args..., b, c]`
                        exprs.unshift(new Assign(new Value(new Arr([
                            new Splat(new IdentifierLiteral(splatParamName)),
                            ...((function () {
                                var k, len2, results;
                                results = [];
                                for (k = 0, len2 = paramsAfterSplat.length; k < len2; k++) {
                                    param = paramsAfterSplat[k];
                                    results.push(param.asReference(o));
                                }
                                return results;
                            })())
                        ])), new Value(new IdentifierLiteral(splatParamName))));
                    }
                    // Add new expressions to the function body
                    wasEmpty = this.body.isEmpty();
                    if (!this.expandCtorSuper(thisAssignments)) {
                        this.body.expressions.unshift(...thisAssignments);
                    }
                    this.body.expressions.unshift(...exprs);
                    if (this.isMethod && this.bound && !this.isStatic && this.classVariable) {
                        boundMethodCheck = new Value(new Literal(utility('boundMethodCheck', o)));
                        this.body.expressions.unshift(new Call(boundMethodCheck, [new Value(new ThisLiteral), this.classVariable]));
                    }
                    if (!(wasEmpty || this.noReturn)) {
                        this.body.makeReturn();
                    }
                    // JavaScript doesn’t allow bound (`=>`) functions to also be generators.
                    // This is usually caught via `Op::compileContinuation`, but double-check:
                    if (this.bound && this.isGenerator) {
                        yieldNode = this.body.contains(function (node) {
                            return node instanceof Op && node.operator === 'yield';
                        });
                        (yieldNode || this).error('yield cannot occur inside bound (fat arrow) functions');
                    }
                    // Assemble the output
                    modifiers = [];
                    if (this.isMethod && this.isStatic) {
                        modifiers.push('static');
                    }
                    if (this.isAsync) {
                        modifiers.push('async');
                    }
                    if (!(this.isMethod || this.bound)) {
                        modifiers.push(`function${(this.isGenerator ? '*' : '')}`);
                    }
                    else if (this.isGenerator) {
                        modifiers.push('*');
                    }
                    signature = [this.makeCode('(')];
                    // Block comments between a function name and `(` get output between
                    // `function` and `(`.
                    if (((ref6 = this.paramStart) != null ? ref6.comments : void 0) != null) {
                        this.compileCommentFragments(o, this.paramStart, signature);
                    }
                    for (i = k = 0, len2 = params.length; k < len2; i = ++k) {
                        param = params[i];
                        if (i !== 0) {
                            signature.push(this.makeCode(', '));
                        }
                        if (haveSplatParam && i === params.length - 1) {
                            signature.push(this.makeCode('...'));
                        }
                        // Compile this parameter, but if any generated variables get created
                        // (e.g. `ref`), shift those into the parent scope since we can’t put a
                        // `var` line inside a function parameter list.
                        scopeVariablesCount = o.scope.variables.length;
                        signature.push(...param.compileToFragments(o));
                        if (scopeVariablesCount !== o.scope.variables.length) {
                            generatedVariables = o.scope.variables.splice(scopeVariablesCount);
                            o.scope.parent.variables.push(...generatedVariables);
                        }
                    }
                    signature.push(this.makeCode(')'));
                    // Block comments between `)` and `->`/`=>` get output between `)` and `{`.
                    if (((ref7 = this.funcGlyph) != null ? ref7.comments : void 0) != null) {
                        ref8 = this.funcGlyph.comments;
                        for (l = 0, len3 = ref8.length; l < len3; l++) {
                            comment = ref8[l];
                            comment.unshift = false;
                        }
                        this.compileCommentFragments(o, this.funcGlyph, signature);
                    }
                    if (!this.body.isEmpty()) {
                        body = this.body.compileWithDeclarations(o);
                    }
                    // We need to compile the body before method names to ensure `super`
                    // references are handled.
                    if (this.isMethod) {
                        [methodScope, o.scope] = [o.scope, o.scope.parent];
                        name = this.name.compileToFragments(o);
                        if (name[0].code === '.') {
                            name.shift();
                        }
                        o.scope = methodScope;
                    }
                    answer = this.joinFragmentArrays((function () {
                        var len4, p, results;
                        results = [];
                        for (p = 0, len4 = modifiers.length; p < len4; p++) {
                            m = modifiers[p];
                            results.push(this.makeCode(m));
                        }
                        return results;
                    }).call(this), ' ');
                    if (modifiers.length && name) {
                        answer.push(this.makeCode(' '));
                    }
                    if (name) {
                        answer.push(...name);
                    }
                    answer.push(...signature);
                    if (this.bound && !this.isMethod) {
                        answer.push(this.makeCode(' =>'));
                    }
                    answer.push(this.makeCode(' {'));
                    if (body != null ? body.length : void 0) {
                        answer.push(this.makeCode('\n'), ...body, this.makeCode(`\n${this.tab}`));
                    }
                    answer.push(this.makeCode('}'));
                    if (this.isMethod) {
                        return indentInitial(answer, this);
                    }
                    if (this.front || (o.level >= LEVEL_ACCESS)) {
                        return this.wrapInParentheses(answer);
                    }
                    else {
                        return answer;
                    }
                }
                eachParamName(iterator) {
                    var j, len1, param, ref1, results;
                    ref1 = this.params;
                    results = [];
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        param = ref1[j];
                        results.push(param.eachName(iterator));
                    }
                    return results;
                }
                // Short-circuit `traverseChildren` method to prevent it from crossing scope
                // boundaries unless `crossScope` is `true`.
                traverseChildren(crossScope, func) {
                    if (crossScope) {
                        return super.traverseChildren(crossScope, func);
                    }
                }
                // Short-circuit `replaceInContext` method to prevent it from crossing context boundaries. Bound
                // functions have the same context.
                replaceInContext(child, replacement) {
                    if (this.bound) {
                        return super.replaceInContext(child, replacement);
                    }
                    else {
                        return false;
                    }
                }
                expandCtorSuper(thisAssignments) {
                    var haveThisParam, param, ref1, seenSuper;
                    if (!this.ctor) {
                        return false;
                    }
                    this.eachSuperCall(Block.wrap(this.params), function (superCall) {
                        return superCall.error("'super' is not allowed in constructor parameter defaults");
                    });
                    seenSuper = this.eachSuperCall(this.body, (superCall) => {
                        if (this.ctor === 'base') {
                            superCall.error("'super' is only allowed in derived class constructors");
                        }
                        return superCall.expressions = thisAssignments;
                    });
                    haveThisParam = thisAssignments.length && thisAssignments.length !== ((ref1 = this.thisAssignments) != null ? ref1.length : void 0);
                    if (this.ctor === 'derived' && !seenSuper && haveThisParam) {
                        param = thisAssignments[0].variable;
                        param.error("Can't use @params in derived class constructors without calling super");
                    }
                    return seenSuper;
                }
                // Find all super calls in the given context node;
                // returns `true` if `iterator` is called.
                eachSuperCall(context, iterator) {
                    var seenSuper;
                    seenSuper = false;
                    context.traverseChildren(true, (child) => {
                        var childArgs;
                        if (child instanceof SuperCall) {
                            // `super` in a constructor (the only `super` without an accessor)
                            // cannot be given an argument with a reference to `this`, as that would
                            // be referencing `this` before calling `super`.
                            if (!child.variable.accessor) {
                                childArgs = child.args.filter(function (arg) {
                                    return !(arg instanceof Class) && (!(arg instanceof Code) || arg.bound);
                                });
                                Block.wrap(childArgs).traverseChildren(true, (node) => {
                                    if (node.this) {
                                        return node.error("Can't call super with @params in derived class constructors");
                                    }
                                });
                            }
                            seenSuper = true;
                            iterator(child);
                        }
                        else if (child instanceof ThisLiteral && this.ctor === 'derived' && !seenSuper) {
                            child.error("Can't reference 'this' before calling super in derived class constructors");
                        }
                        // `super` has the same target in bound (arrow) functions, so check them too
                        return !(child instanceof SuperCall) && (!(child instanceof Code) || child.bound);
                    });
                    return seenSuper;
                }
            }
            ;
            Code.prototype.children = ['params', 'body'];
            Code.prototype.jumps = NO;
            return Code;
        }).call(this);
        //### Param
        // A parameter in a function definition. Beyond a typical JavaScript parameter,
        // these parameters can also attach themselves to the context of the function,
        // as well as be a splat, gathering up a group of parameters into an array.
        exports.Param = Param = (function () {
            class Param extends Base {
                constructor(name1, value1, splat1) {
                    var message, token;
                    super();
                    this.name = name1;
                    this.value = value1;
                    this.splat = splat1;
                    message = isUnassignable(this.name.unwrapAll().value);
                    if (message) {
                        this.name.error(message);
                    }
                    if (this.name instanceof Obj && this.name.generated) {
                        token = this.name.objects[0].operatorToken;
                        token.error(`unexpected ${token.value}`);
                    }
                }
                compileToFragments(o) {
                    return this.name.compileToFragments(o, LEVEL_LIST);
                }
                compileToFragmentsWithoutComments(o) {
                    return this.name.compileToFragmentsWithoutComments(o, LEVEL_LIST);
                }
                asReference(o) {
                    var name, node;
                    if (this.reference) {
                        return this.reference;
                    }
                    node = this.name;
                    if (node.this) {
                        name = node.properties[0].name.value;
                        if (indexOf.call(JS_FORBIDDEN, name) >= 0) {
                            name = `_${name}`;
                        }
                        node = new IdentifierLiteral(o.scope.freeVariable(name));
                    }
                    else if (node.shouldCache()) {
                        node = new IdentifierLiteral(o.scope.freeVariable('arg'));
                    }
                    node = new Value(node);
                    node.updateLocationDataIfMissing(this.locationData);
                    return this.reference = node;
                }
                shouldCache() {
                    return this.name.shouldCache();
                }
                // Iterates the name or names of a `Param`.
                // In a sense, a destructured parameter represents multiple JS parameters. This
                // method allows to iterate them all.
                // The `iterator` function will be called as `iterator(name, node)` where
                // `name` is the name of the parameter and `node` is the AST node corresponding
                // to that name.
                eachName(iterator, name = this.name) {
                    var atParam, j, len1, nObj, node, obj, ref1, ref2;
                    atParam = (obj, originalObj = null) => {
                        return iterator(`@${obj.properties[0].name.value}`, obj, this, originalObj);
                    };
                    if (name instanceof Literal) {
                        // * simple literals `foo`
                        return iterator(name.value, name, this);
                    }
                    if (name instanceof Value) {
                        // * at-params `@foo`
                        return atParam(name);
                    }
                    ref2 = (ref1 = name.objects) != null ? ref1 : [];
                    for (j = 0, len1 = ref2.length; j < len1; j++) {
                        obj = ref2[j];
                        // Save original obj.
                        nObj = obj;
                        // * destructured parameter with default value
                        if (obj instanceof Assign && (obj.context == null)) {
                            obj = obj.variable;
                        }
                        // * assignments within destructured parameters `{foo:bar}`
                        if (obj instanceof Assign) {
                            // ... possibly with a default value
                            if (obj.value instanceof Assign) {
                                obj = obj.value.variable;
                            }
                            else {
                                obj = obj.value;
                            }
                            this.eachName(iterator, obj.unwrap());
                            // * splats within destructured parameters `[xs...]`
                        }
                        else if (obj instanceof Splat) {
                            node = obj.name.unwrap();
                            iterator(node.value, node, this);
                        }
                        else if (obj instanceof Value) {
                            // * destructured parameters within destructured parameters `[{a}]`
                            if (obj.isArray() || obj.isObject()) {
                                this.eachName(iterator, obj.base);
                                // * at-params within destructured parameters `{@foo}`
                            }
                            else if (obj.this) {
                                atParam(obj, nObj);
                            }
                            else {
                                // * simple destructured parameters {foo}
                                iterator(obj.base.value, obj.base, this);
                            }
                        }
                        else if (obj instanceof Elision) {
                            obj;
                        }
                        else if (!(obj instanceof Expansion)) {
                            obj.error(`illegal parameter ${obj.compile()}`);
                        }
                    }
                }
                // Rename a param by replacing the given AST node for a name with a new node.
                // This needs to ensure that the the source for object destructuring does not change.
                renameParam(node, newNode) {
                    var isNode, replacement;
                    isNode = function (candidate) {
                        return candidate === node;
                    };
                    replacement = (node, parent) => {
                        var key;
                        if (parent instanceof Obj) {
                            key = node;
                            if (node.this) {
                                key = node.properties[0].name;
                            }
                            // No need to assign a new variable for the destructured variable if the variable isn't reserved.
                            // Examples:
                            // `({@foo}) ->`  should compile to `({foo}) { this.foo = foo}`
                            // `foo = 1; ({@foo}) ->` should compile to `foo = 1; ({foo:foo1}) { this.foo = foo1 }`
                            if (node.this && key.value === newNode.value) {
                                return new Value(newNode);
                            }
                            else {
                                return new Assign(new Value(key), newNode, 'object');
                            }
                        }
                        else {
                            return newNode;
                        }
                    };
                    return this.replaceInContext(isNode, replacement);
                }
            }
            ;
            Param.prototype.children = ['name', 'value'];
            return Param;
        }).call(this);
        //### Splat
        // A splat, either as a parameter to a function, an argument to a call,
        // or as part of a destructuring assignment.
        exports.Splat = Splat = (function () {
            class Splat extends Base {
                constructor(name) {
                    super();
                    this.name = name.compile ? name : new Literal(name);
                }
                shouldCache() {
                    return false;
                }
                isAssignable() {
                    if (this.name instanceof Obj || this.name instanceof Parens) {
                        return false;
                    }
                    return this.name.isAssignable() && (!this.name.isAtomic || this.name.isAtomic());
                }
                assigns(name) {
                    return this.name.assigns(name);
                }
                compileNode(o) {
                    return [this.makeCode('...'), ...this.name.compileToFragments(o, LEVEL_OP)];
                }
                unwrap() {
                    return this.name;
                }
            }
            ;
            Splat.prototype.children = ['name'];
            return Splat;
        }).call(this);
        //### Expansion
        // Used to skip values inside an array destructuring (pattern matching) or
        // parameter list.
        exports.Expansion = Expansion = (function () {
            class Expansion extends Base {
                compileNode(o) {
                    return this.error('Expansion must be used inside a destructuring assignment or parameter list');
                }
                asReference(o) {
                    return this;
                }
                eachName(iterator) { }
            }
            ;
            Expansion.prototype.shouldCache = NO;
            return Expansion;
        }).call(this);
        //### Elision
        // Array elision element (for example, [,a, , , b, , c, ,]).
        exports.Elision = Elision = (function () {
            class Elision extends Base {
                compileToFragments(o, level) {
                    var fragment;
                    fragment = super.compileToFragments(o, level);
                    fragment.isElision = true;
                    return fragment;
                }
                compileNode(o) {
                    return [this.makeCode(', ')];
                }
                asReference(o) {
                    return this;
                }
                eachName(iterator) { }
            }
            ;
            Elision.prototype.isAssignable = YES;
            Elision.prototype.shouldCache = NO;
            return Elision;
        }).call(this);
        //### While
        // A while loop, the only sort of low-level loop exposed by CoffeeScript. From
        // it, all other loops can be manufactured. Useful in cases where you need more
        // flexibility or more speed than a comprehension can provide.
        exports.While = While = (function () {
            class While extends Base {
                constructor(condition, options) {
                    super();
                    this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition;
                    this.guard = options != null ? options.guard : void 0;
                }
                makeReturn(res) {
                    if (res) {
                        return super.makeReturn(res);
                    }
                    else {
                        this.returns = !this.jumps();
                        return this;
                    }
                }
                addBody(body1) {
                    this.body = body1;
                    return this;
                }
                jumps() {
                    var expressions, j, jumpNode, len1, node;
                    ({ expressions } = this.body);
                    if (!expressions.length) {
                        return false;
                    }
                    for (j = 0, len1 = expressions.length; j < len1; j++) {
                        node = expressions[j];
                        if (jumpNode = node.jumps({
                            loop: true
                        })) {
                            return jumpNode;
                        }
                    }
                    return false;
                }
                // The main difference from a JavaScript *while* is that the CoffeeScript
                // *while* can be used as a part of a larger expression -- while loops may
                // return an array containing the computed result of each iteration.
                compileNode(o) {
                    var answer, body, rvar, set;
                    o.indent += TAB;
                    set = '';
                    ({ body } = this);
                    if (body.isEmpty()) {
                        body = this.makeCode('');
                    }
                    else {
                        if (this.returns) {
                            body.makeReturn(rvar = o.scope.freeVariable('results'));
                            set = `${this.tab}${rvar} = [];\n`;
                        }
                        if (this.guard) {
                            if (body.expressions.length > 1) {
                                body.expressions.unshift(new If((new Parens(this.guard)).invert(), new StatementLiteral("continue")));
                            }
                            else {
                                if (this.guard) {
                                    body = Block.wrap([new If(this.guard, body)]);
                                }
                            }
                        }
                        body = [].concat(this.makeCode("\n"), body.compileToFragments(o, LEVEL_TOP), this.makeCode(`\n${this.tab}`));
                    }
                    answer = [].concat(this.makeCode(set + this.tab + "while ("), this.condition.compileToFragments(o, LEVEL_PAREN), this.makeCode(") {"), body, this.makeCode("}"));
                    if (this.returns) {
                        answer.push(this.makeCode(`\n${this.tab}return ${rvar};`));
                    }
                    return answer;
                }
            }
            ;
            While.prototype.children = ['condition', 'guard', 'body'];
            While.prototype.isStatement = YES;
            return While;
        }).call(this);
        //### Op
        // Simple Arithmetic and logical operations. Performs some conversion from
        // CoffeeScript operations into their JavaScript equivalents.
        exports.Op = Op = (function () {
            var CONVERSIONS, INVERSIONS;
            class Op extends Base {
                constructor(op, first, second, flip) {
                    var firstCall;
                    super();
                    if (op === 'in') {
                        return new In(first, second);
                    }
                    if (op === 'do') {
                        return Op.prototype.generateDo(first);
                    }
                    if (op === 'new') {
                        if ((firstCall = first.unwrap()) instanceof Call && !firstCall.do && !firstCall.isNew) {
                            return firstCall.newInstance();
                        }
                        if (first instanceof Code && first.bound || first.do) {
                            first = new Parens(first);
                        }
                    }
                    this.operator = CONVERSIONS[op] || op;
                    this.first = first;
                    this.second = second;
                    this.flip = !!flip;
                    return this;
                }
                isNumber() {
                    var ref1;
                    return this.isUnary() && ((ref1 = this.operator) === '+' || ref1 === '-') && this.first instanceof Value && this.first.isNumber();
                }
                isAwait() {
                    return this.operator === 'await';
                }
                isYield() {
                    var ref1;
                    return (ref1 = this.operator) === 'yield' || ref1 === 'yield*';
                }
                isUnary() {
                    return !this.second;
                }
                shouldCache() {
                    return !this.isNumber();
                }
                // Am I capable of
                // [Python-style comparison chaining](https://docs.python.org/3/reference/expressions.html#not-in)?
                isChainable() {
                    var ref1;
                    return (ref1 = this.operator) === '<' || ref1 === '>' || ref1 === '>=' || ref1 === '<=' || ref1 === '===' || ref1 === '!==';
                }
                invert() {
                    var allInvertable, curr, fst, op, ref1;
                    if (this.isChainable() && this.first.isChainable()) {
                        allInvertable = true;
                        curr = this;
                        while (curr && curr.operator) {
                            allInvertable && (allInvertable = curr.operator in INVERSIONS);
                            curr = curr.first;
                        }
                        if (!allInvertable) {
                            return new Parens(this).invert();
                        }
                        curr = this;
                        while (curr && curr.operator) {
                            curr.invert = !curr.invert;
                            curr.operator = INVERSIONS[curr.operator];
                            curr = curr.first;
                        }
                        return this;
                    }
                    else if (op = INVERSIONS[this.operator]) {
                        this.operator = op;
                        if (this.first.unwrap() instanceof Op) {
                            this.first.invert();
                        }
                        return this;
                    }
                    else if (this.second) {
                        return new Parens(this).invert();
                    }
                    else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((ref1 = fst.operator) === '!' || ref1 === 'in' || ref1 === 'instanceof')) {
                        return fst;
                    }
                    else {
                        return new Op('!', this);
                    }
                }
                unfoldSoak(o) {
                    var ref1;
                    return ((ref1 = this.operator) === '++' || ref1 === '--' || ref1 === 'delete') && unfoldSoak(o, this, 'first');
                }
                generateDo(exp) {
                    var call, func, j, len1, param, passedParams, ref, ref1;
                    passedParams = [];
                    func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp;
                    ref1 = func.params || [];
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        param = ref1[j];
                        if (param.value) {
                            passedParams.push(param.value);
                            delete param.value;
                        }
                        else {
                            passedParams.push(param);
                        }
                    }
                    call = new Call(exp, passedParams);
                    call.do = true;
                    return call;
                }
                compileNode(o) {
                    var answer, isChain, lhs, message, ref1, rhs;
                    isChain = this.isChainable() && this.first.isChainable();
                    if (!isChain) {
                        // In chains, there's no need to wrap bare obj literals in parens,
                        // as the chained expression is wrapped.
                        this.first.front = this.front;
                    }
                    if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) {
                        this.error('delete operand may not be argument or var');
                    }
                    if ((ref1 = this.operator) === '--' || ref1 === '++') {
                        message = isUnassignable(this.first.unwrapAll().value);
                        if (message) {
                            this.first.error(message);
                        }
                    }
                    if (this.isYield() || this.isAwait()) {
                        return this.compileContinuation(o);
                    }
                    if (this.isUnary()) {
                        return this.compileUnary(o);
                    }
                    if (isChain) {
                        return this.compileChain(o);
                    }
                    switch (this.operator) {
                        case '?':
                            return this.compileExistence(o, this.second.isDefaultValue);
                        case '//':
                            return this.compileFloorDivision(o);
                        case '%%':
                            return this.compileModulo(o);
                        default:
                            lhs = this.first.compileToFragments(o, LEVEL_OP);
                            rhs = this.second.compileToFragments(o, LEVEL_OP);
                            answer = [].concat(lhs, this.makeCode(` ${this.operator} `), rhs);
                            if (o.level <= LEVEL_OP) {
                                return answer;
                            }
                            else {
                                return this.wrapInParentheses(answer);
                            }
                    }
                }
                // Mimic Python's chained comparisons when multiple comparison operators are
                // used sequentially. For example:
                //     bin/coffee -e 'console.log 50 < 65 > 10'
                //     true
                compileChain(o) {
                    var fragments, fst, shared;
                    [this.first.second, shared] = this.first.second.cache(o);
                    fst = this.first.compileToFragments(o, LEVEL_OP);
                    fragments = fst.concat(this.makeCode(` ${(this.invert ? '&&' : '||')} `), shared.compileToFragments(o), this.makeCode(` ${this.operator} `), this.second.compileToFragments(o, LEVEL_OP));
                    return this.wrapInParentheses(fragments);
                }
                // Keep reference to the left expression, unless this an existential assignment
                compileExistence(o, checkOnlyUndefined) {
                    var fst, ref;
                    if (this.first.shouldCache()) {
                        ref = new IdentifierLiteral(o.scope.freeVariable('ref'));
                        fst = new Parens(new Assign(ref, this.first));
                    }
                    else {
                        fst = this.first;
                        ref = fst;
                    }
                    return new If(new Existence(fst, checkOnlyUndefined), ref, {
                        type: 'if'
                    }).addElse(this.second).compileToFragments(o);
                }
                // Compile a unary **Op**.
                compileUnary(o) {
                    var op, parts, plusMinus;
                    parts = [];
                    op = this.operator;
                    parts.push([this.makeCode(op)]);
                    if (op === '!' && this.first instanceof Existence) {
                        this.first.negated = !this.first.negated;
                        return this.first.compileToFragments(o);
                    }
                    if (o.level >= LEVEL_ACCESS) {
                        return (new Parens(this)).compileToFragments(o);
                    }
                    plusMinus = op === '+' || op === '-';
                    if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) {
                        parts.push([this.makeCode(' ')]);
                    }
                    if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) {
                        this.first = new Parens(this.first);
                    }
                    parts.push(this.first.compileToFragments(o, LEVEL_OP));
                    if (this.flip) {
                        parts.reverse();
                    }
                    return this.joinFragmentArrays(parts, '');
                }
                compileContinuation(o) {
                    var op, parts, ref1, ref2;
                    parts = [];
                    op = this.operator;
                    if (o.scope.parent == null) {
                        this.error(`${this.operator} can only occur inside functions`);
                    }
                    if (((ref1 = o.scope.method) != null ? ref1.bound : void 0) && o.scope.method.isGenerator) {
                        this.error('yield cannot occur inside bound (fat arrow) functions');
                    }
                    if (indexOf.call(Object.keys(this.first), 'expression') >= 0 && !(this.first instanceof Throw)) {
                        if (this.first.expression != null) {
                            parts.push(this.first.expression.compileToFragments(o, LEVEL_OP));
                        }
                    }
                    else {
                        if (o.level >= LEVEL_PAREN) {
                            parts.push([this.makeCode("(")]);
                        }
                        parts.push([this.makeCode(op)]);
                        if (((ref2 = this.first.base) != null ? ref2.value : void 0) !== '') {
                            parts.push([this.makeCode(" ")]);
                        }
                        parts.push(this.first.compileToFragments(o, LEVEL_OP));
                        if (o.level >= LEVEL_PAREN) {
                            parts.push([this.makeCode(")")]);
                        }
                    }
                    return this.joinFragmentArrays(parts, '');
                }
                compileFloorDivision(o) {
                    var div, floor, second;
                    floor = new Value(new IdentifierLiteral('Math'), [new Access(new PropertyName('floor'))]);
                    second = this.second.shouldCache() ? new Parens(this.second) : this.second;
                    div = new Op('/', this.first, second);
                    return new Call(floor, [div]).compileToFragments(o);
                }
                compileModulo(o) {
                    var mod;
                    mod = new Value(new Literal(utility('modulo', o)));
                    return new Call(mod, [this.first, this.second]).compileToFragments(o);
                }
                toString(idt) {
                    return super.toString(idt, this.constructor.name + ' ' + this.operator);
                }
            }
            ;
            // The map of conversions from CoffeeScript to JavaScript symbols.
            CONVERSIONS = {
                '==': '===',
                '!=': '!==',
                'of': 'in',
                'yieldfrom': 'yield*'
            };
            // The map of invertible operators.
            INVERSIONS = {
                '!==': '===',
                '===': '!=='
            };
            Op.prototype.children = ['first', 'second'];
            return Op;
        }).call(this);
        //### In
        exports.In = In = (function () {
            class In extends Base {
                constructor(object, array) {
                    super();
                    this.object = object;
                    this.array = array;
                }
                compileNode(o) {
                    var hasSplat, j, len1, obj, ref1;
                    if (this.array instanceof Value && this.array.isArray() && this.array.base.objects.length) {
                        ref1 = this.array.base.objects;
                        for (j = 0, len1 = ref1.length; j < len1; j++) {
                            obj = ref1[j];
                            if (!(obj instanceof Splat)) {
                                continue;
                            }
                            hasSplat = true;
                            break;
                        }
                        if (!hasSplat) {
                            // `compileOrTest` only if we have an array literal with no splats
                            return this.compileOrTest(o);
                        }
                    }
                    return this.compileLoopTest(o);
                }
                compileOrTest(o) {
                    var cmp, cnj, i, item, j, len1, ref, ref1, sub, tests;
                    [sub, ref] = this.object.cache(o, LEVEL_OP);
                    [cmp, cnj] = this.negated ? [' !== ', ' && '] : [' === ', ' || '];
                    tests = [];
                    ref1 = this.array.base.objects;
                    for (i = j = 0, len1 = ref1.length; j < len1; i = ++j) {
                        item = ref1[i];
                        if (i) {
                            tests.push(this.makeCode(cnj));
                        }
                        tests = tests.concat((i ? ref : sub), this.makeCode(cmp), item.compileToFragments(o, LEVEL_ACCESS));
                    }
                    if (o.level < LEVEL_OP) {
                        return tests;
                    }
                    else {
                        return this.wrapInParentheses(tests);
                    }
                }
                compileLoopTest(o) {
                    var fragments, ref, sub;
                    [sub, ref] = this.object.cache(o, LEVEL_LIST);
                    fragments = [].concat(this.makeCode(utility('indexOf', o) + ".call("), this.array.compileToFragments(o, LEVEL_LIST), this.makeCode(", "), ref, this.makeCode(") " + (this.negated ? '< 0' : '>= 0')));
                    if (fragmentsToText(sub) === fragmentsToText(ref)) {
                        return fragments;
                    }
                    fragments = sub.concat(this.makeCode(', '), fragments);
                    if (o.level < LEVEL_LIST) {
                        return fragments;
                    }
                    else {
                        return this.wrapInParentheses(fragments);
                    }
                }
                toString(idt) {
                    return super.toString(idt, this.constructor.name + (this.negated ? '!' : ''));
                }
            }
            ;
            In.prototype.children = ['object', 'array'];
            In.prototype.invert = NEGATE;
            return In;
        }).call(this);
        //### Try
        // A classic *try/catch/finally* block.
        exports.Try = Try = (function () {
            class Try extends Base {
                constructor(attempt, errorVariable, recovery, ensure) {
                    super();
                    this.attempt = attempt;
                    this.errorVariable = errorVariable;
                    this.recovery = recovery;
                    this.ensure = ensure;
                }
                jumps(o) {
                    var ref1;
                    return this.attempt.jumps(o) || ((ref1 = this.recovery) != null ? ref1.jumps(o) : void 0);
                }
                makeReturn(res) {
                    if (this.attempt) {
                        this.attempt = this.attempt.makeReturn(res);
                    }
                    if (this.recovery) {
                        this.recovery = this.recovery.makeReturn(res);
                    }
                    return this;
                }
                // Compilation is more or less as you would expect -- the *finally* clause
                // is optional, the *catch* is not.
                compileNode(o) {
                    var catchPart, ensurePart, generatedErrorVariableName, message, placeholder, tryPart;
                    o.indent += TAB;
                    tryPart = this.attempt.compileToFragments(o, LEVEL_TOP);
                    catchPart = this.recovery ? (generatedErrorVariableName = o.scope.freeVariable('error', {
                        reserve: false
                    }), placeholder = new IdentifierLiteral(generatedErrorVariableName), this.errorVariable ? (message = isUnassignable(this.errorVariable.unwrapAll().value), message ? this.errorVariable.error(message) : void 0, this.recovery.unshift(new Assign(this.errorVariable, placeholder))) : void 0, [].concat(this.makeCode(" catch ("), placeholder.compileToFragments(o), this.makeCode(") {\n"), this.recovery.compileToFragments(o, LEVEL_TOP), this.makeCode(`\n${this.tab}}`))) : !(this.ensure || this.recovery) ? (generatedErrorVariableName = o.scope.freeVariable('error', {
                        reserve: false
                    }), [this.makeCode(` catch (${generatedErrorVariableName}) {}`)]) : [];
                    ensurePart = this.ensure ? [].concat(this.makeCode(" finally {\n"), this.ensure.compileToFragments(o, LEVEL_TOP), this.makeCode(`\n${this.tab}}`)) : [];
                    return [].concat(this.makeCode(`${this.tab}try {\n`), tryPart, this.makeCode(`\n${this.tab}}`), catchPart, ensurePart);
                }
            }
            ;
            Try.prototype.children = ['attempt', 'recovery', 'ensure'];
            Try.prototype.isStatement = YES;
            return Try;
        }).call(this);
        //### Throw
        // Simple node to throw an exception.
        exports.Throw = Throw = (function () {
            class Throw extends Base {
                constructor(expression1) {
                    super();
                    this.expression = expression1;
                }
                compileNode(o) {
                    var fragments;
                    fragments = this.expression.compileToFragments(o, LEVEL_LIST);
                    unshiftAfterComments(fragments, this.makeCode('throw '));
                    fragments.unshift(this.makeCode(this.tab));
                    fragments.push(this.makeCode(';'));
                    return fragments;
                }
            }
            ;
            Throw.prototype.children = ['expression'];
            Throw.prototype.isStatement = YES;
            Throw.prototype.jumps = NO;
            // A **Throw** is already a return, of sorts...
            Throw.prototype.makeReturn = THIS;
            return Throw;
        }).call(this);
        //### Existence
        // Checks a variable for existence -- not `null` and not `undefined`. This is
        // similar to `.nil?` in Ruby, and avoids having to consult a JavaScript truth
        // table. Optionally only check if a variable is not `undefined`.
        exports.Existence = Existence = (function () {
            class Existence extends Base {
                constructor(expression1, onlyNotUndefined = false) {
                    var salvagedComments;
                    super();
                    this.expression = expression1;
                    this.comparisonTarget = onlyNotUndefined ? 'undefined' : 'null';
                    salvagedComments = [];
                    this.expression.traverseChildren(true, function (child) {
                        var comment, j, len1, ref1;
                        if (child.comments) {
                            ref1 = child.comments;
                            for (j = 0, len1 = ref1.length; j < len1; j++) {
                                comment = ref1[j];
                                if (indexOf.call(salvagedComments, comment) < 0) {
                                    salvagedComments.push(comment);
                                }
                            }
                            return delete child.comments;
                        }
                    });
                    attachCommentsToNode(salvagedComments, this);
                    moveComments(this.expression, this);
                }
                compileNode(o) {
                    var cmp, cnj, code;
                    this.expression.front = this.front;
                    code = this.expression.compile(o, LEVEL_OP);
                    if (this.expression.unwrap() instanceof IdentifierLiteral && !o.scope.check(code)) {
                        [cmp, cnj] = this.negated ? ['===', '||'] : ['!==', '&&'];
                        code = `typeof ${code} ${cmp} "undefined"` + (this.comparisonTarget !== 'undefined' ? ` ${cnj} ${code} ${cmp} ${this.comparisonTarget}` : '');
                    }
                    else {
                        // We explicity want to use loose equality (`==`) when comparing against `null`,
                        // so that an existence check roughly corresponds to a check for truthiness.
                        // Do *not* change this to `===` for `null`, as this will break mountains of
                        // existing code. When comparing only against `undefined`, however, we want to
                        // use `===` because this use case is for parity with ES2015+ default values,
                        // which only get assigned when the variable is `undefined` (but not `null`).
                        cmp = this.comparisonTarget === 'null' ? this.negated ? '==' : '!=' : this.negated ? '===' : '!=='; // `undefined`
                        code = `${code} ${cmp} ${this.comparisonTarget}`;
                    }
                    return [this.makeCode(o.level <= LEVEL_COND ? code : `(${code})`)];
                }
            }
            ;
            Existence.prototype.children = ['expression'];
            Existence.prototype.invert = NEGATE;
            return Existence;
        }).call(this);
        //### Parens
        // An extra set of parentheses, specified explicitly in the source. At one time
        // we tried to clean up the results by detecting and removing redundant
        // parentheses, but no longer -- you can put in as many as you please.
        // Parentheses are a good way to force any statement to become an expression.
        exports.Parens = Parens = (function () {
            class Parens extends Base {
                constructor(body1) {
                    super();
                    this.body = body1;
                }
                unwrap() {
                    return this.body;
                }
                shouldCache() {
                    return this.body.shouldCache();
                }
                compileNode(o) {
                    var bare, expr, fragments, ref1, shouldWrapComment;
                    expr = this.body.unwrap();
                    // If these parentheses are wrapping an `IdentifierLiteral` followed by a
                    // block comment, output the parentheses (or put another way, don’t optimize
                    // away these redundant parentheses). This is because Flow requires
                    // parentheses in certain circumstances to distinguish identifiers followed
                    // by comment-based type annotations from JavaScript labels.
                    shouldWrapComment = (ref1 = expr.comments) != null ? ref1.some(function (comment) {
                        return comment.here && !comment.unshift && !comment.newLine;
                    }) : void 0;
                    if (expr instanceof Value && expr.isAtomic() && !this.csxAttribute && !shouldWrapComment) {
                        expr.front = this.front;
                        return expr.compileToFragments(o);
                    }
                    fragments = expr.compileToFragments(o, LEVEL_PAREN);
                    bare = o.level < LEVEL_OP && !shouldWrapComment && (expr instanceof Op || expr.unwrap() instanceof Call || (expr instanceof For && expr.returns)) && (o.level < LEVEL_COND || fragments.length <= 3);
                    if (this.csxAttribute) {
                        return this.wrapInBraces(fragments);
                    }
                    if (bare) {
                        return fragments;
                    }
                    else {
                        return this.wrapInParentheses(fragments);
                    }
                }
            }
            ;
            Parens.prototype.children = ['body'];
            return Parens;
        }).call(this);
        //### StringWithInterpolations
        exports.StringWithInterpolations = StringWithInterpolations = (function () {
            class StringWithInterpolations extends Base {
                constructor(body1) {
                    super();
                    this.body = body1;
                }
                // `unwrap` returns `this` to stop ancestor nodes reaching in to grab @body,
                // and using @body.compileNode. `StringWithInterpolations.compileNode` is
                // _the_ custom logic to output interpolated strings as code.
                unwrap() {
                    return this;
                }
                shouldCache() {
                    return this.body.shouldCache();
                }
                compileNode(o) {
                    var code, element, elements, expr, fragments, j, len1, salvagedComments, wrapped;
                    if (this.csxAttribute) {
                        wrapped = new Parens(new StringWithInterpolations(this.body));
                        wrapped.csxAttribute = true;
                        return wrapped.compileNode(o);
                    }
                    // Assumes that `expr` is `Value` » `StringLiteral` or `Op`
                    expr = this.body.unwrap();
                    elements = [];
                    salvagedComments = [];
                    expr.traverseChildren(false, function (node) {
                        var comment, j, k, len1, len2, ref1;
                        if (node instanceof StringLiteral) {
                            if (node.comments) {
                                salvagedComments.push(...node.comments);
                                delete node.comments;
                            }
                            elements.push(node);
                            return true;
                        }
                        else if (node instanceof Parens) {
                            if (salvagedComments.length !== 0) {
                                for (j = 0, len1 = salvagedComments.length; j < len1; j++) {
                                    comment = salvagedComments[j];
                                    comment.unshift = true;
                                    comment.newLine = true;
                                }
                                attachCommentsToNode(salvagedComments, node);
                            }
                            elements.push(node);
                            return false;
                        }
                        else if (node.comments) {
                            // This node is getting discarded, but salvage its comments.
                            if (elements.length !== 0 && !(elements[elements.length - 1] instanceof StringLiteral)) {
                                ref1 = node.comments;
                                for (k = 0, len2 = ref1.length; k < len2; k++) {
                                    comment = ref1[k];
                                    comment.unshift = false;
                                    comment.newLine = true;
                                }
                                attachCommentsToNode(node.comments, elements[elements.length - 1]);
                            }
                            else {
                                salvagedComments.push(...node.comments);
                            }
                            delete node.comments;
                        }
                        return true;
                    });
                    fragments = [];
                    if (!this.csx) {
                        fragments.push(this.makeCode('`'));
                    }
                    for (j = 0, len1 = elements.length; j < len1; j++) {
                        element = elements[j];
                        if (element instanceof StringLiteral) {
                            element.value = element.unquote(true, this.csx);
                            if (!this.csx) {
                                // Backticks and `${` inside template literals must be escaped.
                                element.value = element.value.replace(/(\\*)(`|\$\{)/g, function (match, backslashes, toBeEscaped) {
                                    if (backslashes.length % 2 === 0) {
                                        return `${backslashes}\\${toBeEscaped}`;
                                    }
                                    else {
                                        return match;
                                    }
                                });
                            }
                            fragments.push(...element.compileToFragments(o));
                        }
                        else {
                            if (!this.csx) {
                                fragments.push(this.makeCode('$'));
                            }
                            code = element.compileToFragments(o, LEVEL_PAREN);
                            if (!this.isNestedTag(element) || code.some(function (fragment) {
                                return fragment.comments != null;
                            })) {
                                code = this.wrapInBraces(code);
                                // Flag the `{` and `}` fragments as having been generated by this
                                // `StringWithInterpolations` node, so that `compileComments` knows
                                // to treat them as bounds. Don’t trust `fragment.type`, which can
                                // report minified variable names when this compiler is minified.
                                code[0].isStringWithInterpolations = true;
                                code[code.length - 1].isStringWithInterpolations = true;
                            }
                            fragments.push(...code);
                        }
                    }
                    if (!this.csx) {
                        fragments.push(this.makeCode('`'));
                    }
                    return fragments;
                }
                isNestedTag(element) {
                    var call, exprs, ref1;
                    exprs = (ref1 = element.body) != null ? ref1.expressions : void 0;
                    call = exprs != null ? exprs[0].unwrap() : void 0;
                    return this.csx && exprs && exprs.length === 1 && call instanceof Call && call.csx;
                }
            }
            ;
            StringWithInterpolations.prototype.children = ['body'];
            return StringWithInterpolations;
        }).call(this);
        //### For
        // CoffeeScript's replacement for the *for* loop is our array and object
        // comprehensions, that compile into *for* loops here. They also act as an
        // expression, able to return the result of each filtered iteration.
        // Unlike Python array comprehensions, they can be multi-line, and you can pass
        // the current index of the loop as a second parameter. Unlike Ruby blocks,
        // you can map and filter in a single pass.
        exports.For = For = (function () {
            class For extends While {
                constructor(body, source) {
                    super();
                    this.addBody(body);
                    this.addSource(source);
                }
                isAwait() {
                    var ref1;
                    return (ref1 = this.await) != null ? ref1 : false;
                }
                addBody(body) {
                    this.body = Block.wrap([body]);
                    return this;
                }
                addSource(source) {
                    var attr, attribs, attribute, j, k, len1, len2, ref1, ref2, ref3, ref4;
                    ({ source: this.source = false } = source);
                    attribs = ["name", "index", "guard", "step", "own", "ownTag", "await", "awaitTag", "object", "from"];
                    for (j = 0, len1 = attribs.length; j < len1; j++) {
                        attr = attribs[j];
                        this[attr] = (ref1 = source[attr]) != null ? ref1 : this[attr];
                    }
                    if (!this.source) {
                        return this;
                    }
                    if (this.from && this.index) {
                        this.index.error('cannot use index with for-from');
                    }
                    if (this.own && !this.object) {
                        this.ownTag.error(`cannot use own with for-${(this.from ? 'from' : 'in')}`);
                    }
                    if (this.object) {
                        [this.name, this.index] = [this.index, this.name];
                    }
                    if (((ref2 = this.index) != null ? typeof ref2.isArray === "function" ? ref2.isArray() : void 0 : void 0) || ((ref3 = this.index) != null ? typeof ref3.isObject === "function" ? ref3.isObject() : void 0 : void 0)) {
                        this.index.error('index cannot be a pattern matching expression');
                    }
                    if (this.await && !this.from) {
                        this.awaitTag.error('await must be used with for-from');
                    }
                    this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length && !this.from;
                    this.pattern = this.name instanceof Value;
                    if (this.range && this.index) {
                        this.index.error('indexes do not apply to range loops');
                    }
                    if (this.range && this.pattern) {
                        this.name.error('cannot pattern match over range loops');
                    }
                    this.returns = false;
                    ref4 = ['source', 'guard', 'step', 'name', 'index'];
                    // Move up any comments in the “`for` line”, i.e. the line of code with `for`,
                    // from any child nodes of that line up to the `for` node itself so that these
                    // comments get output, and get output above the `for` loop.
                    for (k = 0, len2 = ref4.length; k < len2; k++) {
                        attribute = ref4[k];
                        if (!this[attribute]) {
                            continue;
                        }
                        this[attribute].traverseChildren(true, (node) => {
                            var comment, l, len3, ref5;
                            if (node.comments) {
                                ref5 = node.comments;
                                for (l = 0, len3 = ref5.length; l < len3; l++) {
                                    comment = ref5[l];
                                    // These comments are buried pretty deeply, so if they happen to be
                                    // trailing comments the line they trail will be unrecognizable when
                                    // we’re done compiling this `for` loop; so just shift them up to
                                    // output above the `for` line.
                                    comment.newLine = comment.unshift = true;
                                }
                                return moveComments(node, this[attribute]);
                            }
                        });
                        moveComments(this[attribute], this);
                    }
                    return this;
                }
                // Welcome to the hairiest method in all of CoffeeScript. Handles the inner
                // loop, filtering, stepping, and result saving for array, object, and range
                // comprehensions. Some of the generated code can be shared in common, and
                // some cannot.
                compileNode(o) {
                    var body, bodyFragments, compare, compareDown, declare, declareDown, defPart, down, forClose, forCode, forPartFragments, fragments, guardPart, idt1, increment, index, ivar, kvar, kvarAssign, last, lvar, name, namePart, ref, ref1, resultPart, returnResult, rvar, scope, source, step, stepNum, stepVar, svar, varPart;
                    body = Block.wrap([this.body]);
                    ref1 = body.expressions, [last] = slice1.call(ref1, -1);
                    if ((last != null ? last.jumps() : void 0) instanceof Return) {
                        this.returns = false;
                    }
                    source = this.range ? this.source.base : this.source;
                    scope = o.scope;
                    if (!this.pattern) {
                        name = this.name && (this.name.compile(o, LEVEL_LIST));
                    }
                    index = this.index && (this.index.compile(o, LEVEL_LIST));
                    if (name && !this.pattern) {
                        scope.find(name);
                    }
                    if (index && !(this.index instanceof Value)) {
                        scope.find(index);
                    }
                    if (this.returns) {
                        rvar = scope.freeVariable('results');
                    }
                    if (this.from) {
                        if (this.pattern) {
                            ivar = scope.freeVariable('x', {
                                single: true
                            });
                        }
                    }
                    else {
                        ivar = (this.object && index) || scope.freeVariable('i', {
                            single: true
                        });
                    }
                    kvar = ((this.range || this.from) && name) || index || ivar;
                    kvarAssign = kvar !== ivar ? `${kvar} = ` : "";
                    if (this.step && !this.range) {
                        [step, stepVar] = this.cacheToCodeFragments(this.step.cache(o, LEVEL_LIST, shouldCacheOrIsAssignable));
                        if (this.step.isNumber()) {
                            stepNum = Number(stepVar);
                        }
                    }
                    if (this.pattern) {
                        name = ivar;
                    }
                    varPart = '';
                    guardPart = '';
                    defPart = '';
                    idt1 = this.tab + TAB;
                    if (this.range) {
                        forPartFragments = source.compileToFragments(merge(o, {
                            index: ivar,
                            name,
                            step: this.step,
                            shouldCache: shouldCacheOrIsAssignable
                        }));
                    }
                    else {
                        svar = this.source.compile(o, LEVEL_LIST);
                        if ((name || this.own) && !(this.source.unwrap() instanceof IdentifierLiteral)) {
                            defPart += `${this.tab}${(ref = scope.freeVariable('ref'))} = ${svar};\n`;
                            svar = ref;
                        }
                        if (name && !this.pattern && !this.from) {
                            namePart = `${name} = ${svar}[${kvar}]`;
                        }
                        if (!this.object && !this.from) {
                            if (step !== stepVar) {
                                defPart += `${this.tab}${step};\n`;
                            }
                            down = stepNum < 0;
                            if (!(this.step && (stepNum != null) && down)) {
                                lvar = scope.freeVariable('len');
                            }
                            declare = `${kvarAssign}${ivar} = 0, ${lvar} = ${svar}.length`;
                            declareDown = `${kvarAssign}${ivar} = ${svar}.length - 1`;
                            compare = `${ivar} < ${lvar}`;
                            compareDown = `${ivar} >= 0`;
                            if (this.step) {
                                if (stepNum != null) {
                                    if (down) {
                                        compare = compareDown;
                                        declare = declareDown;
                                    }
                                }
                                else {
                                    compare = `${stepVar} > 0 ? ${compare} : ${compareDown}`;
                                    declare = `(${stepVar} > 0 ? (${declare}) : ${declareDown})`;
                                }
                                increment = `${ivar} += ${stepVar}`;
                            }
                            else {
                                increment = `${(kvar !== ivar ? `++${ivar}` : `${ivar}++`)}`;
                            }
                            forPartFragments = [this.makeCode(`${declare}; ${compare}; ${kvarAssign}${increment}`)];
                        }
                    }
                    if (this.returns) {
                        resultPart = `${this.tab}${rvar} = [];\n`;
                        returnResult = `\n${this.tab}return ${rvar};`;
                        body.makeReturn(rvar);
                    }
                    if (this.guard) {
                        if (body.expressions.length > 1) {
                            body.expressions.unshift(new If((new Parens(this.guard)).invert(), new StatementLiteral("continue")));
                        }
                        else {
                            if (this.guard) {
                                body = Block.wrap([new If(this.guard, body)]);
                            }
                        }
                    }
                    if (this.pattern) {
                        body.expressions.unshift(new Assign(this.name, this.from ? new IdentifierLiteral(kvar) : new Literal(`${svar}[${kvar}]`)));
                    }
                    if (namePart) {
                        varPart = `\n${idt1}${namePart};`;
                    }
                    if (this.object) {
                        forPartFragments = [this.makeCode(`${kvar} in ${svar}`)];
                        if (this.own) {
                            guardPart = `\n${idt1}if (!${utility('hasProp', o)}.call(${svar}, ${kvar})) continue;`;
                        }
                    }
                    else if (this.from) {
                        if (this.await) {
                            forPartFragments = new Op('await', new Parens(new Literal(`${kvar} of ${svar}`)));
                            forPartFragments = forPartFragments.compileToFragments(o, LEVEL_TOP);
                        }
                        else {
                            forPartFragments = [this.makeCode(`${kvar} of ${svar}`)];
                        }
                    }
                    bodyFragments = body.compileToFragments(merge(o, {
                        indent: idt1
                    }), LEVEL_TOP);
                    if (bodyFragments && bodyFragments.length > 0) {
                        bodyFragments = [].concat(this.makeCode('\n'), bodyFragments, this.makeCode('\n'));
                    }
                    fragments = [this.makeCode(defPart)];
                    if (resultPart) {
                        fragments.push(this.makeCode(resultPart));
                    }
                    forCode = this.await ? 'for ' : 'for (';
                    forClose = this.await ? '' : ')';
                    fragments = fragments.concat(this.makeCode(this.tab), this.makeCode(forCode), forPartFragments, this.makeCode(`${forClose} {${guardPart}${varPart}`), bodyFragments, this.makeCode(this.tab), this.makeCode('}'));
                    if (returnResult) {
                        fragments.push(this.makeCode(returnResult));
                    }
                    return fragments;
                }
            }
            ;
            For.prototype.children = ['body', 'source', 'guard', 'step'];
            return For;
        }).call(this);
        //### Switch
        // A JavaScript *switch* statement. Converts into a returnable expression on-demand.
        exports.Switch = Switch = (function () {
            class Switch extends Base {
                constructor(subject, cases, otherwise) {
                    super();
                    this.subject = subject;
                    this.cases = cases;
                    this.otherwise = otherwise;
                }
                jumps(o = {
                    block: true
                }) {
                    var block, conds, j, jumpNode, len1, ref1, ref2;
                    ref1 = this.cases;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        [conds, block] = ref1[j];
                        if (jumpNode = block.jumps(o)) {
                            return jumpNode;
                        }
                    }
                    return (ref2 = this.otherwise) != null ? ref2.jumps(o) : void 0;
                }
                makeReturn(res) {
                    var j, len1, pair, ref1, ref2;
                    ref1 = this.cases;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                        pair = ref1[j];
                        pair[1].makeReturn(res);
                    }
                    if (res) {
                        this.otherwise || (this.otherwise = new Block([new Literal('void 0')]));
                    }
                    if ((ref2 = this.otherwise) != null) {
                        ref2.makeReturn(res);
                    }
                    return this;
                }
                compileNode(o) {
                    var block, body, cond, conditions, expr, fragments, i, idt1, idt2, j, k, len1, len2, ref1, ref2;
                    idt1 = o.indent + TAB;
                    idt2 = o.indent = idt1 + TAB;
                    fragments = [].concat(this.makeCode(this.tab + "switch ("), (this.subject ? this.subject.compileToFragments(o, LEVEL_PAREN) : this.makeCode("false")), this.makeCode(") {\n"));
                    ref1 = this.cases;
                    for (i = j = 0, len1 = ref1.length; j < len1; i = ++j) {
                        [conditions, block] = ref1[i];
                        ref2 = flatten([conditions]);
                        for (k = 0, len2 = ref2.length; k < len2; k++) {
                            cond = ref2[k];
                            if (!this.subject) {
                                cond = cond.invert();
                            }
                            fragments = fragments.concat(this.makeCode(idt1 + "case "), cond.compileToFragments(o, LEVEL_PAREN), this.makeCode(":\n"));
                        }
                        if ((body = block.compileToFragments(o, LEVEL_TOP)).length > 0) {
                            fragments = fragments.concat(body, this.makeCode('\n'));
                        }
                        if (i === this.cases.length - 1 && !this.otherwise) {
                            break;
                        }
                        expr = this.lastNode(block.expressions);
                        if (expr instanceof Return || expr instanceof Throw || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) {
                            continue;
                        }
                        fragments.push(cond.makeCode(idt2 + 'break;\n'));
                    }
                    if (this.otherwise && this.otherwise.expressions.length) {
                        fragments.push(this.makeCode(idt1 + "default:\n"), ...(this.otherwise.compileToFragments(o, LEVEL_TOP)), this.makeCode("\n"));
                    }
                    fragments.push(this.makeCode(this.tab + '}'));
                    return fragments;
                }
            }
            ;
            Switch.prototype.children = ['subject', 'cases', 'otherwise'];
            Switch.prototype.isStatement = YES;
            return Switch;
        }).call(this);
        //### If
        // *If/else* statements. Acts as an expression by pushing down requested returns
        // to the last line of each clause.
        // Single-expression **Ifs** are compiled into conditional operators if possible,
        // because ternaries are already proper expressions, and don’t need conversion.
        exports.If = If = (function () {
            class If extends Base {
                constructor(condition, body1, options = {}) {
                    super();
                    this.body = body1;
                    this.condition = options.type === 'unless' ? condition.invert() : condition;
                    this.elseBody = null;
                    this.isChain = false;
                    ({ soak: this.soak } = options);
                    if (this.condition.comments) {
                        moveComments(this.condition, this);
                    }
                }
                bodyNode() {
                    var ref1;
                    return (ref1 = this.body) != null ? ref1.unwrap() : void 0;
                }
                elseBodyNode() {
                    var ref1;
                    return (ref1 = this.elseBody) != null ? ref1.unwrap() : void 0;
                }
                // Rewrite a chain of **Ifs** to add a default case as the final *else*.
                addElse(elseBody) {
                    if (this.isChain) {
                        this.elseBodyNode().addElse(elseBody);
                    }
                    else {
                        this.isChain = elseBody instanceof If;
                        this.elseBody = this.ensureBlock(elseBody);
                        this.elseBody.updateLocationDataIfMissing(elseBody.locationData);
                    }
                    return this;
                }
                // The **If** only compiles into a statement if either of its bodies needs
                // to be a statement. Otherwise a conditional operator is safe.
                isStatement(o) {
                    var ref1;
                    return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((ref1 = this.elseBodyNode()) != null ? ref1.isStatement(o) : void 0);
                }
                jumps(o) {
                    var ref1;
                    return this.body.jumps(o) || ((ref1 = this.elseBody) != null ? ref1.jumps(o) : void 0);
                }
                compileNode(o) {
                    if (this.isStatement(o)) {
                        return this.compileStatement(o);
                    }
                    else {
                        return this.compileExpression(o);
                    }
                }
                makeReturn(res) {
                    if (res) {
                        this.elseBody || (this.elseBody = new Block([new Literal('void 0')]));
                    }
                    this.body && (this.body = new Block([this.body.makeReturn(res)]));
                    this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)]));
                    return this;
                }
                ensureBlock(node) {
                    if (node instanceof Block) {
                        return node;
                    }
                    else {
                        return new Block([node]);
                    }
                }
                // Compile the `If` as a regular *if-else* statement. Flattened chains
                // force inner *else* bodies into statement form.
                compileStatement(o) {
                    var answer, body, child, cond, exeq, ifPart, indent;
                    child = del(o, 'chainChild');
                    exeq = del(o, 'isExistentialEquals');
                    if (exeq) {
                        return new If(this.condition.invert(), this.elseBodyNode(), {
                            type: 'if'
                        }).compileToFragments(o);
                    }
                    indent = o.indent + TAB;
                    cond = this.condition.compileToFragments(o, LEVEL_PAREN);
                    body = this.ensureBlock(this.body).compileToFragments(merge(o, { indent }));
                    ifPart = [].concat(this.makeCode("if ("), cond, this.makeCode(") {\n"), body, this.makeCode(`\n${this.tab}}`));
                    if (!child) {
                        ifPart.unshift(this.makeCode(this.tab));
                    }
                    if (!this.elseBody) {
                        return ifPart;
                    }
                    answer = ifPart.concat(this.makeCode(' else '));
                    if (this.isChain) {
                        o.chainChild = true;
                        answer = answer.concat(this.elseBody.unwrap().compileToFragments(o, LEVEL_TOP));
                    }
                    else {
                        answer = answer.concat(this.makeCode("{\n"), this.elseBody.compileToFragments(merge(o, { indent }), LEVEL_TOP), this.makeCode(`\n${this.tab}}`));
                    }
                    return answer;
                }
                // Compile the `If` as a conditional operator.
                compileExpression(o) {
                    var alt, body, cond, fragments;
                    cond = this.condition.compileToFragments(o, LEVEL_COND);
                    body = this.bodyNode().compileToFragments(o, LEVEL_LIST);
                    alt = this.elseBodyNode() ? this.elseBodyNode().compileToFragments(o, LEVEL_LIST) : [this.makeCode('void 0')];
                    fragments = cond.concat(this.makeCode(" ? "), body, this.makeCode(" : "), alt);
                    if (o.level >= LEVEL_COND) {
                        return this.wrapInParentheses(fragments);
                    }
                    else {
                        return fragments;
                    }
                }
                unfoldSoak() {
                    return this.soak && this;
                }
            }
            ;
            If.prototype.children = ['condition', 'body', 'elseBody'];
            return If;
        }).call(this);
        // Constants
        // ---------
        UTILITIES = {
            modulo: function () {
                return 'function(a, b) { return (+a % (b = +b) + b) % b; }';
            },
            boundMethodCheck: function () {
                return "function(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new Error('Bound instance method accessed before binding'); } }";
            },
            // Shortcuts to speed up the lookup time for native functions.
            hasProp: function () {
                return '{}.hasOwnProperty';
            },
            indexOf: function () {
                return '[].indexOf';
            },
            slice: function () {
                return '[].slice';
            },
            splice: function () {
                return '[].splice';
            }
        };
        // Levels indicate a node's position in the AST. Useful for knowing if
        // parens are necessary or superfluous.
        LEVEL_TOP = 1; // ...;
        LEVEL_PAREN = 2; // (...)
        LEVEL_LIST = 3; // [...]
        LEVEL_COND = 4; // ... ? x : y
        LEVEL_OP = 5; // !...
        LEVEL_ACCESS = 6; // ...[0]
        // Tabs are two spaces for pretty printing.
        TAB = '  ';
        SIMPLENUM = /^[+-]?\d+$/;
        // Helper Functions
        // ----------------
        // Helper for ensuring that utility functions are assigned at the top level.
        utility = function (name, o) {
            var ref, root;
            ({ root } = o.scope);
            if (name in root.utilities) {
                return root.utilities[name];
            }
            else {
                ref = root.freeVariable(name);
                root.assign(ref, UTILITIES[name](o));
                return root.utilities[name] = ref;
            }
        };
        multident = function (code, tab, includingFirstLine = true) {
            var endsWithNewLine;
            endsWithNewLine = code[code.length - 1] === '\n';
            code = (includingFirstLine ? tab : '') + code.replace(/\n/g, `$&${tab}`);
            code = code.replace(/\s+$/, '');
            if (endsWithNewLine) {
                code = code + '\n';
            }
            return code;
        };
        // Wherever in CoffeeScript 1 we might’ve inserted a `makeCode "#{@tab}"` to
        // indent a line of code, now we must account for the possibility of comments
        // preceding that line of code. If there are such comments, indent each line of
        // such comments, and _then_ indent the first following line of code.
        indentInitial = function (fragments, node) {
            var fragment, fragmentIndex, j, len1;
            for (fragmentIndex = j = 0, len1 = fragments.length; j < len1; fragmentIndex = ++j) {
                fragment = fragments[fragmentIndex];
                if (fragment.isHereComment) {
                    fragment.code = multident(fragment.code, node.tab);
                }
                else {
                    fragments.splice(fragmentIndex, 0, node.makeCode(`${node.tab}`));
                    break;
                }
            }
            return fragments;
        };
        hasLineComments = function (node) {
            var comment, j, len1, ref1;
            if (!node.comments) {
                return false;
            }
            ref1 = node.comments;
            for (j = 0, len1 = ref1.length; j < len1; j++) {
                comment = ref1[j];
                if (comment.here === false) {
                    return true;
                }
            }
            return false;
        };
        // Move the `comments` property from one object to another, deleting it from
        // the first object.
        moveComments = function (from, to) {
            if (!(from != null ? from.comments : void 0)) {
                return;
            }
            attachCommentsToNode(from.comments, to);
            return delete from.comments;
        };
        // Sometimes when compiling a node, we want to insert a fragment at the start
        // of an array of fragments; but if the start has one or more comment fragments,
        // we want to insert this fragment after those but before any non-comments.
        unshiftAfterComments = function (fragments, fragmentToInsert) {
            var fragment, fragmentIndex, inserted, j, len1;
            inserted = false;
            for (fragmentIndex = j = 0, len1 = fragments.length; j < len1; fragmentIndex = ++j) {
                fragment = fragments[fragmentIndex];
                if (!(!fragment.isComment)) {
                    continue;
                }
                fragments.splice(fragmentIndex, 0, fragmentToInsert);
                inserted = true;
                break;
            }
            if (!inserted) {
                fragments.push(fragmentToInsert);
            }
            return fragments;
        };
        isLiteralArguments = function (node) {
            return node instanceof IdentifierLiteral && node.value === 'arguments';
        };
        isLiteralThis = function (node) {
            return node instanceof ThisLiteral || (node instanceof Code && node.bound);
        };
        shouldCacheOrIsAssignable = function (node) {
            return node.shouldCache() || (typeof node.isAssignable === "function" ? node.isAssignable() : void 0);
        };
        // Unfold a node's child if soak, then tuck the node under created `If`
        unfoldSoak = function (o, parent, name) {
            var ifn;
            if (!(ifn = parent[name].unfoldSoak(o))) {
                return;
            }
            parent[name] = ifn.body;
            ifn.body = new Value(parent);
            return ifn;
        };
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/parser */ function _(require, module, exports) {
    /* parser generated by jison 0.4.18 */
    /*
      Returns a Parser object of the following structure:
    
      Parser: {
        yy: {}
      }
    
      Parser.prototype: {
        yy: {},
        trace: function(),
        symbols_: {associative list: name ==> number},
        terminals_: {associative list: number ==> name},
        productions_: [...],
        performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),
        table: [...],
        defaultActions: {...},
        parseError: function(str, hash),
        parse: function(input),
    
        lexer: {
            EOF: 1,
            parseError: function(str, hash),
            setInput: function(input),
            input: function(),
            unput: function(str),
            more: function(),
            less: function(n),
            pastInput: function(),
            upcomingInput: function(),
            showPosition: function(),
            test_match: function(regex_match_array, rule_index),
            next: function(),
            lex: function(),
            begin: function(condition),
            popState: function(),
            _currentRules: function(),
            topState: function(),
            pushState: function(condition),
    
            options: {
                ranges: boolean           (optional: true ==> token location info will include a .range[] member)
                flex: boolean             (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)
                backtrack_lexer: boolean  (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)
            },
    
            performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),
            rules: [...],
            conditions: {associative list: name ==> set},
        }
      }
    
    
      token location info (@$, _$, etc.): {
        first_line: n,
        last_line: n,
        first_column: n,
        last_column: n,
        range: [start_number, end_number]       (where the numbers are indexes into the input string, regular zero-based)
      }
    
    
      the parseError function receives a 'hash' object with these members for lexer and parser errors: {
        text:        (matched text)
        token:       (the produced terminal token, if any)
        line:        (yylineno)
      }
      while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {
        loc:         (yylloc)
        expected:    (string describing the set of expected tokens)
        recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)
      }
    */
    var parser = (function () {
        var o = function (k, v, o, l) { for (o = o || {}, l = k.length; l--; o[k[l]] = v)
            ; return o; }, $V0 = [1, 24], $V1 = [1, 56], $V2 = [1, 91], $V3 = [1, 92], $V4 = [1, 87], $V5 = [1, 93], $V6 = [1, 94], $V7 = [1, 89], $V8 = [1, 90], $V9 = [1, 64], $Va = [1, 66], $Vb = [1, 67], $Vc = [1, 68], $Vd = [1, 69], $Ve = [1, 70], $Vf = [1, 72], $Vg = [1, 73], $Vh = [1, 58], $Vi = [1, 42], $Vj = [1, 36], $Vk = [1, 76], $Vl = [1, 77], $Vm = [1, 86], $Vn = [1, 54], $Vo = [1, 59], $Vp = [1, 60], $Vq = [1, 74], $Vr = [1, 75], $Vs = [1, 47], $Vt = [1, 55], $Vu = [1, 71], $Vv = [1, 81], $Vw = [1, 82], $Vx = [1, 83], $Vy = [1, 84], $Vz = [1, 53], $VA = [1, 80], $VB = [1, 38], $VC = [1, 39], $VD = [1, 40], $VE = [1, 41], $VF = [1, 43], $VG = [1, 44], $VH = [1, 95], $VI = [1, 6, 36, 47, 146], $VJ = [1, 6, 35, 36, 47, 69, 70, 93, 127, 135, 146, 149, 157], $VK = [1, 113], $VL = [1, 114], $VM = [1, 115], $VN = [1, 110], $VO = [1, 98], $VP = [1, 97], $VQ = [1, 96], $VR = [1, 99], $VS = [1, 100], $VT = [1, 101], $VU = [1, 102], $VV = [1, 103], $VW = [1, 104], $VX = [1, 105], $VY = [1, 106], $VZ = [1, 107], $V_ = [1, 108], $V$ = [1, 109], $V01 = [1, 117], $V11 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $V21 = [2, 196], $V31 = [1, 123], $V41 = [1, 128], $V51 = [1, 124], $V61 = [1, 125], $V71 = [1, 126], $V81 = [1, 129], $V91 = [1, 122], $Va1 = [1, 6, 35, 36, 47, 69, 70, 93, 127, 135, 146, 148, 149, 150, 156, 157, 174], $Vb1 = [1, 6, 35, 36, 45, 46, 47, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vc1 = [2, 122], $Vd1 = [2, 126], $Ve1 = [6, 35, 88, 93], $Vf1 = [2, 99], $Vg1 = [1, 141], $Vh1 = [1, 135], $Vi1 = [1, 140], $Vj1 = [1, 144], $Vk1 = [1, 149], $Vl1 = [1, 147], $Vm1 = [1, 151], $Vn1 = [1, 155], $Vo1 = [1, 153], $Vp1 = [1, 6, 35, 36, 45, 46, 47, 61, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vq1 = [2, 119], $Vr1 = [1, 6, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vs1 = [2, 31], $Vt1 = [1, 183], $Vu1 = [2, 86], $Vv1 = [1, 187], $Vw1 = [1, 193], $Vx1 = [1, 208], $Vy1 = [1, 203], $Vz1 = [1, 212], $VA1 = [1, 209], $VB1 = [1, 214], $VC1 = [1, 215], $VD1 = [1, 217], $VE1 = [14, 32, 35, 38, 39, 43, 45, 46, 49, 50, 54, 55, 56, 57, 58, 59, 68, 77, 84, 85, 86, 90, 91, 107, 110, 112, 120, 129, 130, 140, 144, 145, 148, 150, 153, 156, 167, 173, 176, 177, 178, 179, 180, 181], $VF1 = [1, 6, 35, 36, 45, 46, 47, 61, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 111, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194], $VG1 = [1, 228], $VH1 = [1, 229], $VI1 = [2, 142], $VJ1 = [1, 245], $VK1 = [1, 247], $VL1 = [1, 257], $VM1 = [1, 6, 35, 36, 45, 46, 47, 65, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $VN1 = [1, 6, 33, 35, 36, 45, 46, 47, 61, 65, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 111, 117, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 164, 165, 166, 174, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194], $VO1 = [1, 6, 35, 36, 45, 46, 47, 52, 65, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $VP1 = [1, 287], $VQ1 = [45, 46, 126], $VR1 = [1, 298], $VS1 = [1, 297], $VT1 = [6, 35], $VU1 = [2, 97], $VV1 = [1, 304], $VW1 = [6, 35, 36, 88, 93], $VX1 = [6, 35, 36, 61, 70, 88, 93], $VY1 = [1, 6, 35, 36, 47, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $VZ1 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $V_1 = [2, 348], $V$1 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 183, 185, 186, 187, 188, 189, 190, 191, 192, 193], $V02 = [45, 46, 80, 81, 101, 102, 103, 105, 125, 126], $V12 = [1, 331], $V22 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174], $V32 = [2, 84], $V42 = [1, 347], $V52 = [1, 349], $V62 = [1, 354], $V72 = [1, 356], $V82 = [6, 35, 69, 93], $V92 = [2, 221], $Va2 = [2, 222], $Vb2 = [1, 6, 35, 36, 45, 46, 47, 61, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 164, 165, 166, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vc2 = [1, 370], $Vd2 = [6, 14, 32, 35, 36, 38, 39, 43, 45, 46, 49, 50, 54, 55, 56, 57, 58, 59, 68, 69, 70, 77, 84, 85, 86, 90, 91, 93, 107, 110, 112, 120, 129, 130, 140, 144, 145, 148, 150, 153, 156, 167, 173, 176, 177, 178, 179, 180, 181], $Ve2 = [6, 35, 36, 69, 93], $Vf2 = [6, 35, 36, 69, 93, 127], $Vg2 = [1, 6, 35, 36, 45, 46, 47, 61, 65, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 111, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 164, 165, 166, 174, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194], $Vh2 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 157, 174], $Vi2 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 149, 157, 174], $Vj2 = [2, 273], $Vk2 = [164, 165, 166], $Vl2 = [93, 164, 165, 166], $Vm2 = [6, 35, 109], $Vn2 = [1, 395], $Vo2 = [6, 35, 36, 93, 109], $Vp2 = [6, 35, 36, 65, 93, 109], $Vq2 = [1, 401], $Vr2 = [1, 402], $Vs2 = [6, 35, 36, 61, 65, 70, 80, 81, 93, 109, 126], $Vt2 = [6, 35, 36, 70, 80, 81, 93, 109, 126], $Vu2 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vv2 = [2, 340], $Vw2 = [2, 339], $Vx2 = [1, 6, 35, 36, 45, 46, 47, 52, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 125, 126, 127, 135, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vy2 = [1, 424], $Vz2 = [14, 32, 38, 39, 43, 45, 46, 49, 50, 54, 55, 56, 57, 58, 59, 68, 77, 83, 84, 85, 86, 90, 91, 107, 110, 112, 120, 129, 130, 140, 144, 145, 148, 150, 153, 156, 167, 173, 176, 177, 178, 179, 180, 181], $VA2 = [2, 207], $VB2 = [6, 35, 36], $VC2 = [2, 98], $VD2 = [1, 433], $VE2 = [1, 434], $VF2 = [1, 6, 35, 36, 47, 69, 70, 80, 81, 83, 88, 93, 101, 102, 103, 105, 109, 127, 135, 142, 143, 146, 148, 149, 150, 156, 157, 169, 171, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $VG2 = [1, 313], $VH2 = [36, 169, 171], $VI2 = [1, 6, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 149, 157, 174], $VJ2 = [1, 469], $VK2 = [1, 475], $VL2 = [1, 6, 35, 36, 47, 69, 70, 93, 127, 135, 146, 149, 157, 174], $VM2 = [2, 113], $VN2 = [1, 488], $VO2 = [1, 489], $VP2 = [6, 35, 36, 69], $VQ2 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 169, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $VR2 = [1, 6, 35, 36, 47, 69, 70, 93, 127, 135, 146, 149, 157, 169], $VS2 = [2, 287], $VT2 = [2, 288], $VU2 = [2, 303], $VV2 = [1, 512], $VW2 = [1, 513], $VX2 = [6, 35, 36, 109], $VY2 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 150, 156, 157, 174], $VZ2 = [1, 534], $V_2 = [6, 35, 36, 93, 127], $V$2 = [6, 35, 36, 93], $V03 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 142, 146, 148, 149, 150, 156, 157, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $V13 = [35, 93], $V23 = [1, 562], $V33 = [1, 563], $V43 = [1, 569], $V53 = [1, 570], $V63 = [2, 258], $V73 = [2, 261], $V83 = [2, 274], $V93 = [1, 619], $Va3 = [1, 620], $Vb3 = [2, 289], $Vc3 = [2, 293], $Vd3 = [2, 290], $Ve3 = [2, 294], $Vf3 = [2, 291], $Vg3 = [2, 292], $Vh3 = [2, 304], $Vi3 = [2, 305], $Vj3 = [1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 174], $Vk3 = [2, 295], $Vl3 = [2, 297], $Vm3 = [2, 299], $Vn3 = [2, 301], $Vo3 = [2, 296], $Vp3 = [2, 298], $Vq3 = [2, 300], $Vr3 = [2, 302];
        var parser = { trace: function trace() { },
            yy: {},
            symbols_: { "error": 2, "Root": 3, "Body": 4, "Line": 5, "TERMINATOR": 6, "Expression": 7, "ExpressionLine": 8, "Statement": 9, "FuncDirective": 10, "YieldReturn": 11, "AwaitReturn": 12, "Return": 13, "STATEMENT": 14, "Import": 15, "Export": 16, "Value": 17, "Code": 18, "Operation": 19, "Assign": 20, "If": 21, "Try": 22, "While": 23, "For": 24, "Switch": 25, "Class": 26, "Throw": 27, "Yield": 28, "CodeLine": 29, "IfLine": 30, "OperationLine": 31, "YIELD": 32, "FROM": 33, "Block": 34, "INDENT": 35, "OUTDENT": 36, "Identifier": 37, "IDENTIFIER": 38, "CSX_TAG": 39, "Property": 40, "PROPERTY": 41, "AlphaNumeric": 42, "NUMBER": 43, "String": 44, "STRING": 45, "STRING_START": 46, "STRING_END": 47, "Regex": 48, "REGEX": 49, "REGEX_START": 50, "Invocation": 51, "REGEX_END": 52, "Literal": 53, "JS": 54, "UNDEFINED": 55, "NULL": 56, "BOOL": 57, "INFINITY": 58, "NAN": 59, "Assignable": 60, "=": 61, "AssignObj": 62, "ObjAssignable": 63, "ObjRestValue": 64, ":": 65, "SimpleObjAssignable": 66, "ThisProperty": 67, "[": 68, "]": 69, "...": 70, "ObjSpreadExpr": 71, "ObjSpreadIdentifier": 72, "Object": 73, "Parenthetical": 74, "Super": 75, "This": 76, "SUPER": 77, "Arguments": 78, "ObjSpreadAccessor": 79, ".": 80, "INDEX_START": 81, "IndexValue": 82, "INDEX_END": 83, "RETURN": 84, "AWAIT": 85, "PARAM_START": 86, "ParamList": 87, "PARAM_END": 88, "FuncGlyph": 89, "->": 90, "=>": 91, "OptComma": 92, ",": 93, "Param": 94, "ParamVar": 95, "Array": 96, "Splat": 97, "SimpleAssignable": 98, "Accessor": 99, "Range": 100, "?.": 101, "::": 102, "?::": 103, "Index": 104, "INDEX_SOAK": 105, "Slice": 106, "{": 107, "AssignList": 108, "}": 109, "CLASS": 110, "EXTENDS": 111, "IMPORT": 112, "ImportDefaultSpecifier": 113, "ImportNamespaceSpecifier": 114, "ImportSpecifierList": 115, "ImportSpecifier": 116, "AS": 117, "DEFAULT": 118, "IMPORT_ALL": 119, "EXPORT": 120, "ExportSpecifierList": 121, "EXPORT_ALL": 122, "ExportSpecifier": 123, "OptFuncExist": 124, "FUNC_EXIST": 125, "CALL_START": 126, "CALL_END": 127, "ArgList": 128, "THIS": 129, "@": 130, "Elisions": 131, "ArgElisionList": 132, "OptElisions": 133, "RangeDots": 134, "..": 135, "Arg": 136, "ArgElision": 137, "Elision": 138, "SimpleArgs": 139, "TRY": 140, "Catch": 141, "FINALLY": 142, "CATCH": 143, "THROW": 144, "(": 145, ")": 146, "WhileLineSource": 147, "WHILE": 148, "WHEN": 149, "UNTIL": 150, "WhileSource": 151, "Loop": 152, "LOOP": 153, "ForBody": 154, "ForLineBody": 155, "FOR": 156, "BY": 157, "ForStart": 158, "ForSource": 159, "ForLineSource": 160, "ForVariables": 161, "OWN": 162, "ForValue": 163, "FORIN": 164, "FOROF": 165, "FORFROM": 166, "SWITCH": 167, "Whens": 168, "ELSE": 169, "When": 170, "LEADING_WHEN": 171, "IfBlock": 172, "IF": 173, "POST_IF": 174, "IfBlockLine": 175, "UNARY": 176, "UNARY_MATH": 177, "-": 178, "+": 179, "--": 180, "++": 181, "?": 182, "MATH": 183, "**": 184, "SHIFT": 185, "COMPARE": 186, "&": 187, "^": 188, "|": 189, "&&": 190, "||": 191, "BIN?": 192, "RELATION": 193, "COMPOUND_ASSIGN": 194, "$accept": 0, "$end": 1 },
            terminals_: { 2: "error", 6: "TERMINATOR", 14: "STATEMENT", 32: "YIELD", 33: "FROM", 35: "INDENT", 36: "OUTDENT", 38: "IDENTIFIER", 39: "CSX_TAG", 41: "PROPERTY", 43: "NUMBER", 45: "STRING", 46: "STRING_START", 47: "STRING_END", 49: "REGEX", 50: "REGEX_START", 52: "REGEX_END", 54: "JS", 55: "UNDEFINED", 56: "NULL", 57: "BOOL", 58: "INFINITY", 59: "NAN", 61: "=", 65: ":", 68: "[", 69: "]", 70: "...", 77: "SUPER", 80: ".", 81: "INDEX_START", 83: "INDEX_END", 84: "RETURN", 85: "AWAIT", 86: "PARAM_START", 88: "PARAM_END", 90: "->", 91: "=>", 93: ",", 101: "?.", 102: "::", 103: "?::", 105: "INDEX_SOAK", 107: "{", 109: "}", 110: "CLASS", 111: "EXTENDS", 112: "IMPORT", 117: "AS", 118: "DEFAULT", 119: "IMPORT_ALL", 120: "EXPORT", 122: "EXPORT_ALL", 125: "FUNC_EXIST", 126: "CALL_START", 127: "CALL_END", 129: "THIS", 130: "@", 135: "..", 140: "TRY", 142: "FINALLY", 143: "CATCH", 144: "THROW", 145: "(", 146: ")", 148: "WHILE", 149: "WHEN", 150: "UNTIL", 153: "LOOP", 156: "FOR", 157: "BY", 162: "OWN", 164: "FORIN", 165: "FOROF", 166: "FORFROM", 167: "SWITCH", 169: "ELSE", 171: "LEADING_WHEN", 173: "IF", 174: "POST_IF", 176: "UNARY", 177: "UNARY_MATH", 178: "-", 179: "+", 180: "--", 181: "++", 182: "?", 183: "MATH", 184: "**", 185: "SHIFT", 186: "COMPARE", 187: "&", 188: "^", 189: "|", 190: "&&", 191: "||", 192: "BIN?", 193: "RELATION", 194: "COMPOUND_ASSIGN" },
            productions_: [0, [3, 0], [3, 1], [4, 1], [4, 3], [4, 2], [5, 1], [5, 1], [5, 1], [5, 1], [10, 1], [10, 1], [9, 1], [9, 1], [9, 1], [9, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [8, 1], [8, 1], [8, 1], [28, 1], [28, 2], [28, 3], [34, 2], [34, 3], [37, 1], [37, 1], [40, 1], [42, 1], [42, 1], [44, 1], [44, 3], [48, 1], [48, 3], [53, 1], [53, 1], [53, 1], [53, 1], [53, 1], [53, 1], [53, 1], [53, 1], [20, 3], [20, 4], [20, 5], [62, 1], [62, 1], [62, 3], [62, 5], [62, 3], [62, 5], [66, 1], [66, 1], [66, 1], [63, 1], [63, 3], [63, 1], [64, 2], [64, 2], [64, 2], [64, 2], [71, 1], [71, 1], [71, 1], [71, 1], [71, 1], [71, 2], [71, 2], [71, 2], [72, 2], [72, 2], [79, 2], [79, 3], [13, 2], [13, 4], [13, 1], [11, 3], [11, 2], [12, 3], [12, 2], [18, 5], [18, 2], [29, 5], [29, 2], [89, 1], [89, 1], [92, 0], [92, 1], [87, 0], [87, 1], [87, 3], [87, 4], [87, 6], [94, 1], [94, 2], [94, 2], [94, 3], [94, 1], [95, 1], [95, 1], [95, 1], [95, 1], [97, 2], [97, 2], [98, 1], [98, 2], [98, 2], [98, 1], [60, 1], [60, 1], [60, 1], [17, 1], [17, 1], [17, 1], [17, 1], [17, 1], [17, 1], [17, 1], [75, 3], [75, 4], [99, 2], [99, 2], [99, 2], [99, 2], [99, 1], [99, 1], [104, 3], [104, 2], [82, 1], [82, 1], [73, 4], [108, 0], [108, 1], [108, 3], [108, 4], [108, 6], [26, 1], [26, 2], [26, 3], [26, 4], [26, 2], [26, 3], [26, 4], [26, 5], [15, 2], [15, 4], [15, 4], [15, 5], [15, 7], [15, 6], [15, 9], [115, 1], [115, 3], [115, 4], [115, 4], [115, 6], [116, 1], [116, 3], [116, 1], [116, 3], [113, 1], [114, 3], [16, 3], [16, 5], [16, 2], [16, 4], [16, 5], [16, 6], [16, 3], [16, 5], [16, 4], [16, 7], [121, 1], [121, 3], [121, 4], [121, 4], [121, 6], [123, 1], [123, 3], [123, 3], [123, 1], [123, 3], [51, 3], [51, 3], [51, 3], [124, 0], [124, 1], [78, 2], [78, 4], [76, 1], [76, 1], [67, 2], [96, 2], [96, 3], [96, 4], [134, 1], [134, 1], [100, 5], [100, 5], [106, 3], [106, 2], [106, 3], [106, 2], [106, 2], [106, 1], [128, 1], [128, 3], [128, 4], [128, 4], [128, 6], [136, 1], [136, 1], [136, 1], [136, 1], [132, 1], [132, 3], [132, 4], [132, 4], [132, 6], [137, 1], [137, 2], [133, 1], [133, 2], [131, 1], [131, 2], [138, 1], [139, 1], [139, 1], [139, 3], [139, 3], [22, 2], [22, 3], [22, 4], [22, 5], [141, 3], [141, 3], [141, 2], [27, 2], [27, 4], [74, 3], [74, 5], [147, 2], [147, 4], [147, 2], [147, 4], [151, 2], [151, 4], [151, 4], [151, 2], [151, 4], [151, 4], [23, 2], [23, 2], [23, 2], [23, 2], [23, 1], [152, 2], [152, 2], [24, 2], [24, 2], [24, 2], [24, 2], [154, 2], [154, 4], [154, 2], [155, 4], [155, 2], [158, 2], [158, 3], [158, 3], [163, 1], [163, 1], [163, 1], [163, 1], [161, 1], [161, 3], [159, 2], [159, 2], [159, 4], [159, 4], [159, 4], [159, 4], [159, 4], [159, 4], [159, 6], [159, 6], [159, 6], [159, 6], [159, 6], [159, 6], [159, 6], [159, 6], [159, 2], [159, 4], [159, 4], [160, 2], [160, 2], [160, 4], [160, 4], [160, 4], [160, 4], [160, 4], [160, 4], [160, 6], [160, 6], [160, 6], [160, 6], [160, 6], [160, 6], [160, 6], [160, 6], [160, 2], [160, 4], [160, 4], [25, 5], [25, 5], [25, 7], [25, 7], [25, 4], [25, 6], [168, 1], [168, 2], [170, 3], [170, 4], [172, 3], [172, 5], [21, 1], [21, 3], [21, 3], [21, 3], [175, 3], [175, 5], [30, 1], [30, 3], [30, 3], [30, 3], [31, 2], [19, 2], [19, 2], [19, 2], [19, 2], [19, 2], [19, 2], [19, 2], [19, 2], [19, 2], [19, 2], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 3], [19, 5], [19, 4]],
            performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) {
                /* this == yyval */
                var $0 = $$.length - 1;
                switch (yystate) {
                    case 1:
                        return this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Block);
                        break;
                    case 2:
                        return this.$ = $$[$0];
                        break;
                    case 3:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(yy.Block.wrap([$$[$0]]));
                        break;
                    case 4:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])($$[$0 - 2].push($$[$0]));
                        break;
                    case 5:
                        this.$ = $$[$0 - 1];
                        break;
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                    case 10:
                    case 11:
                    case 12:
                    case 14:
                    case 15:
                    case 16:
                    case 17:
                    case 18:
                    case 19:
                    case 20:
                    case 21:
                    case 22:
                    case 23:
                    case 24:
                    case 25:
                    case 26:
                    case 27:
                    case 28:
                    case 29:
                    case 30:
                    case 40:
                    case 45:
                    case 47:
                    case 57:
                    case 62:
                    case 63:
                    case 64:
                    case 65:
                    case 67:
                    case 72:
                    case 73:
                    case 74:
                    case 75:
                    case 76:
                    case 97:
                    case 98:
                    case 109:
                    case 110:
                    case 111:
                    case 112:
                    case 118:
                    case 119:
                    case 122:
                    case 127:
                    case 136:
                    case 221:
                    case 222:
                    case 223:
                    case 225:
                    case 237:
                    case 238:
                    case 281:
                    case 282:
                    case 331:
                    case 337:
                    case 343:
                        this.$ = $$[$0];
                        break;
                    case 13:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.StatementLiteral($$[$0]));
                        break;
                    case 31:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Op($$[$0], new yy.Value(new yy.Literal(''))));
                        break;
                    case 32:
                    case 347:
                    case 348:
                    case 349:
                    case 352:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Op($$[$0 - 1], $$[$0]));
                        break;
                    case 33:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Op($$[$0 - 2].concat($$[$0 - 1]), $$[$0]));
                        break;
                    case 34:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Block);
                        break;
                    case 35:
                    case 83:
                    case 137:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])($$[$0 - 1]);
                        break;
                    case 36:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.IdentifierLiteral($$[$0]));
                        break;
                    case 37:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.CSXTag($$[$0]));
                        break;
                    case 38:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.PropertyName($$[$0]));
                        break;
                    case 39:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.NumberLiteral($$[$0]));
                        break;
                    case 41:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.StringLiteral($$[$0]));
                        break;
                    case 42:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.StringWithInterpolations($$[$0 - 1]));
                        break;
                    case 43:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.RegexLiteral($$[$0]));
                        break;
                    case 44:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.RegexWithInterpolations($$[$0 - 1].args));
                        break;
                    case 46:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.PassthroughLiteral($$[$0]));
                        break;
                    case 48:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.UndefinedLiteral($$[$0]));
                        break;
                    case 49:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.NullLiteral($$[$0]));
                        break;
                    case 50:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.BooleanLiteral($$[$0]));
                        break;
                    case 51:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.InfinityLiteral($$[$0]));
                        break;
                    case 52:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.NaNLiteral($$[$0]));
                        break;
                    case 53:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Assign($$[$0 - 2], $$[$0]));
                        break;
                    case 54:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Assign($$[$0 - 3], $$[$0]));
                        break;
                    case 55:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Assign($$[$0 - 4], $$[$0 - 1]));
                        break;
                    case 56:
                    case 115:
                    case 120:
                    case 121:
                    case 123:
                    case 124:
                    case 125:
                    case 126:
                    case 128:
                    case 283:
                    case 284:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Value($$[$0]));
                        break;
                    case 58:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Assign(yy.addDataToNode(yy, _$[$0 - 2])(new yy.Value($$[$0 - 2])), $$[$0], 'object', {
                            operatorToken: yy.addDataToNode(yy, _$[$0 - 1])(new yy.Literal($$[$0 - 1]))
                        }));
                        break;
                    case 59:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Assign(yy.addDataToNode(yy, _$[$0 - 4])(new yy.Value($$[$0 - 4])), $$[$0 - 1], 'object', {
                            operatorToken: yy.addDataToNode(yy, _$[$0 - 3])(new yy.Literal($$[$0 - 3]))
                        }));
                        break;
                    case 60:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Assign(yy.addDataToNode(yy, _$[$0 - 2])(new yy.Value($$[$0 - 2])), $$[$0], null, {
                            operatorToken: yy.addDataToNode(yy, _$[$0 - 1])(new yy.Literal($$[$0 - 1]))
                        }));
                        break;
                    case 61:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Assign(yy.addDataToNode(yy, _$[$0 - 4])(new yy.Value($$[$0 - 4])), $$[$0 - 1], null, {
                            operatorToken: yy.addDataToNode(yy, _$[$0 - 3])(new yy.Literal($$[$0 - 3]))
                        }));
                        break;
                    case 66:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Value(new yy.ComputedPropertyName($$[$0 - 1])));
                        break;
                    case 68:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Splat(new yy.Value($$[$0 - 1])));
                        break;
                    case 69:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Splat(new yy.Value($$[$0])));
                        break;
                    case 70:
                    case 113:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Splat($$[$0 - 1]));
                        break;
                    case 71:
                    case 114:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Splat($$[$0]));
                        break;
                    case 77:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.SuperCall(yy.addDataToNode(yy, _$[$0 - 1])(new yy.Super), $$[$0], false, $$[$0 - 1]));
                        break;
                    case 78:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Call(new yy.Value($$[$0 - 1]), $$[$0]));
                        break;
                    case 79:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Call($$[$0 - 1], $$[$0]));
                        break;
                    case 80:
                    case 81:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])((new yy.Value($$[$0 - 1])).add($$[$0]));
                        break;
                    case 82:
                    case 131:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Access($$[$0]));
                        break;
                    case 84:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Return($$[$0]));
                        break;
                    case 85:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Return(new yy.Value($$[$0 - 1])));
                        break;
                    case 86:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Return);
                        break;
                    case 87:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.YieldReturn($$[$0]));
                        break;
                    case 88:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.YieldReturn);
                        break;
                    case 89:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.AwaitReturn($$[$0]));
                        break;
                    case 90:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.AwaitReturn);
                        break;
                    case 91:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Code($$[$0 - 3], $$[$0], $$[$0 - 1], yy.addDataToNode(yy, _$[$0 - 4])(new yy.Literal($$[$0 - 4]))));
                        break;
                    case 92:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Code([], $$[$0], $$[$0 - 1]));
                        break;
                    case 93:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Code($$[$0 - 3], yy.addDataToNode(yy, _$[$0])(yy.Block.wrap([$$[$0]])), $$[$0 - 1], yy.addDataToNode(yy, _$[$0 - 4])(new yy.Literal($$[$0 - 4]))));
                        break;
                    case 94:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Code([], yy.addDataToNode(yy, _$[$0])(yy.Block.wrap([$$[$0]])), $$[$0 - 1]));
                        break;
                    case 95:
                    case 96:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.FuncGlyph($$[$0]));
                        break;
                    case 99:
                    case 142:
                    case 232:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])([]);
                        break;
                    case 100:
                    case 143:
                    case 162:
                    case 183:
                    case 216:
                    case 230:
                    case 234:
                    case 285:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])([$$[$0]]);
                        break;
                    case 101:
                    case 144:
                    case 163:
                    case 184:
                    case 217:
                    case 226:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])($$[$0 - 2].concat($$[$0]));
                        break;
                    case 102:
                    case 145:
                    case 164:
                    case 185:
                    case 218:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])($$[$0 - 3].concat($$[$0]));
                        break;
                    case 103:
                    case 146:
                    case 166:
                    case 187:
                    case 220:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 5], _$[$0])($$[$0 - 5].concat($$[$0 - 2]));
                        break;
                    case 104:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Param($$[$0]));
                        break;
                    case 105:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Param($$[$0 - 1], null, true));
                        break;
                    case 106:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Param($$[$0], null, true));
                        break;
                    case 107:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Param($$[$0 - 2], $$[$0]));
                        break;
                    case 108:
                    case 224:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Expansion);
                        break;
                    case 116:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])($$[$0 - 1].add($$[$0]));
                        break;
                    case 117:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Value($$[$0 - 1]).add($$[$0]));
                        break;
                    case 129:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Super(yy.addDataToNode(yy, _$[$0])(new yy.Access($$[$0])), [], false, $$[$0 - 2]));
                        break;
                    case 130:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Super(yy.addDataToNode(yy, _$[$0 - 1])(new yy.Index($$[$0 - 1])), [], false, $$[$0 - 3]));
                        break;
                    case 132:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Access($$[$0], 'soak'));
                        break;
                    case 133:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])([yy.addDataToNode(yy, _$[$0 - 1])(new yy.Access(new yy.PropertyName('prototype'))),
                            yy.addDataToNode(yy, _$[$0])(new yy.Access($$[$0]))]);
                        break;
                    case 134:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])([yy.addDataToNode(yy, _$[$0 - 1])(new yy.Access(new yy.PropertyName('prototype'), 'soak')),
                            yy.addDataToNode(yy, _$[$0])(new yy.Access($$[$0]))]);
                        break;
                    case 135:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Access(new yy.PropertyName('prototype')));
                        break;
                    case 138:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(yy.extend($$[$0], {
                            soak: true
                        }));
                        break;
                    case 139:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Index($$[$0]));
                        break;
                    case 140:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Slice($$[$0]));
                        break;
                    case 141:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Obj($$[$0 - 2], $$[$0 - 3].generated));
                        break;
                    case 147:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Class);
                        break;
                    case 148:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Class(null, null, $$[$0]));
                        break;
                    case 149:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Class(null, $$[$0]));
                        break;
                    case 150:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Class(null, $$[$0 - 1], $$[$0]));
                        break;
                    case 151:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Class($$[$0]));
                        break;
                    case 152:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Class($$[$0 - 1], null, $$[$0]));
                        break;
                    case 153:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Class($$[$0 - 2], $$[$0]));
                        break;
                    case 154:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Class($$[$0 - 3], $$[$0 - 1], $$[$0]));
                        break;
                    case 155:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.ImportDeclaration(null, $$[$0]));
                        break;
                    case 156:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.ImportDeclaration(new yy.ImportClause($$[$0 - 2], null), $$[$0]));
                        break;
                    case 157:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.ImportDeclaration(new yy.ImportClause(null, $$[$0 - 2]), $$[$0]));
                        break;
                    case 158:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.ImportDeclaration(new yy.ImportClause(null, new yy.ImportSpecifierList([])), $$[$0]));
                        break;
                    case 159:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 6], _$[$0])(new yy.ImportDeclaration(new yy.ImportClause(null, new yy.ImportSpecifierList($$[$0 - 4])), $$[$0]));
                        break;
                    case 160:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 5], _$[$0])(new yy.ImportDeclaration(new yy.ImportClause($$[$0 - 4], $$[$0 - 2]), $$[$0]));
                        break;
                    case 161:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 8], _$[$0])(new yy.ImportDeclaration(new yy.ImportClause($$[$0 - 7], new yy.ImportSpecifierList($$[$0 - 4])), $$[$0]));
                        break;
                    case 165:
                    case 186:
                    case 199:
                    case 219:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])($$[$0 - 2]);
                        break;
                    case 167:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.ImportSpecifier($$[$0]));
                        break;
                    case 168:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ImportSpecifier($$[$0 - 2], $$[$0]));
                        break;
                    case 169:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.ImportSpecifier(new yy.Literal($$[$0])));
                        break;
                    case 170:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ImportSpecifier(new yy.Literal($$[$0 - 2]), $$[$0]));
                        break;
                    case 171:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.ImportDefaultSpecifier($$[$0]));
                        break;
                    case 172:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ImportNamespaceSpecifier(new yy.Literal($$[$0 - 2]), $$[$0]));
                        break;
                    case 173:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ExportNamedDeclaration(new yy.ExportSpecifierList([])));
                        break;
                    case 174:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.ExportNamedDeclaration(new yy.ExportSpecifierList($$[$0 - 2])));
                        break;
                    case 175:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.ExportNamedDeclaration($$[$0]));
                        break;
                    case 176:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.ExportNamedDeclaration(new yy.Assign($$[$0 - 2], $$[$0], null, {
                            moduleDeclaration: 'export'
                        })));
                        break;
                    case 177:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.ExportNamedDeclaration(new yy.Assign($$[$0 - 3], $$[$0], null, {
                            moduleDeclaration: 'export'
                        })));
                        break;
                    case 178:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 5], _$[$0])(new yy.ExportNamedDeclaration(new yy.Assign($$[$0 - 4], $$[$0 - 1], null, {
                            moduleDeclaration: 'export'
                        })));
                        break;
                    case 179:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ExportDefaultDeclaration($$[$0]));
                        break;
                    case 180:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.ExportDefaultDeclaration(new yy.Value($$[$0 - 1])));
                        break;
                    case 181:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.ExportAllDeclaration(new yy.Literal($$[$0 - 2]), $$[$0]));
                        break;
                    case 182:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 6], _$[$0])(new yy.ExportNamedDeclaration(new yy.ExportSpecifierList($$[$0 - 4]), $$[$0]));
                        break;
                    case 188:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.ExportSpecifier($$[$0]));
                        break;
                    case 189:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ExportSpecifier($$[$0 - 2], $$[$0]));
                        break;
                    case 190:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ExportSpecifier($$[$0 - 2], new yy.Literal($$[$0])));
                        break;
                    case 191:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.ExportSpecifier(new yy.Literal($$[$0])));
                        break;
                    case 192:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.ExportSpecifier(new yy.Literal($$[$0 - 2]), $$[$0]));
                        break;
                    case 193:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.TaggedTemplateCall($$[$0 - 2], $$[$0], $$[$0 - 1]));
                        break;
                    case 194:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Call($$[$0 - 2], $$[$0], $$[$0 - 1]));
                        break;
                    case 195:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.SuperCall(yy.addDataToNode(yy, _$[$0 - 2])(new yy.Super), $$[$0], $$[$0 - 1], $$[$0 - 2]));
                        break;
                    case 196:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(false);
                        break;
                    case 197:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(true);
                        break;
                    case 198:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])([]);
                        break;
                    case 200:
                    case 201:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Value(new yy.ThisLiteral($$[$0])));
                        break;
                    case 202:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Value(yy.addDataToNode(yy, _$[$0 - 1])(new yy.ThisLiteral($$[$0 - 1])), [yy.addDataToNode(yy, _$[$0])(new yy.Access($$[$0]))], 'this'));
                        break;
                    case 203:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Arr([]));
                        break;
                    case 204:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Arr($$[$0 - 1]));
                        break;
                    case 205:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Arr([].concat($$[$0 - 2], $$[$0 - 1])));
                        break;
                    case 206:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])('inclusive');
                        break;
                    case 207:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])('exclusive');
                        break;
                    case 208:
                    case 209:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Range($$[$0 - 3], $$[$0 - 1], $$[$0 - 2]));
                        break;
                    case 210:
                    case 212:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Range($$[$0 - 2], $$[$0], $$[$0 - 1]));
                        break;
                    case 211:
                    case 213:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Range($$[$0 - 1], null, $$[$0]));
                        break;
                    case 214:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Range(null, $$[$0], $$[$0 - 1]));
                        break;
                    case 215:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Range(null, null, $$[$0]));
                        break;
                    case 227:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])($$[$0 - 3].concat($$[$0 - 2], $$[$0]));
                        break;
                    case 228:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])($$[$0 - 2].concat($$[$0 - 1]));
                        break;
                    case 229:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 5], _$[$0])($$[$0 - 5].concat($$[$0 - 4], $$[$0 - 2], $$[$0 - 1]));
                        break;
                    case 231:
                    case 235:
                    case 332:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])($$[$0 - 1].concat($$[$0]));
                        break;
                    case 233:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])([].concat($$[$0]));
                        break;
                    case 236:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])(new yy.Elision);
                        break;
                    case 239:
                    case 240:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])([].concat($$[$0 - 2], $$[$0]));
                        break;
                    case 241:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Try($$[$0]));
                        break;
                    case 242:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Try($$[$0 - 1], $$[$0][0], $$[$0][1]));
                        break;
                    case 243:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Try($$[$0 - 2], null, null, $$[$0]));
                        break;
                    case 244:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Try($$[$0 - 3], $$[$0 - 2][0], $$[$0 - 2][1], $$[$0]));
                        break;
                    case 245:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])([$$[$0 - 1],
                            $$[$0]]);
                        break;
                    case 246:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])([yy.addDataToNode(yy, _$[$0 - 1])(new yy.Value($$[$0 - 1])),
                            $$[$0]]);
                        break;
                    case 247:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])([null,
                            $$[$0]]);
                        break;
                    case 248:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Throw($$[$0]));
                        break;
                    case 249:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Throw(new yy.Value($$[$0 - 1])));
                        break;
                    case 250:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Parens($$[$0 - 1]));
                        break;
                    case 251:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Parens($$[$0 - 2]));
                        break;
                    case 252:
                    case 256:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.While($$[$0]));
                        break;
                    case 253:
                    case 257:
                    case 258:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.While($$[$0 - 2], {
                            guard: $$[$0]
                        }));
                        break;
                    case 254:
                    case 259:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.While($$[$0], {
                            invert: true
                        }));
                        break;
                    case 255:
                    case 260:
                    case 261:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.While($$[$0 - 2], {
                            invert: true,
                            guard: $$[$0]
                        }));
                        break;
                    case 262:
                    case 263:
                    case 271:
                    case 272:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])($$[$0 - 1].addBody($$[$0]));
                        break;
                    case 264:
                    case 265:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])($$[$0].addBody(yy.addDataToNode(yy, _$[$0 - 1])(yy.Block.wrap([$$[$0 - 1]]))));
                        break;
                    case 266:
                        this.$ = yy.addDataToNode(yy, _$[$0], _$[$0])($$[$0]);
                        break;
                    case 267:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.While(yy.addDataToNode(yy, _$[$0 - 1])(new yy.BooleanLiteral('true'))).addBody($$[$0]));
                        break;
                    case 268:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.While(yy.addDataToNode(yy, _$[$0 - 1])(new yy.BooleanLiteral('true'))).addBody(yy.addDataToNode(yy, _$[$0])(yy.Block.wrap([$$[$0]]))));
                        break;
                    case 269:
                    case 270:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])($$[$0].addBody($$[$0 - 1]));
                        break;
                    case 273:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.For([], {
                            source: yy.addDataToNode(yy, _$[$0])(new yy.Value($$[$0]))
                        }));
                        break;
                    case 274:
                    case 276:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.For([], {
                            source: yy.addDataToNode(yy, _$[$0 - 2])(new yy.Value($$[$0 - 2])),
                            step: $$[$0]
                        }));
                        break;
                    case 275:
                    case 277:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])($$[$0 - 1].addSource($$[$0]));
                        break;
                    case 278:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.For([], {
                            name: $$[$0][0],
                            index: $$[$0][1]
                        }));
                        break;
                    case 279:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])((function () {
                            var index, name;
                            [name,
                                index] = $$[$0];
                            return new yy.For([], {
                                name,
                                index,
                                await: true,
                                awaitTag: yy.addDataToNode(yy, _$[$0 - 1])(new yy.Literal($$[$0 - 1]))
                            });
                        }()));
                        break;
                    case 280:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])((function () {
                            var index, name;
                            [name,
                                index] = $$[$0];
                            return new yy.For([], {
                                name,
                                index,
                                own: true,
                                ownTag: yy.addDataToNode(yy, _$[$0 - 1])(new yy.Literal($$[$0 - 1]))
                            });
                        }()));
                        break;
                    case 286:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])([$$[$0 - 2],
                            $$[$0]]);
                        break;
                    case 287:
                    case 306:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])({
                            source: $$[$0]
                        });
                        break;
                    case 288:
                    case 307:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])({
                            source: $$[$0],
                            object: true
                        });
                        break;
                    case 289:
                    case 290:
                    case 308:
                    case 309:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])({
                            source: $$[$0 - 2],
                            guard: $$[$0]
                        });
                        break;
                    case 291:
                    case 292:
                    case 310:
                    case 311:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])({
                            source: $$[$0 - 2],
                            guard: $$[$0],
                            object: true
                        });
                        break;
                    case 293:
                    case 294:
                    case 312:
                    case 313:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])({
                            source: $$[$0 - 2],
                            step: $$[$0]
                        });
                        break;
                    case 295:
                    case 296:
                    case 297:
                    case 298:
                    case 314:
                    case 315:
                    case 316:
                    case 317:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 5], _$[$0])({
                            source: $$[$0 - 4],
                            guard: $$[$0 - 2],
                            step: $$[$0]
                        });
                        break;
                    case 299:
                    case 300:
                    case 301:
                    case 302:
                    case 318:
                    case 319:
                    case 320:
                    case 321:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 5], _$[$0])({
                            source: $$[$0 - 4],
                            step: $$[$0 - 2],
                            guard: $$[$0]
                        });
                        break;
                    case 303:
                    case 322:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])({
                            source: $$[$0],
                            from: true
                        });
                        break;
                    case 304:
                    case 305:
                    case 323:
                    case 324:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])({
                            source: $$[$0 - 2],
                            guard: $$[$0],
                            from: true
                        });
                        break;
                    case 325:
                    case 326:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Switch($$[$0 - 3], $$[$0 - 1]));
                        break;
                    case 327:
                    case 328:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 6], _$[$0])(new yy.Switch($$[$0 - 5], $$[$0 - 3], $$[$0 - 1]));
                        break;
                    case 329:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Switch(null, $$[$0 - 1]));
                        break;
                    case 330:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 5], _$[$0])(new yy.Switch(null, $$[$0 - 3], $$[$0 - 1]));
                        break;
                    case 333:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])([[$$[$0 - 1],
                                $$[$0]]]);
                        break;
                    case 334:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])([[$$[$0 - 2],
                                $$[$0 - 1]]]);
                        break;
                    case 335:
                    case 341:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.If($$[$0 - 1], $$[$0], {
                            type: $$[$0 - 2]
                        }));
                        break;
                    case 336:
                    case 342:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])($$[$0 - 4].addElse(yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.If($$[$0 - 1], $$[$0], {
                            type: $$[$0 - 2]
                        }))));
                        break;
                    case 338:
                    case 344:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])($$[$0 - 2].addElse($$[$0]));
                        break;
                    case 339:
                    case 340:
                    case 345:
                    case 346:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.If($$[$0], yy.addDataToNode(yy, _$[$0 - 2])(yy.Block.wrap([$$[$0 - 2]])), {
                            type: $$[$0 - 1],
                            statement: true
                        }));
                        break;
                    case 350:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Op('-', $$[$0]));
                        break;
                    case 351:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Op('+', $$[$0]));
                        break;
                    case 353:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Op('--', $$[$0]));
                        break;
                    case 354:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Op('++', $$[$0]));
                        break;
                    case 355:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Op('--', $$[$0 - 1], null, true));
                        break;
                    case 356:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Op('++', $$[$0 - 1], null, true));
                        break;
                    case 357:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 1], _$[$0])(new yy.Existence($$[$0 - 1]));
                        break;
                    case 358:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Op('+', $$[$0 - 2], $$[$0]));
                        break;
                    case 359:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Op('-', $$[$0 - 2], $$[$0]));
                        break;
                    case 360:
                    case 361:
                    case 362:
                    case 363:
                    case 364:
                    case 365:
                    case 366:
                    case 367:
                    case 368:
                    case 369:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Op($$[$0 - 1], $$[$0 - 2], $$[$0]));
                        break;
                    case 370:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])((function () {
                            if ($$[$0 - 1].charAt(0) === '!') {
                                return new yy.Op($$[$0 - 1].slice(1), $$[$0 - 2], $$[$0]).invert();
                            }
                            else {
                                return new yy.Op($$[$0 - 1], $$[$0 - 2], $$[$0]);
                            }
                        }()));
                        break;
                    case 371:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 2], _$[$0])(new yy.Assign($$[$0 - 2], $$[$0], $$[$0 - 1]));
                        break;
                    case 372:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 4], _$[$0])(new yy.Assign($$[$0 - 4], $$[$0 - 1], $$[$0 - 3]));
                        break;
                    case 373:
                        this.$ = yy.addDataToNode(yy, _$[$0 - 3], _$[$0])(new yy.Assign($$[$0 - 3], $$[$0], $$[$0 - 2]));
                        break;
                }
            },
            table: [{ 1: [2, 1], 3: 1, 4: 2, 5: 3, 7: 4, 8: 5, 9: 6, 10: 7, 11: 27, 12: 28, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $V1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 1: [3] }, { 1: [2, 2], 6: $VH }, o($VI, [2, 3]), o($VJ, [2, 6], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($VJ, [2, 7]), o($VJ, [2, 8], { 158: 116, 151: 118, 154: 119, 148: $VK, 150: $VL, 156: $VM, 174: $V01 }), o($VJ, [2, 9]), o($V11, [2, 16], { 124: 120, 99: 121, 104: 127, 45: $V21, 46: $V21, 126: $V21, 80: $V31, 81: $V41, 101: $V51, 102: $V61, 103: $V71, 105: $V81, 125: $V91 }), o($V11, [2, 17], { 104: 127, 99: 130, 80: $V31, 81: $V41, 101: $V51, 102: $V61, 103: $V71, 105: $V81 }), o($V11, [2, 18]), o($V11, [2, 19]), o($V11, [2, 20]), o($V11, [2, 21]), o($V11, [2, 22]), o($V11, [2, 23]), o($V11, [2, 24]), o($V11, [2, 25]), o($V11, [2, 26]), o($V11, [2, 27]), o($VJ, [2, 28]), o($VJ, [2, 29]), o($VJ, [2, 30]), o($Va1, [2, 12]), o($Va1, [2, 13]), o($Va1, [2, 14]), o($Va1, [2, 15]), o($VJ, [2, 10]), o($VJ, [2, 11]), o($Vb1, $Vc1, { 61: [1, 131] }), o($Vb1, [2, 123]), o($Vb1, [2, 124]), o($Vb1, [2, 125]), o($Vb1, $Vd1), o($Vb1, [2, 127]), o($Vb1, [2, 128]), o($Ve1, $Vf1, { 87: 132, 94: 133, 95: 134, 37: 136, 67: 137, 96: 138, 73: 139, 38: $V2, 39: $V3, 68: $Vg1, 70: $Vh1, 107: $Vm, 130: $Vi1 }), { 5: 143, 7: 4, 8: 5, 9: 6, 10: 7, 11: 27, 12: 28, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $V1, 34: 142, 35: $Vj1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 145, 8: 146, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 150, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 156, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 157, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 158, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: [1, 159], 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 17: 161, 18: 162, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 163, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 160, 100: 32, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }, { 17: 161, 18: 162, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 163, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 164, 100: 32, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }, o($Vp1, $Vq1, { 180: [1, 165], 181: [1, 166], 194: [1, 167] }), o($V11, [2, 337], { 169: [1, 168] }), { 34: 169, 35: $Vj1 }, { 34: 170, 35: $Vj1 }, { 34: 171, 35: $Vj1 }, o($V11, [2, 266]), { 34: 172, 35: $Vj1 }, { 34: 173, 35: $Vj1 }, { 7: 174, 8: 175, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: [1, 176], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vr1, [2, 147], { 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 44: 88, 89: 152, 17: 161, 18: 162, 60: 163, 34: 177, 98: 179, 35: $Vj1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 86: $Vm1, 90: $Vk, 91: $Vl, 107: $Vm, 111: [1, 178], 129: $Vq, 130: $Vr, 145: $Vu }), { 7: 180, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 35: [1, 181], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o([1, 6, 35, 36, 47, 69, 70, 93, 127, 135, 146, 148, 149, 150, 156, 157, 174, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vs1, { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 89: 152, 9: 154, 7: 182, 14: $V0, 32: $Vk1, 33: $Vt1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 84: [1, 184], 85: $Vl1, 86: $Vm1, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 153: $Vx, 167: $Vz, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), o($VJ, [2, 343], { 169: [1, 185] }), o([1, 6, 36, 47, 69, 70, 93, 127, 135, 146, 148, 149, 150, 156, 157, 174], $Vu1, { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 89: 152, 9: 154, 7: 186, 14: $V0, 32: $Vk1, 35: $Vv1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 153: $Vx, 167: $Vz, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), { 37: 192, 38: $V2, 39: $V3, 44: 188, 45: $V5, 46: $V6, 107: [1, 191], 113: 189, 114: 190, 119: $Vw1 }, { 26: 195, 37: 196, 38: $V2, 39: $V3, 107: [1, 194], 110: $Vn, 118: [1, 197], 122: [1, 198] }, o($Vp1, [2, 120]), o($Vp1, [2, 121]), o($Vb1, [2, 45]), o($Vb1, [2, 46]), o($Vb1, [2, 47]), o($Vb1, [2, 48]), o($Vb1, [2, 49]), o($Vb1, [2, 50]), o($Vb1, [2, 51]), o($Vb1, [2, 52]), { 4: 199, 5: 3, 7: 4, 8: 5, 9: 6, 10: 7, 11: 27, 12: 28, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $V1, 35: [1, 200], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 201, 8: 202, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: $Vx1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 69: $Vy1, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 93: $VA1, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 131: 204, 132: 205, 136: 210, 137: 207, 138: 206, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 80: $VB1, 81: $VC1, 124: 213, 125: $V91, 126: $V21 }, o($Vb1, [2, 200]), o($Vb1, [2, 201], { 40: 216, 41: $VD1 }), o($VE1, [2, 95]), o($VE1, [2, 96]), o($VF1, [2, 115]), o($VF1, [2, 118]), { 7: 218, 8: 219, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 220, 8: 221, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 222, 8: 223, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 225, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 34: 224, 35: $Vj1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 37: 231, 38: $V2, 39: $V3, 67: 232, 68: $Vf, 73: 234, 85: $VG1, 96: 233, 100: 226, 107: $Vm, 130: $Vi1, 161: 227, 162: $VH1, 163: 230 }, { 159: 235, 160: 236, 164: [1, 237], 165: [1, 238], 166: [1, 239] }, o([6, 35, 93, 109], $VI1, { 44: 88, 108: 240, 62: 241, 63: 242, 64: 243, 66: 244, 42: 246, 71: 248, 37: 249, 40: 250, 67: 251, 72: 252, 73: 253, 74: 254, 75: 255, 76: 256, 38: $V2, 39: $V3, 41: $VD1, 43: $V4, 45: $V5, 46: $V6, 68: $VJ1, 70: $VK1, 77: $VL1, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }), o($VM1, [2, 39]), o($VM1, [2, 40]), o($Vb1, [2, 43]), { 17: 161, 18: 162, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 258, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 163, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 259, 100: 32, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }, o($VN1, [2, 36]), o($VN1, [2, 37]), o($VO1, [2, 41]), { 4: 260, 5: 3, 7: 4, 8: 5, 9: 6, 10: 7, 11: 27, 12: 28, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $V1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VI, [2, 5], { 7: 4, 8: 5, 9: 6, 10: 7, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 13: 23, 15: 25, 16: 26, 11: 27, 12: 28, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 89: 37, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 175: 57, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 5: 261, 14: $V0, 32: $V1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 148: $Vv, 150: $Vw, 153: $Vx, 156: $Vy, 167: $Vz, 173: $VA, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), o($V11, [2, 357]), { 7: 262, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 263, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 264, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 265, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 266, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 267, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 268, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 269, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 270, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 271, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 272, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 273, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 274, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 275, 8: 276, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V11, [2, 265]), o($V11, [2, 270]), { 7: 220, 8: 277, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 222, 8: 278, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 37: 231, 38: $V2, 39: $V3, 67: 232, 68: $Vf, 73: 234, 85: $VG1, 96: 233, 100: 279, 107: $Vm, 130: $Vi1, 161: 227, 162: $VH1, 163: 230 }, { 159: 235, 164: [1, 280], 165: [1, 281], 166: [1, 282] }, { 7: 283, 8: 284, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V11, [2, 264]), o($V11, [2, 269]), { 44: 285, 45: $V5, 46: $V6, 78: 286, 126: $VP1 }, o($VF1, [2, 116]), o($VQ1, [2, 197]), { 40: 288, 41: $VD1 }, { 40: 289, 41: $VD1 }, o($VF1, [2, 135], { 40: 290, 41: $VD1 }), { 40: 291, 41: $VD1 }, o($VF1, [2, 136]), { 7: 293, 8: 295, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $VR1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 82: 292, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 106: 294, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 134: 296, 135: $VS1, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 81: $V41, 104: 299, 105: $V81 }, o($VF1, [2, 117]), { 6: [1, 301], 7: 300, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 35: [1, 302], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VT1, $VU1, { 92: 305, 88: [1, 303], 93: $VV1 }), o($VW1, [2, 100]), o($VW1, [2, 104], { 61: [1, 307], 70: [1, 306] }), o($VW1, [2, 108], { 37: 136, 67: 137, 96: 138, 73: 139, 95: 308, 38: $V2, 39: $V3, 68: $Vg1, 107: $Vm, 130: $Vi1 }), o($VX1, [2, 109]), o($VX1, [2, 110]), o($VX1, [2, 111]), o($VX1, [2, 112]), { 40: 216, 41: $VD1 }, { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: $Vx1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 69: $Vy1, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 93: $VA1, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 131: 204, 132: 205, 136: 210, 137: 207, 138: 206, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VY1, [2, 92]), o($VJ, [2, 94]), { 4: 312, 5: 3, 7: 4, 8: 5, 9: 6, 10: 7, 11: 27, 12: 28, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $V1, 36: [1, 311], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VZ1, $V_1, { 151: 111, 154: 112, 158: 116, 182: $VQ }), o($VJ, [2, 347]), { 7: 158, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 148: $VK, 150: $VL, 151: 118, 154: 119, 156: $VM, 158: 116, 174: $V01 }, o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vs1, { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 89: 152, 9: 154, 7: 182, 14: $V0, 32: $Vk1, 33: $Vt1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 153: $Vx, 167: $Vz, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), o($V$1, [2, 349], { 151: 111, 154: 112, 158: 116, 182: $VQ, 184: $VS }), o($Ve1, $Vf1, { 94: 133, 95: 134, 37: 136, 67: 137, 96: 138, 73: 139, 87: 314, 38: $V2, 39: $V3, 68: $Vg1, 70: $Vh1, 107: $Vm, 130: $Vi1 }), { 34: 142, 35: $Vj1 }, { 7: 315, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 148: $VK, 150: $VL, 151: 118, 154: 119, 156: $VM, 158: 116, 174: [1, 316] }, { 7: 317, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V$1, [2, 350], { 151: 111, 154: 112, 158: 116, 182: $VQ, 184: $VS }), o($V$1, [2, 351], { 151: 111, 154: 112, 158: 116, 182: $VQ, 184: $VS }), o($VZ1, [2, 352], { 151: 111, 154: 112, 158: 116, 182: $VQ }), o($VJ, [2, 90], { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 89: 152, 9: 154, 7: 318, 14: $V0, 32: $Vk1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 148: $Vu1, 150: $Vu1, 156: $Vu1, 174: $Vu1, 153: $Vx, 167: $Vz, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), o($V11, [2, 353], { 45: $Vq1, 46: $Vq1, 80: $Vq1, 81: $Vq1, 101: $Vq1, 102: $Vq1, 103: $Vq1, 105: $Vq1, 125: $Vq1, 126: $Vq1 }), o($VQ1, $V21, { 124: 120, 99: 121, 104: 127, 80: $V31, 81: $V41, 101: $V51, 102: $V61, 103: $V71, 105: $V81, 125: $V91 }), { 80: $V31, 81: $V41, 99: 130, 101: $V51, 102: $V61, 103: $V71, 104: 127, 105: $V81 }, o($V02, $Vc1), o($V11, [2, 354], { 45: $Vq1, 46: $Vq1, 80: $Vq1, 81: $Vq1, 101: $Vq1, 102: $Vq1, 103: $Vq1, 105: $Vq1, 125: $Vq1, 126: $Vq1 }), o($V11, [2, 355]), o($V11, [2, 356]), { 6: [1, 321], 7: 319, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 35: [1, 320], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 34: 322, 35: $Vj1, 173: [1, 323] }, o($V11, [2, 241], { 141: 324, 142: [1, 325], 143: [1, 326] }), o($V11, [2, 262]), o($V11, [2, 263]), o($V11, [2, 271]), o($V11, [2, 272]), { 35: [1, 327], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [1, 328] }, { 168: 329, 170: 330, 171: $V12 }, o($V11, [2, 148]), { 7: 332, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vr1, [2, 151], { 34: 333, 35: $Vj1, 45: $Vq1, 46: $Vq1, 80: $Vq1, 81: $Vq1, 101: $Vq1, 102: $Vq1, 103: $Vq1, 105: $Vq1, 125: $Vq1, 126: $Vq1, 111: [1, 334] }), o($V22, [2, 248], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 73: 335, 107: $Vm }, o($V22, [2, 32], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 7: 336, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o([1, 6, 36, 47, 69, 70, 93, 127, 135, 146, 149, 157], [2, 88], { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 89: 152, 9: 154, 7: 337, 14: $V0, 32: $Vk1, 35: $Vv1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 148: $Vu1, 150: $Vu1, 156: $Vu1, 174: $Vu1, 153: $Vx, 167: $Vz, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), { 34: 338, 35: $Vj1, 173: [1, 339] }, o($Va1, $V32, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 73: 340, 107: $Vm }, o($Va1, [2, 155]), { 33: [1, 341], 93: [1, 342] }, { 33: [1, 343] }, { 35: $V42, 37: 348, 38: $V2, 39: $V3, 109: [1, 344], 115: 345, 116: 346, 118: $V52 }, o([33, 93], [2, 171]), { 117: [1, 350] }, { 35: $V62, 37: 355, 38: $V2, 39: $V3, 109: [1, 351], 118: $V72, 121: 352, 123: 353 }, o($Va1, [2, 175]), { 61: [1, 357] }, { 7: 358, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 35: [1, 359], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 33: [1, 360] }, { 6: $VH, 146: [1, 361] }, { 4: 362, 5: 3, 7: 4, 8: 5, 9: 6, 10: 7, 11: 27, 12: 28, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $V1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V82, $V92, { 151: 111, 154: 112, 158: 116, 134: 363, 70: [1, 364], 135: $VS1, 148: $VK, 150: $VL, 156: $VM, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V82, $Va2, { 134: 365, 70: $VR1, 135: $VS1 }), o($Vb2, [2, 203]), { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 69: [1, 366], 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 93: $VA1, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 136: 368, 138: 367, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o([6, 35, 69], $VU1, { 133: 369, 92: 371, 93: $Vc2 }), o($Vd2, [2, 234]), o($Ve2, [2, 225]), { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: $Vx1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 93: $VA1, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 131: 373, 132: 372, 136: 210, 137: 207, 138: 206, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vd2, [2, 236]), o($Ve2, [2, 230]), o($Vf2, [2, 223]), o($Vf2, [2, 224], { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 89: 152, 9: 154, 7: 374, 14: $V0, 32: $Vk1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 148: $Vv, 150: $Vw, 153: $Vx, 156: $Vy, 167: $Vz, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), { 78: 375, 126: $VP1 }, { 40: 376, 41: $VD1 }, { 7: 377, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vg2, [2, 202]), o($Vg2, [2, 38]), { 34: 378, 35: $Vj1, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 34: 379, 35: $Vj1 }, o($Vh2, [2, 256], { 151: 111, 154: 112, 158: 116, 148: $VK, 149: [1, 380], 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 35: [2, 252], 149: [1, 381] }, o($Vh2, [2, 259], { 151: 111, 154: 112, 158: 116, 148: $VK, 149: [1, 382], 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 35: [2, 254], 149: [1, 383] }, o($V11, [2, 267]), o($Vi2, [2, 268], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 35: $Vj2, 157: [1, 384] }, o($Vk2, [2, 278]), { 37: 231, 38: $V2, 39: $V3, 67: 232, 68: $Vg1, 73: 234, 96: 233, 107: $Vm, 130: $Vi1, 161: 385, 163: 230 }, { 37: 231, 38: $V2, 39: $V3, 67: 232, 68: $Vg1, 73: 234, 96: 233, 107: $Vm, 130: $Vi1, 161: 386, 163: 230 }, o($Vk2, [2, 285], { 93: [1, 387] }), o($Vl2, [2, 281]), o($Vl2, [2, 282]), o($Vl2, [2, 283]), o($Vl2, [2, 284]), o($V11, [2, 275]), { 35: [2, 277] }, { 7: 388, 8: 389, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 390, 8: 391, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 392, 8: 393, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vm2, $VU1, { 92: 394, 93: $Vn2 }), o($Vo2, [2, 143]), o($Vo2, [2, 56], { 65: [1, 396] }), o($Vo2, [2, 57]), o($Vp2, [2, 65], { 78: 399, 79: 400, 61: [1, 397], 70: [1, 398], 80: $Vq2, 81: $Vr2, 126: $VP1 }), { 7: 403, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vp2, [2, 67]), { 37: 249, 38: $V2, 39: $V3, 40: 250, 41: $VD1, 66: 404, 67: 251, 71: 405, 72: 252, 73: 253, 74: 254, 75: 255, 76: 256, 77: $VL1, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }, { 70: [1, 406], 78: 407, 79: 408, 80: $Vq2, 81: $Vr2, 126: $VP1 }, o($Vs2, [2, 62]), o($Vs2, [2, 63]), o($Vs2, [2, 64]), o($Vt2, [2, 72]), o($Vt2, [2, 73]), o($Vt2, [2, 74]), o($Vt2, [2, 75]), o($Vt2, [2, 76]), { 78: 409, 80: $VB1, 81: $VC1, 126: $VP1 }, o($V02, $Vd1, { 52: [1, 410] }), o($V02, $Vq1), { 6: $VH, 47: [1, 411] }, o($VI, [2, 4]), o($Vu2, [2, 358], { 151: 111, 154: 112, 158: 116, 182: $VQ, 183: $VR, 184: $VS }), o($Vu2, [2, 359], { 151: 111, 154: 112, 158: 116, 182: $VQ, 183: $VR, 184: $VS }), o($V$1, [2, 360], { 151: 111, 154: 112, 158: 116, 182: $VQ, 184: $VS }), o($V$1, [2, 361], { 151: 111, 154: 112, 158: 116, 182: $VQ, 184: $VS }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 185, 186, 187, 188, 189, 190, 191, 192, 193], [2, 362], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 186, 187, 188, 189, 190, 191, 192], [2, 363], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 193: $V$ }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 187, 188, 189, 190, 191, 192], [2, 364], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 193: $V$ }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 188, 189, 190, 191, 192], [2, 365], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 193: $V$ }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 189, 190, 191, 192], [2, 366], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 193: $V$ }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 190, 191, 192], [2, 367], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 193: $V$ }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 191, 192], [2, 368], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 193: $V$ }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 192], [2, 369], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 193: $V$ }), o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 157, 174, 186, 187, 188, 189, 190, 191, 192, 193], [2, 370], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT }), o($Vi2, $Vv2, { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($VJ, [2, 346]), { 149: [1, 412] }, { 149: [1, 413] }, o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 149, 150, 156, 174, 178, 179, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193], $Vj2, { 157: [1, 414] }), { 7: 415, 8: 416, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 417, 8: 418, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 419, 8: 420, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vi2, $Vw2, { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($VJ, [2, 345]), o($Vx2, [2, 193]), o($Vx2, [2, 194]), { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: $Vy2, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 127: [1, 421], 128: 422, 129: $Vq, 130: $Vr, 136: 423, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VF1, [2, 131]), o($VF1, [2, 132]), o($VF1, [2, 133]), o($VF1, [2, 134]), { 83: [1, 425] }, { 70: $VR1, 83: [2, 139], 134: 426, 135: $VS1, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 83: [2, 140] }, { 70: $VR1, 134: 427, 135: $VS1 }, { 7: 428, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 83: [2, 215], 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vz2, [2, 206]), o($Vz2, $VA2), o($VF1, [2, 138]), o($V22, [2, 53], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 7: 429, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 430, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 89: 431, 90: $Vk, 91: $Vl }, o($VB2, $VC2, { 95: 134, 37: 136, 67: 137, 96: 138, 73: 139, 94: 432, 38: $V2, 39: $V3, 68: $Vg1, 70: $Vh1, 107: $Vm, 130: $Vi1 }), { 6: $VD2, 35: $VE2 }, o($VW1, [2, 105]), { 7: 435, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VW1, [2, 106]), o($Vf2, $V92, { 151: 111, 154: 112, 158: 116, 70: [1, 436], 148: $VK, 150: $VL, 156: $VM, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($Vf2, $Va2), o($VF2, [2, 34]), { 6: $VH, 36: [1, 437] }, { 7: 438, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VT1, $VU1, { 92: 305, 88: [1, 439], 93: $VV1 }), o($VZ1, $V_1, { 151: 111, 154: 112, 158: 116, 182: $VQ }), { 7: 440, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 34: 378, 35: $Vj1, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($VJ, [2, 89], { 151: 111, 154: 112, 158: 116, 148: $V32, 150: $V32, 156: $V32, 174: $V32, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, [2, 371], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 7: 441, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 442, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V11, [2, 338]), { 7: 443, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V11, [2, 242], { 142: [1, 444] }), { 34: 445, 35: $Vj1 }, { 34: 448, 35: $Vj1, 37: 446, 38: $V2, 39: $V3, 73: 447, 107: $Vm }, { 168: 449, 170: 330, 171: $V12 }, { 168: 450, 170: 330, 171: $V12 }, { 36: [1, 451], 169: [1, 452], 170: 453, 171: $V12 }, o($VH2, [2, 331]), { 7: 455, 8: 456, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 139: 454, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VI2, [2, 149], { 151: 111, 154: 112, 158: 116, 34: 457, 35: $Vj1, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V11, [2, 152]), { 7: 458, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 36: [1, 459] }, o($V22, [2, 33], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($VJ, [2, 87], { 151: 111, 154: 112, 158: 116, 148: $V32, 150: $V32, 156: $V32, 174: $V32, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($VJ, [2, 344]), { 7: 461, 8: 460, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 36: [1, 462] }, { 44: 463, 45: $V5, 46: $V6 }, { 107: [1, 465], 114: 464, 119: $Vw1 }, { 44: 466, 45: $V5, 46: $V6 }, { 33: [1, 467] }, o($Vm2, $VU1, { 92: 468, 93: $VJ2 }), o($Vo2, [2, 162]), { 35: $V42, 37: 348, 38: $V2, 39: $V3, 115: 470, 116: 346, 118: $V52 }, o($Vo2, [2, 167], { 117: [1, 471] }), o($Vo2, [2, 169], { 117: [1, 472] }), { 37: 473, 38: $V2, 39: $V3 }, o($Va1, [2, 173]), o($Vm2, $VU1, { 92: 474, 93: $VK2 }), o($Vo2, [2, 183]), { 35: $V62, 37: 355, 38: $V2, 39: $V3, 118: $V72, 121: 476, 123: 353 }, o($Vo2, [2, 188], { 117: [1, 477] }), o($Vo2, [2, 191], { 117: [1, 478] }), { 6: [1, 480], 7: 479, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 35: [1, 481], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VL2, [2, 179], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 73: 482, 107: $Vm }, { 44: 483, 45: $V5, 46: $V6 }, o($Vb1, [2, 250]), { 6: $VH, 36: [1, 484] }, { 7: 485, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o([14, 32, 38, 39, 43, 45, 46, 49, 50, 54, 55, 56, 57, 58, 59, 68, 77, 84, 85, 86, 90, 91, 107, 110, 112, 120, 129, 130, 140, 144, 145, 148, 150, 153, 156, 167, 173, 176, 177, 178, 179, 180, 181], $VA2, { 6: $VM2, 35: $VM2, 69: $VM2, 93: $VM2 }), { 7: 486, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vb2, [2, 204]), o($Vd2, [2, 235]), o($Ve2, [2, 231]), { 6: $VN2, 35: $VO2, 69: [1, 487] }, o($VP2, $VC2, { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 89: 37, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 175: 57, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 9: 148, 138: 206, 136: 210, 97: 211, 7: 309, 8: 310, 137: 490, 131: 491, 14: $V0, 32: $Vk1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 70: $Vz1, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 90: $Vk, 91: $Vl, 93: $VA1, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 148: $Vv, 150: $Vw, 153: $Vx, 156: $Vy, 167: $Vz, 173: $VA, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), o($VP2, [2, 232]), o($VB2, $VU1, { 92: 371, 133: 492, 93: $Vc2 }), { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 93: $VA1, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 136: 368, 138: 367, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vf2, [2, 114], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($Vx2, [2, 195]), o($Vb1, [2, 129]), { 83: [1, 493], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($VQ2, [2, 335]), o($VR2, [2, 341]), { 7: 494, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 495, 8: 496, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 497, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 498, 8: 499, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 500, 8: 501, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vk2, [2, 279]), o($Vk2, [2, 280]), { 37: 231, 38: $V2, 39: $V3, 67: 232, 68: $Vg1, 73: 234, 96: 233, 107: $Vm, 130: $Vi1, 163: 502 }, { 35: $VS2, 148: $VK, 149: [1, 503], 150: $VL, 151: 111, 154: 112, 156: $VM, 157: [1, 504], 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 306], 149: [1, 505], 157: [1, 506] }, { 35: $VT2, 148: $VK, 149: [1, 507], 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 307], 149: [1, 508] }, { 35: $VU2, 148: $VK, 149: [1, 509], 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 322], 149: [1, 510] }, { 6: $VV2, 35: $VW2, 109: [1, 511] }, o($VX2, $VC2, { 44: 88, 63: 242, 64: 243, 66: 244, 42: 246, 71: 248, 37: 249, 40: 250, 67: 251, 72: 252, 73: 253, 74: 254, 75: 255, 76: 256, 62: 514, 38: $V2, 39: $V3, 41: $VD1, 43: $V4, 45: $V5, 46: $V6, 68: $VJ1, 70: $VK1, 77: $VL1, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }), { 7: 515, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 35: [1, 516], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 517, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 35: [1, 518], 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vo2, [2, 68]), o($Vt2, [2, 78]), o($Vt2, [2, 80]), { 40: 519, 41: $VD1 }, { 7: 293, 8: 295, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $VR1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 82: 520, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 106: 294, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 134: 296, 135: $VS1, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 69: [1, 521], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($Vo2, [2, 69], { 78: 399, 79: 400, 80: $Vq2, 81: $Vr2, 126: $VP1 }), o($Vo2, [2, 71], { 78: 407, 79: 408, 80: $Vq2, 81: $Vr2, 126: $VP1 }), o($Vo2, [2, 70]), o($Vt2, [2, 79]), o($Vt2, [2, 81]), o($Vt2, [2, 77]), o($Vb1, [2, 44]), o($VO1, [2, 42]), { 7: 522, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 523, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 524, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o([1, 6, 35, 36, 47, 69, 70, 83, 88, 93, 109, 127, 135, 146, 148, 150, 156, 174], $VS2, { 151: 111, 154: 112, 158: 116, 149: [1, 525], 157: [1, 526], 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 149: [1, 527], 157: [1, 528] }, o($VY2, $VT2, { 151: 111, 154: 112, 158: 116, 149: [1, 529], 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 149: [1, 530] }, o($VY2, $VU2, { 151: 111, 154: 112, 158: 116, 149: [1, 531], 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 149: [1, 532] }, o($Vx2, [2, 198]), o([6, 35, 127], $VU1, { 92: 533, 93: $VZ2 }), o($V_2, [2, 216]), { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: $Vy2, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 128: 535, 129: $Vq, 130: $Vr, 136: 423, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VF1, [2, 137]), { 7: 536, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 83: [2, 211], 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 537, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 83: [2, 213], 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 83: [2, 214], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($V22, [2, 54], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 36: [1, 538], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 5: 540, 7: 4, 8: 5, 9: 6, 10: 7, 11: 27, 12: 28, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $V1, 34: 539, 35: $Vj1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vi, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($VW1, [2, 101]), { 37: 136, 38: $V2, 39: $V3, 67: 137, 68: $Vg1, 70: $Vh1, 73: 139, 94: 541, 95: 134, 96: 138, 107: $Vm, 130: $Vi1 }, o($V$2, $Vf1, { 94: 133, 95: 134, 37: 136, 67: 137, 96: 138, 73: 139, 87: 542, 38: $V2, 39: $V3, 68: $Vg1, 70: $Vh1, 107: $Vm, 130: $Vi1 }), o($VW1, [2, 107], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($Vf2, $VM2), o($VF2, [2, 35]), o($Vi2, $Vv2, { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 89: 543, 90: $Vk, 91: $Vl }, o($Vi2, $Vw2, { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 36: [1, 544], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($V22, [2, 373], { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 34: 545, 35: $Vj1, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 34: 546, 35: $Vj1 }, o($V11, [2, 243]), { 34: 547, 35: $Vj1 }, { 34: 548, 35: $Vj1 }, o($V03, [2, 247]), { 36: [1, 549], 169: [1, 550], 170: 453, 171: $V12 }, { 36: [1, 551], 169: [1, 552], 170: 453, 171: $V12 }, o($V11, [2, 329]), { 34: 553, 35: $Vj1 }, o($VH2, [2, 332]), { 34: 554, 35: $Vj1, 93: [1, 555] }, o($V13, [2, 237], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V13, [2, 238]), o($V11, [2, 150]), o($VI2, [2, 153], { 151: 111, 154: 112, 158: 116, 34: 556, 35: $Vj1, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V11, [2, 249]), { 34: 557, 35: $Vj1 }, { 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($Va1, [2, 85]), o($Va1, [2, 156]), { 33: [1, 558] }, { 35: $V42, 37: 348, 38: $V2, 39: $V3, 115: 559, 116: 346, 118: $V52 }, o($Va1, [2, 157]), { 44: 560, 45: $V5, 46: $V6 }, { 6: $V23, 35: $V33, 109: [1, 561] }, o($VX2, $VC2, { 37: 348, 116: 564, 38: $V2, 39: $V3, 118: $V52 }), o($VB2, $VU1, { 92: 565, 93: $VJ2 }), { 37: 566, 38: $V2, 39: $V3 }, { 37: 567, 38: $V2, 39: $V3 }, { 33: [2, 172] }, { 6: $V43, 35: $V53, 109: [1, 568] }, o($VX2, $VC2, { 37: 355, 123: 571, 38: $V2, 39: $V3, 118: $V72 }), o($VB2, $VU1, { 92: 572, 93: $VK2 }), { 37: 573, 38: $V2, 39: $V3, 118: [1, 574] }, { 37: 575, 38: $V2, 39: $V3 }, o($VL2, [2, 176], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 7: 576, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 577, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 36: [1, 578] }, o($Va1, [2, 181]), { 146: [1, 579] }, { 69: [1, 580], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 69: [1, 581], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($Vb2, [2, 205]), { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 93: $VA1, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 131: 373, 136: 210, 137: 582, 138: 206, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: $Vx1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 93: $VA1, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 131: 373, 132: 583, 136: 210, 137: 207, 138: 206, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Ve2, [2, 226]), o($VP2, [2, 233], { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 89: 37, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 175: 57, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 9: 148, 97: 211, 7: 309, 8: 310, 138: 367, 136: 368, 14: $V0, 32: $Vk1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 70: $Vz1, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 90: $Vk, 91: $Vl, 93: $VA1, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 148: $Vv, 150: $Vw, 153: $Vx, 156: $Vy, 167: $Vz, 173: $VA, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), { 6: $VN2, 35: $VO2, 36: [1, 584] }, o($Vb1, [2, 130]), o($Vi2, [2, 257], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 35: $V63, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 253] }, o($Vi2, [2, 260], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 35: $V73, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 255] }, { 35: $V83, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 276] }, o($Vk2, [2, 286]), { 7: 585, 8: 586, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 587, 8: 588, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 589, 8: 590, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 591, 8: 592, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 593, 8: 594, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 595, 8: 596, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 597, 8: 598, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 599, 8: 600, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vb2, [2, 141]), { 37: 249, 38: $V2, 39: $V3, 40: 250, 41: $VD1, 42: 246, 43: $V4, 44: 88, 45: $V5, 46: $V6, 62: 601, 63: 242, 64: 243, 66: 244, 67: 251, 68: $VJ1, 70: $VK1, 71: 248, 72: 252, 73: 253, 74: 254, 75: 255, 76: 256, 77: $VL1, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }, o($V$2, $VI1, { 44: 88, 62: 241, 63: 242, 64: 243, 66: 244, 42: 246, 71: 248, 37: 249, 40: 250, 67: 251, 72: 252, 73: 253, 74: 254, 75: 255, 76: 256, 108: 602, 38: $V2, 39: $V3, 41: $VD1, 43: $V4, 45: $V5, 46: $V6, 68: $VJ1, 70: $VK1, 77: $VL1, 107: $Vm, 129: $Vq, 130: $Vr, 145: $Vu }), o($Vo2, [2, 144]), o($Vo2, [2, 58], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 7: 603, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vo2, [2, 60], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 7: 604, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($Vt2, [2, 82]), { 83: [1, 605] }, o($Vp2, [2, 66]), o($Vi2, $V63, { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($Vi2, $V73, { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($Vi2, $V83, { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 7: 606, 8: 607, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 608, 8: 609, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 610, 8: 611, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 612, 8: 613, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 614, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 615, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 616, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 617, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 6: $V93, 35: $Va3, 127: [1, 618] }, o([6, 35, 36, 127], $VC2, { 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 13: 23, 15: 25, 16: 26, 60: 29, 53: 30, 74: 31, 100: 32, 51: 33, 76: 34, 75: 35, 89: 37, 98: 45, 172: 46, 151: 48, 147: 49, 152: 50, 154: 51, 155: 52, 175: 57, 96: 61, 73: 62, 42: 63, 48: 65, 37: 78, 67: 79, 158: 85, 44: 88, 9: 148, 97: 211, 7: 309, 8: 310, 136: 621, 14: $V0, 32: $Vk1, 38: $V2, 39: $V3, 43: $V4, 45: $V5, 46: $V6, 49: $V7, 50: $V8, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 68: $Vf, 70: $Vz1, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 90: $Vk, 91: $Vl, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 148: $Vv, 150: $Vw, 153: $Vx, 156: $Vy, 167: $Vz, 173: $VA, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }), o($VB2, $VU1, { 92: 622, 93: $VZ2 }), { 83: [2, 210], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 83: [2, 212], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($V11, [2, 55]), o($VY1, [2, 91]), o($VJ, [2, 93]), o($VW1, [2, 102]), o($VB2, $VU1, { 92: 623, 93: $VV1 }), { 34: 539, 35: $Vj1 }, o($V11, [2, 372]), o($VQ2, [2, 336]), o($V11, [2, 244]), o($V03, [2, 245]), o($V03, [2, 246]), o($V11, [2, 325]), { 34: 624, 35: $Vj1 }, o($V11, [2, 326]), { 34: 625, 35: $Vj1 }, { 36: [1, 626] }, o($VH2, [2, 333], { 6: [1, 627] }), { 7: 628, 8: 629, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V11, [2, 154]), o($VR2, [2, 342]), { 44: 630, 45: $V5, 46: $V6 }, o($Vm2, $VU1, { 92: 631, 93: $VJ2 }), o($Va1, [2, 158]), { 33: [1, 632] }, { 37: 348, 38: $V2, 39: $V3, 116: 633, 118: $V52 }, { 35: $V42, 37: 348, 38: $V2, 39: $V3, 115: 634, 116: 346, 118: $V52 }, o($Vo2, [2, 163]), { 6: $V23, 35: $V33, 36: [1, 635] }, o($Vo2, [2, 168]), o($Vo2, [2, 170]), o($Va1, [2, 174], { 33: [1, 636] }), { 37: 355, 38: $V2, 39: $V3, 118: $V72, 123: 637 }, { 35: $V62, 37: 355, 38: $V2, 39: $V3, 118: $V72, 121: 638, 123: 353 }, o($Vo2, [2, 184]), { 6: $V43, 35: $V53, 36: [1, 639] }, o($Vo2, [2, 189]), o($Vo2, [2, 190]), o($Vo2, [2, 192]), o($VL2, [2, 177], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 36: [1, 640], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($Va1, [2, 180]), o($Vb1, [2, 251]), o($Vb1, [2, 208]), o($Vb1, [2, 209]), o($Ve2, [2, 227]), o($VB2, $VU1, { 92: 371, 133: 641, 93: $Vc2 }), o($Ve2, [2, 228]), { 35: $Vb3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 157: [1, 642], 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 308], 157: [1, 643] }, { 35: $Vc3, 148: $VK, 149: [1, 644], 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 312], 149: [1, 645] }, { 35: $Vd3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 157: [1, 646], 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 309], 157: [1, 647] }, { 35: $Ve3, 148: $VK, 149: [1, 648], 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 313], 149: [1, 649] }, { 35: $Vf3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 310] }, { 35: $Vg3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 311] }, { 35: $Vh3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 323] }, { 35: $Vi3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 324] }, o($Vo2, [2, 145]), o($VB2, $VU1, { 92: 650, 93: $Vn2 }), { 36: [1, 651], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 36: [1, 652], 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VG2, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, o($Vt2, [2, 83]), o($Vj3, $Vb3, { 151: 111, 154: 112, 158: 116, 157: [1, 653], 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 157: [1, 654] }, o($VY2, $Vc3, { 151: 111, 154: 112, 158: 116, 149: [1, 655], 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 149: [1, 656] }, o($Vj3, $Vd3, { 151: 111, 154: 112, 158: 116, 157: [1, 657], 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 157: [1, 658] }, o($VY2, $Ve3, { 151: 111, 154: 112, 158: 116, 149: [1, 659], 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 149: [1, 660] }, o($V22, $Vf3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vg3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vh3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vi3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($Vx2, [2, 199]), { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 136: 661, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 309, 8: 310, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 35: $Vy2, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 70: $Vz1, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 97: 211, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 128: 662, 129: $Vq, 130: $Vr, 136: 423, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V_2, [2, 217]), { 6: $V93, 35: $Va3, 36: [1, 663] }, { 6: $VD2, 35: $VE2, 36: [1, 664] }, { 36: [1, 665] }, { 36: [1, 666] }, o($V11, [2, 330]), o($VH2, [2, 334]), o($V13, [2, 239], { 151: 111, 154: 112, 158: 116, 148: $VK, 150: $VL, 156: $VM, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V13, [2, 240]), o($Va1, [2, 160]), { 6: $V23, 35: $V33, 109: [1, 667] }, { 44: 668, 45: $V5, 46: $V6 }, o($Vo2, [2, 164]), o($VB2, $VU1, { 92: 669, 93: $VJ2 }), o($Vo2, [2, 165]), { 44: 670, 45: $V5, 46: $V6 }, o($Vo2, [2, 185]), o($VB2, $VU1, { 92: 671, 93: $VK2 }), o($Vo2, [2, 186]), o($Va1, [2, 178]), { 6: $VN2, 35: $VO2, 36: [1, 672] }, { 7: 673, 8: 674, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 675, 8: 676, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 677, 8: 678, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 679, 8: 680, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 681, 8: 682, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 683, 8: 684, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 685, 8: 686, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 687, 8: 688, 9: 148, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 29: 20, 30: 21, 31: 22, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vj, 89: 37, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $VA, 175: 57, 176: $VB, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 6: $VV2, 35: $VW2, 36: [1, 689] }, o($Vo2, [2, 59]), o($Vo2, [2, 61]), { 7: 690, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 691, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 692, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 693, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 694, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 695, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 696, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, { 7: 697, 9: 154, 13: 23, 14: $V0, 15: 25, 16: 26, 17: 8, 18: 9, 19: 10, 20: 11, 21: 12, 22: 13, 23: 14, 24: 15, 25: 16, 26: 17, 27: 18, 28: 19, 32: $Vk1, 37: 78, 38: $V2, 39: $V3, 42: 63, 43: $V4, 44: 88, 45: $V5, 46: $V6, 48: 65, 49: $V7, 50: $V8, 51: 33, 53: 30, 54: $V9, 55: $Va, 56: $Vb, 57: $Vc, 58: $Vd, 59: $Ve, 60: 29, 67: 79, 68: $Vf, 73: 62, 74: 31, 75: 35, 76: 34, 77: $Vg, 84: $Vh, 85: $Vl1, 86: $Vm1, 89: 152, 90: $Vk, 91: $Vl, 96: 61, 98: 45, 100: 32, 107: $Vm, 110: $Vn, 112: $Vo, 120: $Vp, 129: $Vq, 130: $Vr, 140: $Vs, 144: $Vt, 145: $Vu, 147: 49, 148: $Vv, 150: $Vw, 151: 48, 152: 50, 153: $Vx, 154: 51, 155: 52, 156: $Vy, 158: 85, 167: $Vz, 172: 46, 173: $Vn1, 176: $Vo1, 177: $VC, 178: $VD, 179: $VE, 180: $VF, 181: $VG }, o($V_2, [2, 218]), o($VB2, $VU1, { 92: 698, 93: $VZ2 }), o($V_2, [2, 219]), o($VW1, [2, 103]), o($V11, [2, 327]), o($V11, [2, 328]), { 33: [1, 699] }, o($Va1, [2, 159]), { 6: $V23, 35: $V33, 36: [1, 700] }, o($Va1, [2, 182]), { 6: $V43, 35: $V53, 36: [1, 701] }, o($Ve2, [2, 229]), { 35: $Vk3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 314] }, { 35: $Vl3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 316] }, { 35: $Vm3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 318] }, { 35: $Vn3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 320] }, { 35: $Vo3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 315] }, { 35: $Vp3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 317] }, { 35: $Vq3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 319] }, { 35: $Vr3, 148: $VK, 150: $VL, 151: 111, 154: 112, 156: $VM, 158: 116, 174: $VN, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }, { 35: [2, 321] }, o($Vo2, [2, 146]), o($V22, $Vk3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vl3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vm3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vn3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vo3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vp3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vq3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), o($V22, $Vr3, { 151: 111, 154: 112, 158: 116, 178: $VO, 179: $VP, 182: $VQ, 183: $VR, 184: $VS, 185: $VT, 186: $VU, 187: $VV, 188: $VW, 189: $VX, 190: $VY, 191: $VZ, 192: $V_, 193: $V$ }), { 6: $V93, 35: $Va3, 36: [1, 702] }, { 44: 703, 45: $V5, 46: $V6 }, o($Vo2, [2, 166]), o($Vo2, [2, 187]), o($V_2, [2, 220]), o($Va1, [2, 161])],
            defaultActions: { 236: [2, 277], 294: [2, 140], 473: [2, 172], 496: [2, 253], 499: [2, 255], 501: [2, 276], 594: [2, 310], 596: [2, 311], 598: [2, 323], 600: [2, 324], 674: [2, 314], 676: [2, 316], 678: [2, 318], 680: [2, 320], 682: [2, 315], 684: [2, 317], 686: [2, 319], 688: [2, 321] },
            parseError: function parseError(str, hash) {
                if (hash.recoverable) {
                    this.trace(str);
                }
                else {
                    var error = new Error(str);
                    error.hash = hash;
                    throw error;
                }
            },
            parse: function parse(input) {
                var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
                var args = lstack.slice.call(arguments, 1);
                var lexer = Object.create(this.lexer);
                var sharedState = { yy: {} };
                for (var k in this.yy) {
                    if (Object.prototype.hasOwnProperty.call(this.yy, k)) {
                        sharedState.yy[k] = this.yy[k];
                    }
                }
                lexer.setInput(input, sharedState.yy);
                sharedState.yy.lexer = lexer;
                sharedState.yy.parser = this;
                if (typeof lexer.yylloc == 'undefined') {
                    lexer.yylloc = {};
                }
                var yyloc = lexer.yylloc;
                lstack.push(yyloc);
                var ranges = lexer.options && lexer.options.ranges;
                if (typeof sharedState.yy.parseError === 'function') {
                    this.parseError = sharedState.yy.parseError;
                }
                else {
                    this.parseError = Object.getPrototypeOf(this).parseError;
                }
                function popStack(n) {
                    stack.length = stack.length - 2 * n;
                    vstack.length = vstack.length - n;
                    lstack.length = lstack.length - n;
                }
                _token_stack: var lex = function () {
                    var token;
                    token = lexer.lex() || EOF;
                    if (typeof token !== 'number') {
                        token = self.symbols_[token] || token;
                    }
                    return token;
                };
                var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
                while (true) {
                    state = stack[stack.length - 1];
                    if (this.defaultActions[state]) {
                        action = this.defaultActions[state];
                    }
                    else {
                        if (symbol === null || typeof symbol == 'undefined') {
                            symbol = lex();
                        }
                        action = table[state] && table[state][symbol];
                    }
                    if (typeof action === 'undefined' || !action.length || !action[0]) {
                        var errStr = '';
                        expected = [];
                        for (p in table[state]) {
                            if (this.terminals_[p] && p > TERROR) {
                                expected.push('\'' + this.terminals_[p] + '\'');
                            }
                        }
                        if (lexer.showPosition) {
                            errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\'';
                        }
                        else {
                            errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\'');
                        }
                        this.parseError(errStr, {
                            text: lexer.match,
                            token: this.terminals_[symbol] || symbol,
                            line: lexer.yylineno,
                            loc: yyloc,
                            expected: expected
                        });
                    }
                    if (action[0] instanceof Array && action.length > 1) {
                        throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol);
                    }
                    switch (action[0]) {
                        case 1:
                            stack.push(symbol);
                            vstack.push(lexer.yytext);
                            lstack.push(lexer.yylloc);
                            stack.push(action[1]);
                            symbol = null;
                            if (!preErrorSymbol) {
                                yyleng = lexer.yyleng;
                                yytext = lexer.yytext;
                                yylineno = lexer.yylineno;
                                yyloc = lexer.yylloc;
                                if (recovering > 0) {
                                    recovering--;
                                }
                            }
                            else {
                                symbol = preErrorSymbol;
                                preErrorSymbol = null;
                            }
                            break;
                        case 2:
                            len = this.productions_[action[1]][1];
                            yyval.$ = vstack[vstack.length - len];
                            yyval._$ = {
                                first_line: lstack[lstack.length - (len || 1)].first_line,
                                last_line: lstack[lstack.length - 1].last_line,
                                first_column: lstack[lstack.length - (len || 1)].first_column,
                                last_column: lstack[lstack.length - 1].last_column
                            };
                            if (ranges) {
                                yyval._$.range = [
                                    lstack[lstack.length - (len || 1)].range[0],
                                    lstack[lstack.length - 1].range[1]
                                ];
                            }
                            r = this.performAction.apply(yyval, [
                                yytext,
                                yyleng,
                                yylineno,
                                sharedState.yy,
                                action[1],
                                vstack,
                                lstack
                            ].concat(args));
                            if (typeof r !== 'undefined') {
                                return r;
                            }
                            if (len) {
                                stack = stack.slice(0, -1 * len * 2);
                                vstack = vstack.slice(0, -1 * len);
                                lstack = lstack.slice(0, -1 * len);
                            }
                            stack.push(this.productions_[action[1]][0]);
                            vstack.push(yyval.$);
                            lstack.push(yyval._$);
                            newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
                            stack.push(newState);
                            break;
                        case 3:
                            return true;
                    }
                }
                return true;
            } };
        function Parser() {
            this.yy = {};
        }
        Parser.prototype = parser;
        parser.Parser = Parser;
        return new Parser;
    })();
    if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
        exports.parser = parser;
        exports.Parser = parser.Parser;
        exports.parse = function () { return parser.parse.apply(parser, arguments); };
        exports.main = function () { };
        if (typeof module !== 'undefined' && require.main === module) {
            exports.main(process.argv.slice(1));
        }
    }
}
,
/* coffeescript/lib/coffeescript/register */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        var CoffeeScript, Module, binary, child_process, ext, findExtension, fork, getRootModule, helpers, i, len, loadFile, path, ref;
        CoffeeScript = require(77) /* ./ */;
        child_process = require('child_process');
        helpers = require(76) /* ./helpers */;
        path = require('path');
        // Load and run a CoffeeScript file for Node, stripping any `BOM`s.
        loadFile = function (module, filename) {
            var answer, options;
            options = module.options || getRootModule(module).options;
            answer = CoffeeScript._compileFile(filename, options);
            return module._compile(answer, filename);
        };
        // If the installed version of Node supports `require.extensions`, register
        // CoffeeScript as an extension.
        if (require.extensions) {
            ref = CoffeeScript.FILE_EXTENSIONS;
            for (i = 0, len = ref.length; i < len; i++) {
                ext = ref[i];
                require.extensions[ext] = loadFile;
            }
            // Patch Node's module loader to be able to handle multi-dot extensions.
            // This is a horrible thing that should not be required.
            Module = require('module');
            findExtension = function (filename) {
                var curExtension, extensions;
                extensions = path.basename(filename).split('.');
                if (extensions[0] === '') {
                    // Remove the initial dot from dotfiles.
                    extensions.shift();
                }
                // Start with the longest possible extension and work our way shortwards.
                while (extensions.shift()) {
                    curExtension = '.' + extensions.join('.');
                    if (Module._extensions[curExtension]) {
                        return curExtension;
                    }
                }
                return '.js';
            };
            Module.prototype.load = function (filename) {
                var extension;
                this.filename = filename;
                this.paths = Module._nodeModulePaths(path.dirname(filename));
                extension = findExtension(filename);
                Module._extensions[extension](this, filename);
                return this.loaded = true;
            };
        }
        // If we're on Node, patch `child_process.fork` so that Coffee scripts are able
        // to fork both CoffeeScript files, and JavaScript files, directly.
        if (child_process) {
            ({ fork } = child_process);
            binary = require.resolve('../../bin/coffee');
            child_process.fork = function (path, args, options) {
                if (helpers.isCoffee(path)) {
                    if (!Array.isArray(args)) {
                        options = args || {};
                        args = [];
                    }
                    args = [path].concat(args);
                    path = binary;
                }
                return fork(path, args, options);
            };
        }
        // Utility function to find the `options` object attached to the topmost module.
        getRootModule = function (module) {
            if (module.parent) {
                return getRootModule(module.parent);
            }
            else {
                return module;
            }
        };
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/rewriter */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // The CoffeeScript language has a good deal of optional syntax, implicit syntax,
        // and shorthand syntax. This can greatly complicate a grammar and bloat
        // the resulting parse table. Instead of making the parser handle it all, we take
        // a series of passes over the token stream, using this **Rewriter** to convert
        // shorthand into the unambiguous long form, add implicit indentation and
        // parentheses, and generally clean things up.
        var BALANCED_PAIRS, CALL_CLOSERS, CONTROL_IN_IMPLICIT, DISCARDED, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, Rewriter, SINGLE_CLOSERS, SINGLE_LINERS, generate, k, left, len, moveComments, right, throwSyntaxError, indexOf = [].indexOf;
        ({ throwSyntaxError } = require(76) /* ./helpers */);
        // Move attached comments from one token to another.
        moveComments = function (fromToken, toToken) {
            var comment, k, len, ref, unshiftedComments;
            if (!fromToken.comments) {
                return;
            }
            if (toToken.comments && toToken.comments.length !== 0) {
                unshiftedComments = [];
                ref = fromToken.comments;
                for (k = 0, len = ref.length; k < len; k++) {
                    comment = ref[k];
                    if (comment.unshift) {
                        unshiftedComments.push(comment);
                    }
                    else {
                        toToken.comments.push(comment);
                    }
                }
                toToken.comments = unshiftedComments.concat(toToken.comments);
            }
            else {
                toToken.comments = fromToken.comments;
            }
            return delete fromToken.comments;
        };
        // Create a generated token: one that exists due to a use of implicit syntax.
        // Optionally have this new token take the attached comments from another token.
        generate = function (tag, value, origin, commentsToken) {
            var token;
            token = [tag, value];
            token.generated = true;
            if (origin) {
                token.origin = origin;
            }
            if (commentsToken) {
                moveComments(commentsToken, token);
            }
            return token;
        };
        // The **Rewriter** class is used by the [Lexer](lexer.html), directly against
        // its internal array of tokens.
        exports.Rewriter = Rewriter = (function () {
            class Rewriter {
                // Rewrite the token stream in multiple passes, one logical filter at
                // a time. This could certainly be changed into a single pass through the
                // stream, with a big ol’ efficient switch, but it’s much nicer to work with
                // like this. The order of these passes matters—indentation must be
                // corrected before implicit parentheses can be wrapped around blocks of code.
                rewrite(tokens1) {
                    var ref, ref1, t;
                    this.tokens = tokens1;
                    // Set environment variable `DEBUG_TOKEN_STREAM` to `true` to output token
                    // debugging info. Also set `DEBUG_REWRITTEN_TOKEN_STREAM` to `true` to
                    // output the token stream after it has been rewritten by this file.
                    if (typeof process !== "undefined" && process !== null ? (ref = process.env) != null ? ref.DEBUG_TOKEN_STREAM : void 0 : void 0) {
                        if (process.env.DEBUG_REWRITTEN_TOKEN_STREAM) {
                            console.log('Initial token stream:');
                        }
                        console.log(((function () {
                            var k, len, ref1, results;
                            ref1 = this.tokens;
                            results = [];
                            for (k = 0, len = ref1.length; k < len; k++) {
                                t = ref1[k];
                                results.push(t[0] + '/' + t[1] + (t.comments ? '*' : ''));
                            }
                            return results;
                        }).call(this)).join(' '));
                    }
                    this.removeLeadingNewlines();
                    this.closeOpenCalls();
                    this.closeOpenIndexes();
                    this.normalizeLines();
                    this.tagPostfixConditionals();
                    this.addImplicitBracesAndParens();
                    this.addParensToChainedDoIife();
                    this.rescueStowawayComments();
                    this.addLocationDataToGeneratedTokens();
                    this.enforceValidCSXAttributes();
                    this.fixOutdentLocationData();
                    if (typeof process !== "undefined" && process !== null ? (ref1 = process.env) != null ? ref1.DEBUG_REWRITTEN_TOKEN_STREAM : void 0 : void 0) {
                        if (process.env.DEBUG_TOKEN_STREAM) {
                            console.log('Rewritten token stream:');
                        }
                        console.log(((function () {
                            var k, len, ref2, results;
                            ref2 = this.tokens;
                            results = [];
                            for (k = 0, len = ref2.length; k < len; k++) {
                                t = ref2[k];
                                results.push(t[0] + '/' + t[1] + (t.comments ? '*' : ''));
                            }
                            return results;
                        }).call(this)).join(' '));
                    }
                    return this.tokens;
                }
                // Rewrite the token stream, looking one token ahead and behind.
                // Allow the return value of the block to tell us how many tokens to move
                // forwards (or backwards) in the stream, to make sure we don’t miss anything
                // as tokens are inserted and removed, and the stream changes length under
                // our feet.
                scanTokens(block) {
                    var i, token, tokens;
                    ({ tokens } = this);
                    i = 0;
                    while (token = tokens[i]) {
                        i += block.call(this, token, i, tokens);
                    }
                    return true;
                }
                detectEnd(i, condition, action, opts = {}) {
                    var levels, ref, ref1, token, tokens;
                    ({ tokens } = this);
                    levels = 0;
                    while (token = tokens[i]) {
                        if (levels === 0 && condition.call(this, token, i)) {
                            return action.call(this, token, i);
                        }
                        if (ref = token[0], indexOf.call(EXPRESSION_START, ref) >= 0) {
                            levels += 1;
                        }
                        else if (ref1 = token[0], indexOf.call(EXPRESSION_END, ref1) >= 0) {
                            levels -= 1;
                        }
                        if (levels < 0) {
                            if (opts.returnOnNegativeLevel) {
                                return;
                            }
                            return action.call(this, token, i);
                        }
                        i += 1;
                    }
                    return i - 1;
                }
                // Leading newlines would introduce an ambiguity in the grammar, so we
                // dispatch them here.
                removeLeadingNewlines() {
                    var i, k, l, leadingNewlineToken, len, len1, ref, ref1, tag;
                    ref = this.tokens;
                    for (i = k = 0, len = ref.length; k < len; i = ++k) {
                        [tag] = ref[i];
                        if (tag !== 'TERMINATOR') {
                            // Find the index of the first non-`TERMINATOR` token.
                            break;
                        }
                    }
                    if (i === 0) {
                        return;
                    }
                    ref1 = this.tokens.slice(0, i);
                    // If there are any comments attached to the tokens we’re about to discard,
                    // shift them forward to what will become the new first token.
                    for (l = 0, len1 = ref1.length; l < len1; l++) {
                        leadingNewlineToken = ref1[l];
                        moveComments(leadingNewlineToken, this.tokens[i]);
                    }
                    // Discard all the leading newline tokens.
                    return this.tokens.splice(0, i);
                }
                // The lexer has tagged the opening parenthesis of a method call. Match it with
                // its paired close.
                closeOpenCalls() {
                    var action, condition;
                    condition = function (token, i) {
                        var ref;
                        return (ref = token[0]) === ')' || ref === 'CALL_END';
                    };
                    action = function (token, i) {
                        return token[0] = 'CALL_END';
                    };
                    return this.scanTokens(function (token, i) {
                        if (token[0] === 'CALL_START') {
                            this.detectEnd(i + 1, condition, action);
                        }
                        return 1;
                    });
                }
                // The lexer has tagged the opening bracket of an indexing operation call.
                // Match it with its paired close.
                closeOpenIndexes() {
                    var action, condition;
                    condition = function (token, i) {
                        var ref;
                        return (ref = token[0]) === ']' || ref === 'INDEX_END';
                    };
                    action = function (token, i) {
                        return token[0] = 'INDEX_END';
                    };
                    return this.scanTokens(function (token, i) {
                        if (token[0] === 'INDEX_START') {
                            this.detectEnd(i + 1, condition, action);
                        }
                        return 1;
                    });
                }
                // Match tags in token stream starting at `i` with `pattern`.
                // `pattern` may consist of strings (equality), an array of strings (one of)
                // or null (wildcard). Returns the index of the match or -1 if no match.
                indexOfTag(i, ...pattern) {
                    var fuzz, j, k, ref, ref1;
                    fuzz = 0;
                    for (j = k = 0, ref = pattern.length; (0 <= ref ? k < ref : k > ref); j = 0 <= ref ? ++k : --k) {
                        if (pattern[j] == null) {
                            continue;
                        }
                        if (typeof pattern[j] === 'string') {
                            pattern[j] = [pattern[j]];
                        }
                        if (ref1 = this.tag(i + j + fuzz), indexOf.call(pattern[j], ref1) < 0) {
                            return -1;
                        }
                    }
                    return i + j + fuzz - 1;
                }
                // Returns `yes` if standing in front of something looking like
                // `@<x>:`, `<x>:` or `<EXPRESSION_START><x>...<EXPRESSION_END>:`.
                looksObjectish(j) {
                    var end, index;
                    if (this.indexOfTag(j, '@', null, ':') !== -1 || this.indexOfTag(j, null, ':') !== -1) {
                        return true;
                    }
                    index = this.indexOfTag(j, EXPRESSION_START);
                    if (index !== -1) {
                        end = null;
                        this.detectEnd(index + 1, (function (token) {
                            var ref;
                            return ref = token[0], indexOf.call(EXPRESSION_END, ref) >= 0;
                        }), (function (token, i) {
                            return end = i;
                        }));
                        if (this.tag(end + 1) === ':') {
                            return true;
                        }
                    }
                    return false;
                }
                // Returns `yes` if current line of tokens contain an element of tags on same
                // expression level. Stop searching at `LINEBREAKS` or explicit start of
                // containing balanced expression.
                findTagsBackwards(i, tags) {
                    var backStack, ref, ref1, ref2, ref3, ref4, ref5;
                    backStack = [];
                    while (i >= 0 && (backStack.length || (ref2 = this.tag(i), indexOf.call(tags, ref2) < 0) && ((ref3 = this.tag(i), indexOf.call(EXPRESSION_START, ref3) < 0) || this.tokens[i].generated) && (ref4 = this.tag(i), indexOf.call(LINEBREAKS, ref4) < 0))) {
                        if (ref = this.tag(i), indexOf.call(EXPRESSION_END, ref) >= 0) {
                            backStack.push(this.tag(i));
                        }
                        if ((ref1 = this.tag(i), indexOf.call(EXPRESSION_START, ref1) >= 0) && backStack.length) {
                            backStack.pop();
                        }
                        i -= 1;
                    }
                    return ref5 = this.tag(i), indexOf.call(tags, ref5) >= 0;
                }
                // Look for signs of implicit calls and objects in the token stream and
                // add them.
                addImplicitBracesAndParens() {
                    var stack, start;
                    // Track current balancing depth (both implicit and explicit) on stack.
                    stack = [];
                    start = null;
                    return this.scanTokens(function (token, i, tokens) {
                        var endImplicitCall, endImplicitObject, forward, implicitObjectContinues, inControlFlow, inImplicit, inImplicitCall, inImplicitControl, inImplicitObject, isImplicit, isImplicitCall, isImplicitObject, k, newLine, nextTag, nextToken, offset, prevTag, prevToken, ref, ref1, ref2, s, sameLine, stackIdx, stackItem, stackTag, stackTop, startIdx, startImplicitCall, startImplicitObject, startsLine, tag;
                        [tag] = token;
                        [prevTag] = prevToken = i > 0 ? tokens[i - 1] : [];
                        [nextTag] = nextToken = i < tokens.length - 1 ? tokens[i + 1] : [];
                        stackTop = function () {
                            return stack[stack.length - 1];
                        };
                        startIdx = i;
                        // Helper function, used for keeping track of the number of tokens consumed
                        // and spliced, when returning for getting a new token.
                        forward = function (n) {
                            return i - startIdx + n;
                        };
                        // Helper functions
                        isImplicit = function (stackItem) {
                            var ref;
                            return stackItem != null ? (ref = stackItem[2]) != null ? ref.ours : void 0 : void 0;
                        };
                        isImplicitObject = function (stackItem) {
                            return isImplicit(stackItem) && (stackItem != null ? stackItem[0] : void 0) === '{';
                        };
                        isImplicitCall = function (stackItem) {
                            return isImplicit(stackItem) && (stackItem != null ? stackItem[0] : void 0) === '(';
                        };
                        inImplicit = function () {
                            return isImplicit(stackTop());
                        };
                        inImplicitCall = function () {
                            return isImplicitCall(stackTop());
                        };
                        inImplicitObject = function () {
                            return isImplicitObject(stackTop());
                        };
                        // Unclosed control statement inside implicit parens (like
                        // class declaration or if-conditionals).
                        inImplicitControl = function () {
                            var ref;
                            return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === 'CONTROL';
                        };
                        startImplicitCall = function (idx) {
                            stack.push([
                                '(',
                                idx,
                                {
                                    ours: true
                                }
                            ]);
                            return tokens.splice(idx, 0, generate('CALL_START', '(', ['', 'implicit function call', token[2]], prevToken));
                        };
                        endImplicitCall = function () {
                            stack.pop();
                            tokens.splice(i, 0, generate('CALL_END', ')', ['', 'end of input', token[2]], prevToken));
                            return i += 1;
                        };
                        startImplicitObject = function (idx, startsLine = true) {
                            var val;
                            stack.push([
                                '{',
                                idx,
                                {
                                    sameLine: true,
                                    startsLine: startsLine,
                                    ours: true
                                }
                            ]);
                            val = new String('{');
                            val.generated = true;
                            return tokens.splice(idx, 0, generate('{', val, token, prevToken));
                        };
                        endImplicitObject = function (j) {
                            j = j != null ? j : i;
                            stack.pop();
                            tokens.splice(j, 0, generate('}', '}', token, prevToken));
                            return i += 1;
                        };
                        implicitObjectContinues = (j) => {
                            var nextTerminatorIdx;
                            nextTerminatorIdx = null;
                            this.detectEnd(j, function (token) {
                                return token[0] === 'TERMINATOR';
                            }, function (token, i) {
                                return nextTerminatorIdx = i;
                            }, {
                                returnOnNegativeLevel: true
                            });
                            if (nextTerminatorIdx == null) {
                                return false;
                            }
                            return this.looksObjectish(nextTerminatorIdx + 1);
                        };
                        // Don’t end an implicit call/object on next indent if any of these are in an argument/value.
                        if ((inImplicitCall() || inImplicitObject()) && indexOf.call(CONTROL_IN_IMPLICIT, tag) >= 0 || inImplicitObject() && prevTag === ':' && tag === 'FOR') {
                            stack.push([
                                'CONTROL',
                                i,
                                {
                                    ours: true
                                }
                            ]);
                            return forward(1);
                        }
                        if (tag === 'INDENT' && inImplicit()) {
                            // An `INDENT` closes an implicit call unless
                            //  1. We have seen a `CONTROL` argument on the line.
                            //  2. The last token before the indent is part of the list below.
                            if (prevTag !== '=>' && prevTag !== '->' && prevTag !== '[' && prevTag !== '(' && prevTag !== ',' && prevTag !== '{' && prevTag !== 'ELSE' && prevTag !== '=') {
                                while (inImplicitCall() || inImplicitObject() && prevTag !== ':') {
                                    if (inImplicitCall()) {
                                        endImplicitCall();
                                    }
                                    else {
                                        endImplicitObject();
                                    }
                                }
                            }
                            if (inImplicitControl()) {
                                stack.pop();
                            }
                            stack.push([tag, i]);
                            return forward(1);
                        }
                        // Straightforward start of explicit expression.
                        if (indexOf.call(EXPRESSION_START, tag) >= 0) {
                            stack.push([tag, i]);
                            return forward(1);
                        }
                        // Close all implicit expressions inside of explicitly closed expressions.
                        if (indexOf.call(EXPRESSION_END, tag) >= 0) {
                            while (inImplicit()) {
                                if (inImplicitCall()) {
                                    endImplicitCall();
                                }
                                else if (inImplicitObject()) {
                                    endImplicitObject();
                                }
                                else {
                                    stack.pop();
                                }
                            }
                            start = stack.pop();
                        }
                        inControlFlow = () => {
                            var controlFlow, isFunc, seenFor, tagCurrentLine;
                            seenFor = this.findTagsBackwards(i, ['FOR']) && this.findTagsBackwards(i, ['FORIN', 'FOROF', 'FORFROM']);
                            controlFlow = seenFor || this.findTagsBackwards(i, ['WHILE', 'UNTIL', 'LOOP', 'LEADING_WHEN']);
                            if (!controlFlow) {
                                return false;
                            }
                            isFunc = false;
                            tagCurrentLine = token[2].first_line;
                            this.detectEnd(i, function (token, i) {
                                var ref;
                                return ref = token[0], indexOf.call(LINEBREAKS, ref) >= 0;
                            }, function (token, i) {
                                var first_line;
                                [prevTag, , { first_line }] = tokens[i - 1] || [];
                                return isFunc = tagCurrentLine === first_line && (prevTag === '->' || prevTag === '=>');
                            }, {
                                returnOnNegativeLevel: true
                            });
                            return isFunc;
                        };
                        // Recognize standard implicit calls like
                        // f a, f() b, f? c, h[0] d etc.
                        // Added support for spread dots on the left side: f ...a
                        if ((indexOf.call(IMPLICIT_FUNC, tag) >= 0 && token.spaced || tag === '?' && i > 0 && !tokens[i - 1].spaced) && (indexOf.call(IMPLICIT_CALL, nextTag) >= 0 || (nextTag === '...' && (ref = this.tag(i + 2), indexOf.call(IMPLICIT_CALL, ref) >= 0) && !this.findTagsBackwards(i, ['INDEX_START', '['])) || indexOf.call(IMPLICIT_UNSPACED_CALL, nextTag) >= 0 && !nextToken.spaced && !nextToken.newLine) && !inControlFlow()) {
                            if (tag === '?') {
                                tag = token[0] = 'FUNC_EXIST';
                            }
                            startImplicitCall(i + 1);
                            return forward(2);
                        }
                        // Implicit call taking an implicit indented object as first argument.
                        //     f
                        //       a: b
                        //       c: d
                        // Don’t accept implicit calls of this type, when on the same line
                        // as the control structures below as that may misinterpret constructs like:
                        //     if f
                        //        a: 1
                        // as
                        //     if f(a: 1)
                        // which is probably always unintended.
                        // Furthermore don’t allow this in literal arrays, as
                        // that creates grammatical ambiguities.
                        if (indexOf.call(IMPLICIT_FUNC, tag) >= 0 && this.indexOfTag(i + 1, 'INDENT') > -1 && this.looksObjectish(i + 2) && !this.findTagsBackwards(i, ['CLASS', 'EXTENDS', 'IF', 'CATCH', 'SWITCH', 'LEADING_WHEN', 'FOR', 'WHILE', 'UNTIL'])) {
                            startImplicitCall(i + 1);
                            stack.push(['INDENT', i + 2]);
                            return forward(3);
                        }
                        // Implicit objects start here.
                        if (tag === ':') {
                            // Go back to the (implicit) start of the object.
                            s = (function () {
                                var ref1;
                                switch (false) {
                                    case ref1 = this.tag(i - 1), indexOf.call(EXPRESSION_END, ref1) < 0:
                                        return start[1];
                                    case this.tag(i - 2) !== '@':
                                        return i - 2;
                                    default:
                                        return i - 1;
                                }
                            }).call(this);
                            startsLine = s <= 0 || (ref1 = this.tag(s - 1), indexOf.call(LINEBREAKS, ref1) >= 0) || tokens[s - 1].newLine;
                            // Are we just continuing an already declared object?
                            if (stackTop()) {
                                [stackTag, stackIdx] = stackTop();
                                if ((stackTag === '{' || stackTag === 'INDENT' && this.tag(stackIdx - 1) === '{') && (startsLine || this.tag(s - 1) === ',' || this.tag(s - 1) === '{')) {
                                    return forward(1);
                                }
                            }
                            startImplicitObject(s, !!startsLine);
                            return forward(2);
                        }
                        // End implicit calls when chaining method calls
                        // like e.g.:
                        //     f ->
                        //       a
                        //     .g b, ->
                        //       c
                        //     .h a
                        // and also
                        //     f a
                        //     .g b
                        //     .h a
                        // Mark all enclosing objects as not sameLine
                        if (indexOf.call(LINEBREAKS, tag) >= 0) {
                            for (k = stack.length - 1; k >= 0; k += -1) {
                                stackItem = stack[k];
                                if (!isImplicit(stackItem)) {
                                    break;
                                }
                                if (isImplicitObject(stackItem)) {
                                    stackItem[2].sameLine = false;
                                }
                            }
                        }
                        newLine = prevTag === 'OUTDENT' || prevToken.newLine;
                        if (indexOf.call(IMPLICIT_END, tag) >= 0 || (indexOf.call(CALL_CLOSERS, tag) >= 0 && newLine) || ((tag === '..' || tag === '...') && this.findTagsBackwards(i, ["INDEX_START"]))) {
                            while (inImplicit()) {
                                [stackTag, stackIdx, { sameLine, startsLine }] = stackTop();
                                // Close implicit calls when reached end of argument list
                                if (inImplicitCall() && prevTag !== ',' || (prevTag === ',' && tag === 'TERMINATOR' && (nextTag == null))) {
                                    endImplicitCall();
                                    // Close implicit objects such as:
                                    // return a: 1, b: 2 unless true
                                }
                                else if (inImplicitObject() && sameLine && tag !== 'TERMINATOR' && prevTag !== ':' && !((tag === 'POST_IF' || tag === 'FOR' || tag === 'WHILE' || tag === 'UNTIL') && startsLine && implicitObjectContinues(i + 1))) {
                                    endImplicitObject();
                                    // Close implicit objects when at end of line, line didn't end with a comma
                                    // and the implicit object didn't start the line or the next line doesn’t look like
                                    // the continuation of an object.
                                }
                                else if (inImplicitObject() && tag === 'TERMINATOR' && prevTag !== ',' && !(startsLine && this.looksObjectish(i + 1))) {
                                    endImplicitObject();
                                }
                                else {
                                    break;
                                }
                            }
                        }
                        // Close implicit object if comma is the last character
                        // and what comes after doesn’t look like it belongs.
                        // This is used for trailing commas and calls, like:
                        //     x =
                        //         a: b,
                        //         c: d,
                        //     e = 2
                        // and
                        //     f a, b: c, d: e, f, g: h: i, j
                        if (tag === ',' && !this.looksObjectish(i + 1) && inImplicitObject() && !((ref2 = this.tag(i + 2)) === 'FOROF' || ref2 === 'FORIN') && (nextTag !== 'TERMINATOR' || !this.looksObjectish(i + 2))) {
                            // When nextTag is OUTDENT the comma is insignificant and
                            // should just be ignored so embed it in the implicit object.
                            // When it isn’t the comma go on to play a role in a call or
                            // array further up the stack, so give it a chance.
                            offset = nextTag === 'OUTDENT' ? 1 : 0;
                            while (inImplicitObject()) {
                                endImplicitObject(i + offset);
                            }
                        }
                        return forward(1);
                    });
                }
                // Make sure only strings and wrapped expressions are used in CSX attributes.
                enforceValidCSXAttributes() {
                    return this.scanTokens(function (token, i, tokens) {
                        var next, ref;
                        if (token.csxColon) {
                            next = tokens[i + 1];
                            if ((ref = next[0]) !== 'STRING_START' && ref !== 'STRING' && ref !== '(') {
                                throwSyntaxError('expected wrapped or quoted JSX attribute', next[2]);
                            }
                        }
                        return 1;
                    });
                }
                // Not all tokens survive processing by the parser. To avoid comments getting
                // lost into the ether, find comments attached to doomed tokens and move them
                // to a token that will make it to the other side.
                rescueStowawayComments() {
                    var insertPlaceholder, shiftCommentsBackward, shiftCommentsForward;
                    insertPlaceholder = function (token, j, tokens, method) {
                        if (tokens[j][0] !== 'TERMINATOR') {
                            tokens[method](generate('TERMINATOR', '\n', tokens[j]));
                        }
                        return tokens[method](generate('JS', '', tokens[j], token));
                    };
                    shiftCommentsForward = function (token, i, tokens) {
                        var comment, j, k, len, ref, ref1, ref2;
                        // Find the next surviving token and attach this token’s comments to it,
                        // with a flag that we know to output such comments *before* that
                        // token’s own compilation. (Otherwise comments are output following
                        // the token they’re attached to.)
                        j = i;
                        while (j !== tokens.length && (ref = tokens[j][0], indexOf.call(DISCARDED, ref) >= 0)) {
                            j++;
                        }
                        if (!(j === tokens.length || (ref1 = tokens[j][0], indexOf.call(DISCARDED, ref1) >= 0))) {
                            ref2 = token.comments;
                            for (k = 0, len = ref2.length; k < len; k++) {
                                comment = ref2[k];
                                comment.unshift = true;
                            }
                            moveComments(token, tokens[j]);
                            return 1; // All following tokens are doomed!
                        }
                        else {
                            j = tokens.length - 1;
                            insertPlaceholder(token, j, tokens, 'push');
                            // The generated tokens were added to the end, not inline, so we don’t skip.
                            return 1;
                        }
                    };
                    shiftCommentsBackward = function (token, i, tokens) {
                        var j, ref, ref1;
                        // Find the last surviving token and attach this token’s comments to it.
                        j = i;
                        while (j !== -1 && (ref = tokens[j][0], indexOf.call(DISCARDED, ref) >= 0)) {
                            j--;
                        }
                        if (!(j === -1 || (ref1 = tokens[j][0], indexOf.call(DISCARDED, ref1) >= 0))) {
                            moveComments(token, tokens[j]);
                            return 1; // All previous tokens are doomed!
                        }
                        else {
                            insertPlaceholder(token, 0, tokens, 'unshift');
                            // We added two tokens, so shift forward to account for the insertion.
                            return 3;
                        }
                    };
                    return this.scanTokens(function (token, i, tokens) {
                        var dummyToken, j, ref, ref1, ret;
                        if (!token.comments) {
                            return 1;
                        }
                        ret = 1;
                        if (ref = token[0], indexOf.call(DISCARDED, ref) >= 0) {
                            // This token won’t survive passage through the parser, so we need to
                            // rescue its attached tokens and redistribute them to nearby tokens.
                            // Comments that don’t start a new line can shift backwards to the last
                            // safe token, while other tokens should shift forward.
                            dummyToken = {
                                comments: []
                            };
                            j = token.comments.length - 1;
                            while (j !== -1) {
                                if (token.comments[j].newLine === false && token.comments[j].here === false) {
                                    dummyToken.comments.unshift(token.comments[j]);
                                    token.comments.splice(j, 1);
                                }
                                j--;
                            }
                            if (dummyToken.comments.length !== 0) {
                                ret = shiftCommentsBackward(dummyToken, i - 1, tokens);
                            }
                            if (token.comments.length !== 0) {
                                shiftCommentsForward(token, i, tokens);
                            }
                        }
                        else {
                            // If any of this token’s comments start a line—there’s only
                            // whitespace between the preceding newline and the start of the
                            // comment—and this isn’t one of the special `JS` tokens, then
                            // shift this comment forward to precede the next valid token.
                            // `Block.compileComments` also has logic to make sure that
                            // “starting new line” comments follow or precede the nearest
                            // newline relative to the token that the comment is attached to,
                            // but that newline might be inside a `}` or `)` or other generated
                            // token that we really want this comment to output after. Therefore
                            // we need to shift the comments here, avoiding such generated and
                            // discarded tokens.
                            dummyToken = {
                                comments: []
                            };
                            j = token.comments.length - 1;
                            while (j !== -1) {
                                if (token.comments[j].newLine && !token.comments[j].unshift && !(token[0] === 'JS' && token.generated)) {
                                    dummyToken.comments.unshift(token.comments[j]);
                                    token.comments.splice(j, 1);
                                }
                                j--;
                            }
                            if (dummyToken.comments.length !== 0) {
                                ret = shiftCommentsForward(dummyToken, i + 1, tokens);
                            }
                        }
                        if (((ref1 = token.comments) != null ? ref1.length : void 0) === 0) {
                            delete token.comments;
                        }
                        return ret;
                    });
                }
                // Add location data to all tokens generated by the rewriter.
                addLocationDataToGeneratedTokens() {
                    return this.scanTokens(function (token, i, tokens) {
                        var column, line, nextLocation, prevLocation, ref, ref1;
                        if (token[2]) {
                            return 1;
                        }
                        if (!(token.generated || token.explicit)) {
                            return 1;
                        }
                        if (token[0] === '{' && (nextLocation = (ref = tokens[i + 1]) != null ? ref[2] : void 0)) {
                            ({
                                first_line: line,
                                first_column: column
                            } = nextLocation);
                        }
                        else if (prevLocation = (ref1 = tokens[i - 1]) != null ? ref1[2] : void 0) {
                            ({
                                last_line: line,
                                last_column: column
                            } = prevLocation);
                        }
                        else {
                            line = column = 0;
                        }
                        token[2] = {
                            first_line: line,
                            first_column: column,
                            last_line: line,
                            last_column: column
                        };
                        return 1;
                    });
                }
                // `OUTDENT` tokens should always be positioned at the last character of the
                // previous token, so that AST nodes ending in an `OUTDENT` token end up with a
                // location corresponding to the last “real” token under the node.
                fixOutdentLocationData() {
                    return this.scanTokens(function (token, i, tokens) {
                        var prevLocationData;
                        if (!(token[0] === 'OUTDENT' || (token.generated && token[0] === 'CALL_END') || (token.generated && token[0] === '}'))) {
                            return 1;
                        }
                        prevLocationData = tokens[i - 1][2];
                        token[2] = {
                            first_line: prevLocationData.last_line,
                            first_column: prevLocationData.last_column,
                            last_line: prevLocationData.last_line,
                            last_column: prevLocationData.last_column
                        };
                        return 1;
                    });
                }
                // Add parens around a `do` IIFE followed by a chained `.` so that the
                // chaining applies to the executed function rather than the function
                // object (see #3736)
                addParensToChainedDoIife() {
                    var action, condition, doIndex;
                    condition = function (token, i) {
                        return this.tag(i - 1) === 'OUTDENT';
                    };
                    action = function (token, i) {
                        var ref;
                        if (ref = token[0], indexOf.call(CALL_CLOSERS, ref) < 0) {
                            return;
                        }
                        this.tokens.splice(doIndex, 0, generate('(', '(', this.tokens[doIndex]));
                        return this.tokens.splice(i + 1, 0, generate(')', ')', this.tokens[i]));
                    };
                    doIndex = null;
                    return this.scanTokens(function (token, i, tokens) {
                        var glyphIndex, ref;
                        if (token[1] !== 'do') {
                            return 1;
                        }
                        doIndex = i;
                        glyphIndex = i + 1;
                        if (this.tag(i + 1) === 'PARAM_START') {
                            glyphIndex = null;
                            this.detectEnd(i + 1, function (token, i) {
                                return this.tag(i - 1) === 'PARAM_END';
                            }, function (token, i) {
                                return glyphIndex = i;
                            });
                        }
                        if (!((glyphIndex != null) && ((ref = this.tag(glyphIndex)) === '->' || ref === '=>') && this.tag(glyphIndex + 1) === 'INDENT')) {
                            return 1;
                        }
                        this.detectEnd(glyphIndex + 1, condition, action);
                        return 2;
                    });
                }
                // Because our grammar is LALR(1), it can’t handle some single-line
                // expressions that lack ending delimiters. The **Rewriter** adds the implicit
                // blocks, so it doesn’t need to. To keep the grammar clean and tidy, trailing
                // newlines within expressions are removed and the indentation tokens of empty
                // blocks are added.
                normalizeLines() {
                    var action, closeElseTag, condition, ifThens, indent, leading_if_then, leading_switch_when, outdent, starter;
                    starter = indent = outdent = null;
                    leading_switch_when = null;
                    leading_if_then = null;
                    // Count `THEN` tags
                    ifThens = [];
                    condition = function (token, i) {
                        var ref, ref1, ref2, ref3;
                        return token[1] !== ';' && (ref = token[0], indexOf.call(SINGLE_CLOSERS, ref) >= 0) && !(token[0] === 'TERMINATOR' && (ref1 = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref1) >= 0)) && !(token[0] === 'ELSE' && (starter !== 'THEN' || (leading_if_then || leading_switch_when))) && !(((ref2 = token[0]) === 'CATCH' || ref2 === 'FINALLY') && (starter === '->' || starter === '=>')) || (ref3 = token[0], indexOf.call(CALL_CLOSERS, ref3) >= 0) && (this.tokens[i - 1].newLine || this.tokens[i - 1][0] === 'OUTDENT');
                    };
                    action = function (token, i) {
                        if (token[0] === 'ELSE' && starter === 'THEN') {
                            ifThens.pop();
                        }
                        return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
                    };
                    closeElseTag = (tokens, i) => {
                        var lastThen, outdentElse, tlen;
                        tlen = ifThens.length;
                        if (!(tlen > 0)) {
                            return i;
                        }
                        lastThen = ifThens.pop();
                        [, outdentElse] = this.indentation(tokens[lastThen]);
                        // Insert `OUTDENT` to close inner `IF`.
                        outdentElse[1] = tlen * 2;
                        tokens.splice(i, 0, outdentElse);
                        // Insert `OUTDENT` to close outer `IF`.
                        outdentElse[1] = 2;
                        tokens.splice(i + 1, 0, outdentElse);
                        // Remove outdents from the end.
                        this.detectEnd(i + 2, function (token, i) {
                            var ref;
                            return (ref = token[0]) === 'OUTDENT' || ref === 'TERMINATOR';
                        }, function (token, i) {
                            if (this.tag(i) === 'OUTDENT' && this.tag(i + 1) === 'OUTDENT') {
                                return tokens.splice(i, 2);
                            }
                        });
                        return i + 2;
                    };
                    return this.scanTokens(function (token, i, tokens) {
                        var conditionTag, j, k, ref, ref1, tag;
                        [tag] = token;
                        conditionTag = (tag === '->' || tag === '=>') && this.findTagsBackwards(i, ['IF', 'WHILE', 'FOR', 'UNTIL', 'SWITCH', 'WHEN', 'LEADING_WHEN', '[', 'INDEX_START']) && !(this.findTagsBackwards(i, ['THEN', '..', '...']));
                        if (tag === 'TERMINATOR') {
                            if (this.tag(i + 1) === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
                                tokens.splice(i, 1, ...this.indentation());
                                return 1;
                            }
                            if (ref = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref) >= 0) {
                                tokens.splice(i, 1);
                                return 0;
                            }
                        }
                        if (tag === 'CATCH') {
                            for (j = k = 1; k <= 2; j = ++k) {
                                if (!((ref1 = this.tag(i + j)) === 'OUTDENT' || ref1 === 'TERMINATOR' || ref1 === 'FINALLY')) {
                                    continue;
                                }
                                tokens.splice(i + j, 0, ...this.indentation());
                                return 2 + j;
                            }
                        }
                        if ((tag === '->' || tag === '=>') && (this.tag(i + 1) === ',' || this.tag(i + 1) === '.' && token.newLine)) {
                            [indent, outdent] = this.indentation(tokens[i]);
                            tokens.splice(i + 1, 0, indent, outdent);
                            return 1;
                        }
                        if (indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF') && !conditionTag) {
                            starter = tag;
                            [indent, outdent] = this.indentation(tokens[i]);
                            if (starter === 'THEN') {
                                indent.fromThen = true;
                            }
                            if (tag === 'THEN') {
                                leading_switch_when = this.findTagsBackwards(i, ['LEADING_WHEN']) && this.tag(i + 1) === 'IF';
                                leading_if_then = this.findTagsBackwards(i, ['IF']) && this.tag(i + 1) === 'IF';
                            }
                            if (tag === 'THEN' && this.findTagsBackwards(i, ['IF'])) {
                                ifThens.push(i);
                            }
                            // `ELSE` tag is not closed.
                            if (tag === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
                                i = closeElseTag(tokens, i);
                            }
                            tokens.splice(i + 1, 0, indent);
                            this.detectEnd(i + 2, condition, action);
                            if (tag === 'THEN') {
                                tokens.splice(i, 1);
                            }
                            return 1;
                        }
                        return 1;
                    });
                }
                // Tag postfix conditionals as such, so that we can parse them with a
                // different precedence.
                tagPostfixConditionals() {
                    var action, condition, original;
                    original = null;
                    condition = function (token, i) {
                        var prevTag, tag;
                        [tag] = token;
                        [prevTag] = this.tokens[i - 1];
                        return tag === 'TERMINATOR' || (tag === 'INDENT' && indexOf.call(SINGLE_LINERS, prevTag) < 0);
                    };
                    action = function (token, i) {
                        if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) {
                            return original[0] = 'POST_' + original[0];
                        }
                    };
                    return this.scanTokens(function (token, i) {
                        if (token[0] !== 'IF') {
                            return 1;
                        }
                        original = token;
                        this.detectEnd(i + 1, condition, action);
                        return 1;
                    });
                }
                // Generate the indentation tokens, based on another token on the same line.
                indentation(origin) {
                    var indent, outdent;
                    indent = ['INDENT', 2];
                    outdent = ['OUTDENT', 2];
                    if (origin) {
                        indent.generated = outdent.generated = true;
                        indent.origin = outdent.origin = origin;
                    }
                    else {
                        indent.explicit = outdent.explicit = true;
                    }
                    return [indent, outdent];
                }
                // Look up a tag by token index.
                tag(i) {
                    var ref;
                    return (ref = this.tokens[i]) != null ? ref[0] : void 0;
                }
            }
            ;
            Rewriter.prototype.generate = generate;
            return Rewriter;
        }).call(this);
        // Constants
        // ---------
        // List of the token pairs that must be balanced.
        BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END'], ['STRING_START', 'STRING_END'], ['REGEX_START', 'REGEX_END']];
        // The inverse mappings of `BALANCED_PAIRS` we’re trying to fix up, so we can
        // look things up from either end.
        exports.INVERSES = INVERSES = {};
        // The tokens that signal the start/end of a balanced pair.
        EXPRESSION_START = [];
        EXPRESSION_END = [];
        for (k = 0, len = BALANCED_PAIRS.length; k < len; k++) {
            [left, right] = BALANCED_PAIRS[k];
            EXPRESSION_START.push(INVERSES[right] = left);
            EXPRESSION_END.push(INVERSES[left] = right);
        }
        // Tokens that indicate the close of a clause of an expression.
        EXPRESSION_CLOSE = ['CATCH', 'THEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);
        // Tokens that, if followed by an `IMPLICIT_CALL`, indicate a function invocation.
        IMPLICIT_FUNC = ['IDENTIFIER', 'PROPERTY', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];
        // If preceded by an `IMPLICIT_FUNC`, indicates a function invocation.
        IMPLICIT_CALL = ['IDENTIFIER', 'CSX_TAG', 'PROPERTY', 'NUMBER', 'INFINITY', 'NAN', 'STRING', 'STRING_START', 'REGEX', 'REGEX_START', 'JS', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'UNDEFINED', 'NULL', 'BOOL', 'UNARY', 'YIELD', 'AWAIT', 'UNARY_MATH', 'SUPER', 'THROW', '@', '->', '=>', '[', '(', '{', '--', '++'];
        IMPLICIT_UNSPACED_CALL = ['+', '-'];
        // Tokens that always mark the end of an implicit call for single-liners.
        IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];
        // Single-line flavors of block expressions that have unclosed endings.
        // The grammar can’t disambiguate them, so we insert the implicit indentation.
        SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];
        SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];
        // Tokens that end a line.
        LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];
        // Tokens that close open calls when they follow a newline.
        CALL_CLOSERS = ['.', '?.', '::', '?::'];
        // Tokens that prevent a subsequent indent from ending implicit calls/objects
        CONTROL_IN_IMPLICIT = ['IF', 'TRY', 'FINALLY', 'CATCH', 'CLASS', 'SWITCH'];
        // Tokens that are swallowed up by the parser, never leading to code generation.
        // You can spot these in `grammar.coffee` because the `o` function second
        // argument doesn’t contain a `new` call for these tokens.
        // `STRING_START` isn’t on this list because its `locationData` matches that of
        // the node that becomes `StringWithInterpolations`, and therefore
        // `addDataToNode` attaches `STRING_START`’s tokens to that node.
        DISCARDED = ['(', ')', '[', ']', '{', '}', '.', '..', '...', ',', '=', '++', '--', '?', 'AS', 'AWAIT', 'CALL_START', 'CALL_END', 'DEFAULT', 'ELSE', 'EXTENDS', 'EXPORT', 'FORIN', 'FOROF', 'FORFROM', 'IMPORT', 'INDENT', 'INDEX_SOAK', 'LEADING_WHEN', 'OUTDENT', 'PARAM_END', 'REGEX_START', 'REGEX_END', 'RETURN', 'STRING_END', 'THROW', 'UNARY', 'YIELD'].concat(IMPLICIT_UNSPACED_CALL.concat(IMPLICIT_END.concat(CALL_CLOSERS.concat(CONTROL_IN_IMPLICIT))));
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/scope */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // The **Scope** class regulates lexical scoping within CoffeeScript. As you
        // generate code, you create a tree of scopes in the same shape as the nested
        // function bodies. Each scope knows about the variables declared within it,
        // and has a reference to its parent enclosing scope. In this way, we know which
        // variables are new and need to be declared with `var`, and which are shared
        // with external scopes.
        var Scope, indexOf = [].indexOf;
        exports.Scope = Scope = class Scope {
            // Initialize a scope with its parent, for lookups up the chain,
            // as well as a reference to the **Block** node it belongs to, which is
            // where it should declare its variables, a reference to the function that
            // it belongs to, and a list of variables referenced in the source code
            // and therefore should be avoided when generating variables. Also track comments
            // that should be output as part of variable declarations.
            constructor(parent, expressions, method, referencedVars) {
                var ref, ref1;
                this.parent = parent;
                this.expressions = expressions;
                this.method = method;
                this.referencedVars = referencedVars;
                this.variables = [
                    {
                        name: 'arguments',
                        type: 'arguments'
                    }
                ];
                this.comments = {};
                this.positions = {};
                if (!this.parent) {
                    this.utilities = {};
                }
                // The `@root` is the top-level **Scope** object for a given file.
                this.root = (ref = (ref1 = this.parent) != null ? ref1.root : void 0) != null ? ref : this;
            }
            // Adds a new variable or overrides an existing one.
            add(name, type, immediate) {
                if (this.shared && !immediate) {
                    return this.parent.add(name, type, immediate);
                }
                if (Object.prototype.hasOwnProperty.call(this.positions, name)) {
                    return this.variables[this.positions[name]].type = type;
                }
                else {
                    return this.positions[name] = this.variables.push({ name, type }) - 1;
                }
            }
            // When `super` is called, we need to find the name of the current method we're
            // in, so that we know how to invoke the same method of the parent class. This
            // can get complicated if super is being called from an inner function.
            // `namedMethod` will walk up the scope tree until it either finds the first
            // function object that has a name filled in, or bottoms out.
            namedMethod() {
                var ref;
                if (((ref = this.method) != null ? ref.name : void 0) || !this.parent) {
                    return this.method;
                }
                return this.parent.namedMethod();
            }
            // Look up a variable name in lexical scope, and declare it if it does not
            // already exist.
            find(name, type = 'var') {
                if (this.check(name)) {
                    return true;
                }
                this.add(name, type);
                return false;
            }
            // Reserve a variable name as originating from a function parameter for this
            // scope. No `var` required for internal references.
            parameter(name) {
                if (this.shared && this.parent.check(name, true)) {
                    return;
                }
                return this.add(name, 'param');
            }
            // Just check to see if a variable has already been declared, without reserving,
            // walks up to the root scope.
            check(name) {
                var ref;
                return !!(this.type(name) || ((ref = this.parent) != null ? ref.check(name) : void 0));
            }
            // Generate a temporary variable name at the given index.
            temporary(name, index, single = false) {
                var diff, endCode, letter, newCode, num, startCode;
                if (single) {
                    startCode = name.charCodeAt(0);
                    endCode = 'z'.charCodeAt(0);
                    diff = endCode - startCode;
                    newCode = startCode + index % (diff + 1);
                    letter = String.fromCharCode(newCode);
                    num = Math.floor(index / (diff + 1));
                    return `${letter}${num || ''}`;
                }
                else {
                    return `${name}${index || ''}`;
                }
            }
            // Gets the type of a variable.
            type(name) {
                var i, len, ref, v;
                ref = this.variables;
                for (i = 0, len = ref.length; i < len; i++) {
                    v = ref[i];
                    if (v.name === name) {
                        return v.type;
                    }
                }
                return null;
            }
            // If we need to store an intermediate result, find an available name for a
            // compiler-generated variable. `_var`, `_var2`, and so on...
            freeVariable(name, options = {}) {
                var index, ref, temp;
                index = 0;
                while (true) {
                    temp = this.temporary(name, index, options.single);
                    if (!(this.check(temp) || indexOf.call(this.root.referencedVars, temp) >= 0)) {
                        break;
                    }
                    index++;
                }
                if ((ref = options.reserve) != null ? ref : true) {
                    this.add(temp, 'var', true);
                }
                return temp;
            }
            // Ensure that an assignment is made at the top of this scope
            // (or at the top-level scope, if requested).
            assign(name, value) {
                this.add(name, {
                    value,
                    assigned: true
                }, true);
                return this.hasAssignments = true;
            }
            // Does this scope have any declared variables?
            hasDeclarations() {
                return !!this.declaredVariables().length;
            }
            // Return the list of variables first declared in this scope.
            declaredVariables() {
                var v;
                return ((function () {
                    var i, len, ref, results;
                    ref = this.variables;
                    results = [];
                    for (i = 0, len = ref.length; i < len; i++) {
                        v = ref[i];
                        if (v.type === 'var') {
                            results.push(v.name);
                        }
                    }
                    return results;
                }).call(this)).sort();
            }
            // Return the list of assignments that are supposed to be made at the top
            // of this scope.
            assignedVariables() {
                var i, len, ref, results, v;
                ref = this.variables;
                results = [];
                for (i = 0, len = ref.length; i < len; i++) {
                    v = ref[i];
                    if (v.type.assigned) {
                        results.push(`${v.name} = ${v.type.value}`);
                    }
                }
                return results;
            }
        };
    }).call(this);
}
,
/* coffeescript/lib/coffeescript/sourcemap */ function _(require, module, exports) {
    // Generated by CoffeeScript 2.3.0
    (function () {
        // Source maps allow JavaScript runtimes to match running JavaScript back to
        // the original source code that corresponds to it. This can be minified
        // JavaScript, but in our case, we're concerned with mapping pretty-printed
        // JavaScript back to CoffeeScript.
        // In order to produce maps, we must keep track of positions (line number, column number)
        // that originated every node in the syntax tree, and be able to generate a
        // [map file](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit)
        // — which is a compact, VLQ-encoded representation of the JSON serialization
        // of this information — to write out alongside the generated JavaScript.
        // LineMap
        // -------
        // A **LineMap** object keeps track of information about original line and column
        // positions for a single line of output JavaScript code.
        // **SourceMaps** are implemented in terms of **LineMaps**.
        var LineMap, SourceMap;
        LineMap = class LineMap {
            constructor(line1) {
                this.line = line1;
                this.columns = [];
            }
            add(column, [sourceLine, sourceColumn], options = {}) {
                if (this.columns[column] && options.noReplace) {
                    return;
                }
                return this.columns[column] = {
                    line: this.line,
                    column,
                    sourceLine,
                    sourceColumn
                };
            }
            sourceLocation(column) {
                var mapping;
                while (!((mapping = this.columns[column]) || (column <= 0))) {
                    column--;
                }
                return mapping && [mapping.sourceLine, mapping.sourceColumn];
            }
        };
        SourceMap = (function () {
            var BASE64_CHARS, VLQ_CONTINUATION_BIT, VLQ_SHIFT, VLQ_VALUE_MASK;
            // SourceMap
            // ---------
            // Maps locations in a single generated JavaScript file back to locations in
            // the original CoffeeScript source file.
            // This is intentionally agnostic towards how a source map might be represented on
            // disk. Once the compiler is ready to produce a "v3"-style source map, we can walk
            // through the arrays of line and column buffer to produce it.
            class SourceMap {
                constructor() {
                    this.lines = [];
                }
                // Adds a mapping to this SourceMap. `sourceLocation` and `generatedLocation`
                // are both `[line, column]` arrays. If `options.noReplace` is true, then if there
                // is already a mapping for the specified `line` and `column`, this will have no
                // effect.
                add(sourceLocation, generatedLocation, options = {}) {
                    var base, column, line, lineMap;
                    [line, column] = generatedLocation;
                    lineMap = ((base = this.lines)[line] || (base[line] = new LineMap(line)));
                    return lineMap.add(column, sourceLocation, options);
                }
                // Look up the original position of a given `line` and `column` in the generated
                // code.
                sourceLocation([line, column]) {
                    var lineMap;
                    while (!((lineMap = this.lines[line]) || (line <= 0))) {
                        line--;
                    }
                    return lineMap && lineMap.sourceLocation(column);
                }
                // V3 SourceMap Generation
                // -----------------------
                // Builds up a V3 source map, returning the generated JSON as a string.
                // `options.sourceRoot` may be used to specify the sourceRoot written to the source
                // map.  Also, `options.sourceFiles` and `options.generatedFile` may be passed to
                // set "sources" and "file", respectively.
                generate(options = {}, code = null) {
                    var buffer, i, j, lastColumn, lastSourceColumn, lastSourceLine, len, len1, lineMap, lineNumber, mapping, needComma, ref, ref1, sources, v3, writingline;
                    writingline = 0;
                    lastColumn = 0;
                    lastSourceLine = 0;
                    lastSourceColumn = 0;
                    needComma = false;
                    buffer = "";
                    ref = this.lines;
                    for (lineNumber = i = 0, len = ref.length; i < len; lineNumber = ++i) {
                        lineMap = ref[lineNumber];
                        if (lineMap) {
                            ref1 = lineMap.columns;
                            for (j = 0, len1 = ref1.length; j < len1; j++) {
                                mapping = ref1[j];
                                if (!(mapping)) {
                                    continue;
                                }
                                while (writingline < mapping.line) {
                                    lastColumn = 0;
                                    needComma = false;
                                    buffer += ";";
                                    writingline++;
                                }
                                // Write a comma if we've already written a segment on this line.
                                if (needComma) {
                                    buffer += ",";
                                    needComma = false;
                                }
                                // Write the next segment. Segments can be 1, 4, or 5 values.  If just one, then it
                                // is a generated column which doesn't match anything in the source code.
                                // The starting column in the generated source, relative to any previous recorded
                                // column for the current line:
                                buffer += this.encodeVlq(mapping.column - lastColumn);
                                lastColumn = mapping.column;
                                // The index into the list of sources:
                                buffer += this.encodeVlq(0);
                                // The starting line in the original source, relative to the previous source line.
                                buffer += this.encodeVlq(mapping.sourceLine - lastSourceLine);
                                lastSourceLine = mapping.sourceLine;
                                // The starting column in the original source, relative to the previous column.
                                buffer += this.encodeVlq(mapping.sourceColumn - lastSourceColumn);
                                lastSourceColumn = mapping.sourceColumn;
                                needComma = true;
                            }
                        }
                    }
                    // Produce the canonical JSON object format for a "v3" source map.
                    sources = options.sourceFiles ? options.sourceFiles : options.filename ? [options.filename] : ['<anonymous>'];
                    v3 = {
                        version: 3,
                        file: options.generatedFile || '',
                        sourceRoot: options.sourceRoot || '',
                        sources: sources,
                        names: [],
                        mappings: buffer
                    };
                    if (options.sourceMap || options.inlineMap) {
                        v3.sourcesContent = [code];
                    }
                    return v3;
                }
                encodeVlq(value) {
                    var answer, nextChunk, signBit, valueToEncode;
                    answer = '';
                    // Least significant bit represents the sign.
                    signBit = value < 0 ? 1 : 0;
                    // The next bits are the actual value.
                    valueToEncode = (Math.abs(value) << 1) + signBit;
                    // Make sure we encode at least one character, even if valueToEncode is 0.
                    while (valueToEncode || !answer) {
                        nextChunk = valueToEncode & VLQ_VALUE_MASK;
                        valueToEncode = valueToEncode >> VLQ_SHIFT;
                        if (valueToEncode) {
                            nextChunk |= VLQ_CONTINUATION_BIT;
                        }
                        answer += this.encodeBase64(nextChunk);
                    }
                    return answer;
                }
                encodeBase64(value) {
                    return BASE64_CHARS[value] || (function () {
                        throw new Error(`Cannot Base64 encode value: ${value}`);
                    })();
                }
            }
            ;
            // Base64 VLQ Encoding
            // -------------------
            // Note that SourceMap VLQ encoding is "backwards".  MIDI-style VLQ encoding puts
            // the most-significant-bit (MSB) from the original value into the MSB of the VLQ
            // encoded value (see [Wikipedia](https://en.wikipedia.org/wiki/File:Uintvar_coding.svg)).
            // SourceMap VLQ does things the other way around, with the least significat four
            // bits of the original value encoded into the first byte of the VLQ encoded value.
            VLQ_SHIFT = 5;
            VLQ_CONTINUATION_BIT = 1 << VLQ_SHIFT; // 0010 0000
            VLQ_VALUE_MASK = VLQ_CONTINUATION_BIT - 1; // 0001 1111
            // Regular Base64 Encoding
            // -----------------------
            BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
            return SourceMap;
        }).call(this);
        // Our API for source maps is just the `SourceMap` class.
        module.exports = SourceMap;
    }).call(this);
}
,
/* coffeescript/package.json */ function _(require, module, exports) {
    {
        "_args";
        [
            [
                "coffeescript@2.3.0",
                "/home/travis/build/bokeh/bokeh/bokehjs"
            ]
        ],
            "_development";
        true,
            "_from";
        "coffeescript@2.3.0",
            "_id";
        "coffeescript@2.3.0",
            "_inBundle";
        false,
            "_integrity";
        "sha512-M1AINTgv6EvFAK92LeaYdHUzsTE+j97kBQyLHjfnMz1jh21rJMjdTe471Zgs+qK7Tavpbh5e4pP2VxcRTFxm9A==",
            "_location";
        "/coffeescript",
            "_phantomChildren";
        { }
        "_requested";
        {
            "type";
            "version",
                "registry";
            true,
                "raw";
            "coffeescript@2.3.0",
                "name";
            "coffeescript",
                "escapedName";
            "coffeescript",
                "rawSpec";
            "2.3.0",
                "saveSpec";
            null,
                "fetchSpec";
            "2.3.0";
        }
        "_requiredBy";
        [
            "#DEV:/"
        ],
            "_resolved";
        "https://registry.npmjs.org/coffeescript/-/coffeescript-2.3.0.tgz",
            "_spec";
        "2.3.0",
            "_where";
        "/home/travis/build/bokeh/bokeh/bokehjs",
            "author";
        {
            "name";
            "Jeremy Ashkenas";
        }
        "bin";
        {
            "coffee";
            "./bin/coffee",
                "cake";
            "./bin/cake";
        }
        "browser";
        "./lib/coffeescript/browser",
            "bugs";
        {
            "url";
            "https://github.com/jashkenas/coffeescript/issues";
        }
        "dependencies";
        { }
        "description";
        "Unfancy JavaScript",
            "devDependencies";
        {
            "babel-core";
            "~6.26.2",
                "babel-preset-babili";
            "~0.1.4",
                "babel-preset-env";
            "~1.6.1",
                "babel-preset-minify";
            "^0.4.0",
                "codemirror";
            "^5.37.0",
                "docco";
            "~0.8.0",
                "highlight.js";
            "~9.12.0",
                "jison";
            ">=0.4.18",
                "markdown-it";
            "~8.4.1",
                "underscore";
            "~1.9.0",
                "webpack";
            "~4.6.0";
        }
        "directories";
        {
            "lib";
            "./lib/coffeescript";
        }
        "engines";
        {
            "node";
            ">=6";
        }
        "files";
        [
            "bin",
            "lib",
            "register.js",
            "repl.js"
        ],
            "homepage";
        "http://coffeescript.org",
            "keywords";
        [
            "javascript",
            "language",
            "coffeescript",
            "compiler"
        ],
            "license";
        "MIT",
            "main";
        "./lib/coffeescript/index",
            "name";
        "coffeescript",
            "repository";
        {
            "type";
            "git",
                "url";
            "git://github.com/jashkenas/coffeescript.git";
        }
        "scripts";
        {
            "test";
            "node ./bin/cake test",
                "test-harmony";
            "node --harmony ./bin/cake test";
        }
        "version";
        "2.3.0";
    }
}
,
/* combined-stream/lib/combined_stream */ function _(require, module, exports) {
    var util = require('util');
    var Stream = require('stream').Stream;
    var DelayedStream = require(99) /* delayed-stream */;
    var defer = require(87) /* ./defer.js */;
    module.exports = CombinedStream;
    function CombinedStream() {
        this.writable = false;
        this.readable = true;
        this.dataSize = 0;
        this.maxDataSize = 2 * 1024 * 1024;
        this.pauseStreams = true;
        this._released = false;
        this._streams = [];
        this._currentStream = null;
    }
    util.inherits(CombinedStream, Stream);
    CombinedStream.create = function (options) {
        var combinedStream = new this();
        options = options || {};
        for (var option in options) {
            combinedStream[option] = options[option];
        }
        return combinedStream;
    };
    CombinedStream.isStreamLike = function (stream) {
        return (typeof stream !== 'function')
            && (typeof stream !== 'string')
            && (typeof stream !== 'boolean')
            && (typeof stream !== 'number')
            && (!Buffer.isBuffer(stream));
    };
    CombinedStream.prototype.append = function (stream) {
        var isStreamLike = CombinedStream.isStreamLike(stream);
        if (isStreamLike) {
            if (!(stream instanceof DelayedStream)) {
                var newStream = DelayedStream.create(stream, {
                    maxDataSize: Infinity,
                    pauseStream: this.pauseStreams,
                });
                stream.on('data', this._checkDataSize.bind(this));
                stream = newStream;
            }
            this._handleErrors(stream);
            if (this.pauseStreams) {
                stream.pause();
            }
        }
        this._streams.push(stream);
        return this;
    };
    CombinedStream.prototype.pipe = function (dest, options) {
        Stream.prototype.pipe.call(this, dest, options);
        this.resume();
        return dest;
    };
    CombinedStream.prototype._getNext = function () {
        this._currentStream = null;
        var stream = this._streams.shift();
        if (typeof stream == 'undefined') {
            this.end();
            return;
        }
        if (typeof stream !== 'function') {
            this._pipeNext(stream);
            return;
        }
        var getStream = stream;
        getStream(function (stream) {
            var isStreamLike = CombinedStream.isStreamLike(stream);
            if (isStreamLike) {
                stream.on('data', this._checkDataSize.bind(this));
                this._handleErrors(stream);
            }
            defer(this._pipeNext.bind(this, stream));
        }.bind(this));
    };
    CombinedStream.prototype._pipeNext = function (stream) {
        this._currentStream = stream;
        var isStreamLike = CombinedStream.isStreamLike(stream);
        if (isStreamLike) {
            stream.on('end', this._getNext.bind(this));
            stream.pipe(this, { end: false });
            return;
        }
        var value = stream;
        this.write(value);
        this._getNext();
    };
    CombinedStream.prototype._handleErrors = function (stream) {
        var self = this;
        stream.on('error', function (err) {
            self._emitError(err);
        });
    };
    CombinedStream.prototype.write = function (data) {
        this.emit('data', data);
    };
    CombinedStream.prototype.pause = function () {
        if (!this.pauseStreams) {
            return;
        }
        if (this.pauseStreams && this._currentStream && typeof (this._currentStream.pause) == 'function')
            this._currentStream.pause();
        this.emit('pause');
    };
    CombinedStream.prototype.resume = function () {
        if (!this._released) {
            this._released = true;
            this.writable = true;
            this._getNext();
        }
        if (this.pauseStreams && this._currentStream && typeof (this._currentStream.resume) == 'function')
            this._currentStream.resume();
        this.emit('resume');
    };
    CombinedStream.prototype.end = function () {
        this._reset();
        this.emit('end');
    };
    CombinedStream.prototype.destroy = function () {
        this._reset();
        this.emit('close');
    };
    CombinedStream.prototype._reset = function () {
        this.writable = false;
        this._streams = [];
        this._currentStream = null;
    };
    CombinedStream.prototype._checkDataSize = function () {
        this._updateDataSize();
        if (this.dataSize <= this.maxDataSize) {
            return;
        }
        var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
        this._emitError(new Error(message));
    };
    CombinedStream.prototype._updateDataSize = function () {
        this.dataSize = 0;
        var self = this;
        this._streams.forEach(function (stream) {
            if (!stream.dataSize) {
                return;
            }
            self.dataSize += stream.dataSize;
        });
        if (this._currentStream && this._currentStream.dataSize) {
            this.dataSize += this._currentStream.dataSize;
        }
    };
    CombinedStream.prototype._emitError = function (err) {
        this._reset();
        this.emit('error', err);
    };
}
,
/* combined-stream/lib/defer */ function _(require, module, exports) {
    module.exports = defer;
    /**
     * Runs provided function on next iteration of the event loop
     *
     * @param {function} fn - function to run
     */
    function defer(fn) {
        var nextTick = typeof setImmediate == 'function'
            ? setImmediate
            : (typeof process == 'object' && typeof process.nextTick == 'function'
                ? process.nextTick
                : null);
        if (nextTick) {
            nextTick(fn);
        }
        else {
            setTimeout(fn, 0);
        }
    }
}
,
/* core-util-is/lib/util */ 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.
    // NOTE: These type checking functions intentionally don't use `instanceof`
    // because it is fragile and can be easily faked with `Object.create()`.
    function isArray(arg) {
        if (Array.isArray) {
            return Array.isArray(arg);
        }
        return objectToString(arg) === '[object Array]';
    }
    exports.isArray = isArray;
    function isBoolean(arg) {
        return typeof arg === 'boolean';
    }
    exports.isBoolean = isBoolean;
    function isNull(arg) {
        return arg === null;
    }
    exports.isNull = isNull;
    function isNullOrUndefined(arg) {
        return arg == null;
    }
    exports.isNullOrUndefined = isNullOrUndefined;
    function isNumber(arg) {
        return typeof arg === 'number';
    }
    exports.isNumber = isNumber;
    function isString(arg) {
        return typeof arg === 'string';
    }
    exports.isString = isString;
    function isSymbol(arg) {
        return typeof arg === 'symbol';
    }
    exports.isSymbol = isSymbol;
    function isUndefined(arg) {
        return arg === void 0;
    }
    exports.isUndefined = isUndefined;
    function isRegExp(re) {
        return objectToString(re) === '[object RegExp]';
    }
    exports.isRegExp = isRegExp;
    function isObject(arg) {
        return typeof arg === 'object' && arg !== null;
    }
    exports.isObject = isObject;
    function isDate(d) {
        return objectToString(d) === '[object Date]';
    }
    exports.isDate = isDate;
    function isError(e) {
        return (objectToString(e) === '[object Error]' || e instanceof Error);
    }
    exports.isError = isError;
    function isFunction(arg) {
        return typeof arg === 'function';
    }
    exports.isFunction = isFunction;
    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;
    exports.isBuffer = Buffer.isBuffer;
    function objectToString(o) {
        return Object.prototype.toString.call(o);
    }
}
,
/* cross-spawn/index */ function _(require, module, exports) {
    var cp = require('child_process');
    var parse = require(91) /* ./lib/parse */;
    var enoent = require(90) /* ./lib/enoent */;
    var cpSpawnSync = cp.spawnSync;
    function spawn(command, args, options) {
        var parsed;
        var spawned;
        // Parse the arguments
        parsed = parse(command, args, options);
        // Spawn the child process
        spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
        // Hook into child process "exit" event to emit an error if the command
        // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
        enoent.hookChildProcess(spawned, parsed);
        return spawned;
    }
    function spawnSync(command, args, options) {
        var parsed;
        var result;
        if (!cpSpawnSync) {
            try {
                cpSpawnSync = require(330) /* spawn-sync */; // eslint-disable-line global-require
            }
            catch (ex) {
                throw new Error('In order to use spawnSync on node 0.10 or older, you must ' +
                    'install spawn-sync:\n\n' +
                    '  npm install spawn-sync --save');
            }
        }
        // Parse the arguments
        parsed = parse(command, args, options);
        // Spawn the child process
        result = cpSpawnSync(parsed.command, parsed.args, parsed.options);
        // Analyze if the command does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
        result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
        return result;
    }
    module.exports = spawn;
    module.exports.spawn = spawn;
    module.exports.sync = spawnSync;
    module.exports._parse = parse;
    module.exports._enoent = enoent;
}
,
/* cross-spawn/lib/enoent */ function _(require, module, exports) {
    var isWin = process.platform === 'win32';
    var resolveCommand = require(96) /* ./util/resolveCommand */;
    var isNode10 = process.version.indexOf('v0.10.') === 0;
    function notFoundError(command, syscall) {
        var err;
        err = new Error(syscall + ' ' + command + ' ENOENT');
        err.code = err.errno = 'ENOENT';
        err.syscall = syscall + ' ' + command;
        return err;
    }
    function hookChildProcess(cp, parsed) {
        var originalEmit;
        if (!isWin) {
            return;
        }
        originalEmit = cp.emit;
        cp.emit = function (name, arg1) {
            var err;
            // If emitting "exit" event and exit code is 1, we need to check if
            // the command exists and emit an "error" instead
            // See: https://github.com/IndigoUnited/node-cross-spawn/issues/16
            if (name === 'exit') {
                err = verifyENOENT(arg1, parsed, 'spawn');
                if (err) {
                    return originalEmit.call(cp, 'error', err);
                }
            }
            return originalEmit.apply(cp, arguments);
        };
    }
    function verifyENOENT(status, parsed) {
        if (isWin && status === 1 && !parsed.file) {
            return notFoundError(parsed.original, 'spawn');
        }
        return null;
    }
    function verifyENOENTSync(status, parsed) {
        if (isWin && status === 1 && !parsed.file) {
            return notFoundError(parsed.original, 'spawnSync');
        }
        // If we are in node 10, then we are using spawn-sync; if it exited
        // with -1 it probably means that the command does not exist
        if (isNode10 && status === -1) {
            parsed.file = isWin ? parsed.file : resolveCommand(parsed.original);
            if (!parsed.file) {
                return notFoundError(parsed.original, 'spawnSync');
            }
        }
        return null;
    }
    module.exports.hookChildProcess = hookChildProcess;
    module.exports.verifyENOENT = verifyENOENT;
    module.exports.verifyENOENTSync = verifyENOENTSync;
    module.exports.notFoundError = notFoundError;
}
,
/* cross-spawn/lib/parse */ function _(require, module, exports) {
    var resolveCommand = require(96) /* ./util/resolveCommand */;
    var hasEmptyArgumentBug = require(94) /* ./util/hasEmptyArgumentBug */;
    var escapeArgument = require(92) /* ./util/escapeArgument */;
    var escapeCommand = require(93) /* ./util/escapeCommand */;
    var readShebang = require(95) /* ./util/readShebang */;
    var isWin = process.platform === 'win32';
    var skipShellRegExp = /\.(?:com|exe)$/i;
    // Supported in Node >= 6 and >= 4.8
    var supportsShellOption = parseInt(process.version.substr(1).split('.')[0], 10) >= 6 ||
        parseInt(process.version.substr(1).split('.')[0], 10) === 4 && parseInt(process.version.substr(1).split('.')[1], 10) >= 8;
    function parseNonShell(parsed) {
        var shebang;
        var needsShell;
        var applyQuotes;
        if (!isWin) {
            return parsed;
        }
        // Detect & add support for shebangs
        parsed.file = resolveCommand(parsed.command);
        parsed.file = parsed.file || resolveCommand(parsed.command, true);
        shebang = parsed.file && readShebang(parsed.file);
        if (shebang) {
            parsed.args.unshift(parsed.file);
            parsed.command = shebang;
            needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(resolveCommand(shebang) || resolveCommand(shebang, true));
        }
        else {
            needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(parsed.file);
        }
        // If a shell is required, use cmd.exe and take care of escaping everything correctly
        if (needsShell) {
            // Escape command & arguments
            applyQuotes = (parsed.command !== 'echo'); // Do not quote arguments for the special "echo" command
            parsed.command = escapeCommand(parsed.command);
            parsed.args = parsed.args.map(function (arg) {
                return escapeArgument(arg, applyQuotes);
            });
            // Make use of cmd.exe
            parsed.args = ['/d', '/s', '/c', '"' + parsed.command + (parsed.args.length ? ' ' + parsed.args.join(' ') : '') + '"'];
            parsed.command = process.env.comspec || 'cmd.exe';
            parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
        }
        return parsed;
    }
    function parseShell(parsed) {
        var shellCommand;
        // If node supports the shell option, there's no need to mimic its behavior
        if (supportsShellOption) {
            return parsed;
        }
        // Mimic node shell option, see: https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335
        shellCommand = [parsed.command].concat(parsed.args).join(' ');
        if (isWin) {
            parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe';
            parsed.args = ['/d', '/s', '/c', '"' + shellCommand + '"'];
            parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
        }
        else {
            if (typeof parsed.options.shell === 'string') {
                parsed.command = parsed.options.shell;
            }
            else if (process.platform === 'android') {
                parsed.command = '/system/bin/sh';
            }
            else {
                parsed.command = '/bin/sh';
            }
            parsed.args = ['-c', shellCommand];
        }
        return parsed;
    }
    // ------------------------------------------------
    function parse(command, args, options) {
        var parsed;
        // Normalize arguments, similar to nodejs
        if (args && !Array.isArray(args)) {
            options = args;
            args = null;
        }
        args = args ? args.slice(0) : []; // Clone array to avoid changing the original
        options = options || {};
        // Build our parsed object
        parsed = {
            command: command,
            args: args,
            options: options,
            file: undefined,
            original: command,
        };
        // Delegate further parsing to shell or non-shell
        return options.shell ? parseShell(parsed) : parseNonShell(parsed);
    }
    module.exports = parse;
}
,
/* cross-spawn/lib/util/escapeArgument */ function _(require, module, exports) {
    function escapeArgument(arg, quote) {
        // Convert to string
        arg = '' + arg;
        // If we are not going to quote the argument,
        // escape shell metacharacters, including double and single quotes:
        if (!quote) {
            arg = arg.replace(/([()%!^<>&|;,"'\s])/g, '^$1');
        }
        else {
            // Sequence of backslashes followed by a double quote:
            // double up all the backslashes and escape the double quote
            arg = arg.replace(/(\\*)"/g, '$1$1\\"');
            // Sequence of backslashes followed by the end of the string
            // (which will become a double quote later):
            // double up all the backslashes
            arg = arg.replace(/(\\*)$/, '$1$1');
            // All other backslashes occur literally
            // Quote the whole thing:
            arg = '"' + arg + '"';
        }
        return arg;
    }
    module.exports = escapeArgument;
}
,
/* cross-spawn/lib/util/escapeCommand */ function _(require, module, exports) {
    var escapeArgument = require(92) /* ./escapeArgument */;
    function escapeCommand(command) {
        // Do not escape if this command is not dangerous..
        // We do this so that commands like "echo" or "ifconfig" work
        // Quoting them, will make them unaccessible
        return /^[a-z0-9_-]+$/i.test(command) ? command : escapeArgument(command, true);
    }
    module.exports = escapeCommand;
}
,
/* cross-spawn/lib/util/hasEmptyArgumentBug */ function _(require, module, exports) {
    // See: https://github.com/IndigoUnited/node-cross-spawn/pull/34#issuecomment-221623455
    function hasEmptyArgumentBug() {
        var nodeVer;
        if (process.platform !== 'win32') {
            return false;
        }
        nodeVer = process.version.substr(1).split('.').map(function (num) {
            return parseInt(num, 10);
        });
        return (nodeVer[0] === 0 && nodeVer[1] < 12);
    }
    module.exports = hasEmptyArgumentBug();
}
,
/* cross-spawn/lib/util/readShebang */ function _(require, module, exports) {
    var fs = require('fs');
    var LRU = require(97) /* lru-cache */;
    var shebangCommand = require(314) /* shebang-command */;
    var shebangCache = new LRU({ max: 50, maxAge: 30 * 1000 }); // Cache just for 30sec
    function readShebang(command) {
        var buffer;
        var fd;
        var shebang;
        // Check if it is in the cache first
        if (shebangCache.has(command)) {
            return shebangCache.get(command);
        }
        // Read the first 150 bytes from the file
        buffer = new Buffer(150);
        try {
            fd = fs.openSync(command, 'r');
            fs.readSync(fd, buffer, 0, 150, 0);
            fs.closeSync(fd);
        }
        catch (e) { /* empty */ }
        // Attempt to extract shebang (null is returned if not a shebang)
        shebang = shebangCommand(buffer.toString());
        // Store the shebang in the cache
        shebangCache.set(command, shebang);
        return shebang;
    }
    module.exports = readShebang;
}
,
/* cross-spawn/lib/util/resolveCommand */ function _(require, module, exports) {
    var path = require('path');
    var which = require(373) /* which */;
    var LRU = require(97) /* lru-cache */;
    var commandCache = new LRU({ max: 50, maxAge: 30 * 1000 }); // Cache just for 30sec
    function resolveCommand(command, noExtension) {
        var resolved;
        noExtension = !!noExtension;
        resolved = commandCache.get(command + '!' + noExtension);
        // Check if its resolved in the cache
        if (commandCache.has(command)) {
            return commandCache.get(command);
        }
        try {
            resolved = !noExtension ?
                which.sync(command) :
                which.sync(command, { pathExt: path.delimiter + (process.env.PATHEXT || '') });
        }
        catch (e) { /* empty */ }
        commandCache.set(command + '!' + noExtension, resolved);
        return resolved;
    }
    module.exports = resolveCommand;
}
,
/* cross-spawn/node_modules/lru-cache/index */ function _(require, module, exports) {
    module.exports = LRUCache;
    // This will be a proper iterable 'Map' in engines that support it,
    // or a fakey-fake PseudoMap in older versions.
    var Map = require(287) /* pseudomap */;
    var util = require('util');
    // A linked list to keep track of recently-used-ness
    var Yallist = require(376) /* yallist */;
    // use symbols if possible, otherwise just _props
    var hasSymbol = typeof Symbol === 'function';
    var makeSymbol;
    if (hasSymbol) {
        makeSymbol = function (key) {
            return Symbol(key);
        };
    }
    else {
        makeSymbol = function (key) {
            return '_' + key;
        };
    }
    var MAX = makeSymbol('max');
    var LENGTH = makeSymbol('length');
    var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
    var ALLOW_STALE = makeSymbol('allowStale');
    var MAX_AGE = makeSymbol('maxAge');
    var DISPOSE = makeSymbol('dispose');
    var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
    var LRU_LIST = makeSymbol('lruList');
    var CACHE = makeSymbol('cache');
    function naiveLength() { return 1; }
    // lruList is a yallist where the head is the youngest
    // item, and the tail is the oldest.  the list contains the Hit
    // objects as the entries.
    // Each Hit object has a reference to its Yallist.Node.  This
    // never changes.
    //
    // cache is a Map (or PseudoMap) that matches the keys to
    // the Yallist.Node object.
    function LRUCache(options) {
        if (!(this instanceof LRUCache)) {
            return new LRUCache(options);
        }
        if (typeof options === 'number') {
            options = { max: options };
        }
        if (!options) {
            options = {};
        }
        var max = this[MAX] = options.max;
        // Kind of weird to have a default max of Infinity, but oh well.
        if (!max ||
            !(typeof max === 'number') ||
            max <= 0) {
            this[MAX] = Infinity;
        }
        var lc = options.length || naiveLength;
        if (typeof lc !== 'function') {
            lc = naiveLength;
        }
        this[LENGTH_CALCULATOR] = lc;
        this[ALLOW_STALE] = options.stale || false;
        this[MAX_AGE] = options.maxAge || 0;
        this[DISPOSE] = options.dispose;
        this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
        this.reset();
    }
    // resize the cache when the max changes.
    Object.defineProperty(LRUCache.prototype, 'max', {
        set: function (mL) {
            if (!mL || !(typeof mL === 'number') || mL <= 0) {
                mL = Infinity;
            }
            this[MAX] = mL;
            trim(this);
        },
        get: function () {
            return this[MAX];
        },
        enumerable: true
    });
    Object.defineProperty(LRUCache.prototype, 'allowStale', {
        set: function (allowStale) {
            this[ALLOW_STALE] = !!allowStale;
        },
        get: function () {
            return this[ALLOW_STALE];
        },
        enumerable: true
    });
    Object.defineProperty(LRUCache.prototype, 'maxAge', {
        set: function (mA) {
            if (!mA || !(typeof mA === 'number') || mA < 0) {
                mA = 0;
            }
            this[MAX_AGE] = mA;
            trim(this);
        },
        get: function () {
            return this[MAX_AGE];
        },
        enumerable: true
    });
    // resize the cache when the lengthCalculator changes.
    Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
        set: function (lC) {
            if (typeof lC !== 'function') {
                lC = naiveLength;
            }
            if (lC !== this[LENGTH_CALCULATOR]) {
                this[LENGTH_CALCULATOR] = lC;
                this[LENGTH] = 0;
                this[LRU_LIST].forEach(function (hit) {
                    hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
                    this[LENGTH] += hit.length;
                }, this);
            }
            trim(this);
        },
        get: function () { return this[LENGTH_CALCULATOR]; },
        enumerable: true
    });
    Object.defineProperty(LRUCache.prototype, 'length', {
        get: function () { return this[LENGTH]; },
        enumerable: true
    });
    Object.defineProperty(LRUCache.prototype, 'itemCount', {
        get: function () { return this[LRU_LIST].length; },
        enumerable: true
    });
    LRUCache.prototype.rforEach = function (fn, thisp) {
        thisp = thisp || this;
        for (var walker = this[LRU_LIST].tail; walker !== null;) {
            var prev = walker.prev;
            forEachStep(this, fn, walker, thisp);
            walker = prev;
        }
    };
    function forEachStep(self, fn, node, thisp) {
        var hit = node.value;
        if (isStale(self, hit)) {
            del(self, node);
            if (!self[ALLOW_STALE]) {
                hit = undefined;
            }
        }
        if (hit) {
            fn.call(thisp, hit.value, hit.key, self);
        }
    }
    LRUCache.prototype.forEach = function (fn, thisp) {
        thisp = thisp || this;
        for (var walker = this[LRU_LIST].head; walker !== null;) {
            var next = walker.next;
            forEachStep(this, fn, walker, thisp);
            walker = next;
        }
    };
    LRUCache.prototype.keys = function () {
        return this[LRU_LIST].toArray().map(function (k) {
            return k.key;
        }, this);
    };
    LRUCache.prototype.values = function () {
        return this[LRU_LIST].toArray().map(function (k) {
            return k.value;
        }, this);
    };
    LRUCache.prototype.reset = function () {
        if (this[DISPOSE] &&
            this[LRU_LIST] &&
            this[LRU_LIST].length) {
            this[LRU_LIST].forEach(function (hit) {
                this[DISPOSE](hit.key, hit.value);
            }, this);
        }
        this[CACHE] = new Map(); // hash of items by key
        this[LRU_LIST] = new Yallist(); // list of items in order of use recency
        this[LENGTH] = 0; // length of items in the list
    };
    LRUCache.prototype.dump = function () {
        return this[LRU_LIST].map(function (hit) {
            if (!isStale(this, hit)) {
                return {
                    k: hit.key,
                    v: hit.value,
                    e: hit.now + (hit.maxAge || 0)
                };
            }
        }, this).toArray().filter(function (h) {
            return h;
        });
    };
    LRUCache.prototype.dumpLru = function () {
        return this[LRU_LIST];
    };
    LRUCache.prototype.inspect = function (n, opts) {
        var str = 'LRUCache {';
        var extras = false;
        var as = this[ALLOW_STALE];
        if (as) {
            str += '\n  allowStale: true';
            extras = true;
        }
        var max = this[MAX];
        if (max && max !== Infinity) {
            if (extras) {
                str += ',';
            }
            str += '\n  max: ' + util.inspect(max, opts);
            extras = true;
        }
        var maxAge = this[MAX_AGE];
        if (maxAge) {
            if (extras) {
                str += ',';
            }
            str += '\n  maxAge: ' + util.inspect(maxAge, opts);
            extras = true;
        }
        var lc = this[LENGTH_CALCULATOR];
        if (lc && lc !== naiveLength) {
            if (extras) {
                str += ',';
            }
            str += '\n  length: ' + util.inspect(this[LENGTH], opts);
            extras = true;
        }
        var didFirst = false;
        this[LRU_LIST].forEach(function (item) {
            if (didFirst) {
                str += ',\n  ';
            }
            else {
                if (extras) {
                    str += ',\n';
                }
                didFirst = true;
                str += '\n  ';
            }
            var key = util.inspect(item.key).split('\n').join('\n  ');
            var val = { value: item.value };
            if (item.maxAge !== maxAge) {
                val.maxAge = item.maxAge;
            }
            if (lc !== naiveLength) {
                val.length = item.length;
            }
            if (isStale(this, item)) {
                val.stale = true;
            }
            val = util.inspect(val, opts).split('\n').join('\n  ');
            str += key + ' => ' + val;
        });
        if (didFirst || extras) {
            str += '\n';
        }
        str += '}';
        return str;
    };
    LRUCache.prototype.set = function (key, value, maxAge) {
        maxAge = maxAge || this[MAX_AGE];
        var now = maxAge ? Date.now() : 0;
        var len = this[LENGTH_CALCULATOR](value, key);
        if (this[CACHE].has(key)) {
            if (len > this[MAX]) {
                del(this, this[CACHE].get(key));
                return false;
            }
            var node = this[CACHE].get(key);
            var item = node.value;
            // dispose of the old one before overwriting
            // split out into 2 ifs for better coverage tracking
            if (this[DISPOSE]) {
                if (!this[NO_DISPOSE_ON_SET]) {
                    this[DISPOSE](key, item.value);
                }
            }
            item.now = now;
            item.maxAge = maxAge;
            item.value = value;
            this[LENGTH] += len - item.length;
            item.length = len;
            this.get(key);
            trim(this);
            return true;
        }
        var hit = new Entry(key, value, len, now, maxAge);
        // oversized objects fall out of cache automatically.
        if (hit.length > this[MAX]) {
            if (this[DISPOSE]) {
                this[DISPOSE](key, value);
            }
            return false;
        }
        this[LENGTH] += hit.length;
        this[LRU_LIST].unshift(hit);
        this[CACHE].set(key, this[LRU_LIST].head);
        trim(this);
        return true;
    };
    LRUCache.prototype.has = function (key) {
        if (!this[CACHE].has(key))
            return false;
        var hit = this[CACHE].get(key).value;
        if (isStale(this, hit)) {
            return false;
        }
        return true;
    };
    LRUCache.prototype.get = function (key) {
        return get(this, key, true);
    };
    LRUCache.prototype.peek = function (key) {
        return get(this, key, false);
    };
    LRUCache.prototype.pop = function () {
        var node = this[LRU_LIST].tail;
        if (!node)
            return null;
        del(this, node);
        return node.value;
    };
    LRUCache.prototype.del = function (key) {
        del(this, this[CACHE].get(key));
    };
    LRUCache.prototype.load = function (arr) {
        // reset the cache
        this.reset();
        var now = Date.now();
        // A previous serialized cache has the most recent items first
        for (var l = arr.length - 1; l >= 0; l--) {
            var hit = arr[l];
            var expiresAt = hit.e || 0;
            if (expiresAt === 0) {
                // the item was created without expiration in a non aged cache
                this.set(hit.k, hit.v);
            }
            else {
                var maxAge = expiresAt - now;
                // dont add already expired items
                if (maxAge > 0) {
                    this.set(hit.k, hit.v, maxAge);
                }
            }
        }
    };
    LRUCache.prototype.prune = function () {
        var self = this;
        this[CACHE].forEach(function (value, key) {
            get(self, key, false);
        });
    };
    function get(self, key, doUse) {
        var node = self[CACHE].get(key);
        if (node) {
            var hit = node.value;
            if (isStale(self, hit)) {
                del(self, node);
                if (!self[ALLOW_STALE])
                    hit = undefined;
            }
            else {
                if (doUse) {
                    self[LRU_LIST].unshiftNode(node);
                }
            }
            if (hit)
                hit = hit.value;
        }
        return hit;
    }
    function isStale(self, hit) {
        if (!hit || (!hit.maxAge && !self[MAX_AGE])) {
            return false;
        }
        var stale = false;
        var diff = Date.now() - hit.now;
        if (hit.maxAge) {
            stale = diff > hit.maxAge;
        }
        else {
            stale = self[MAX_AGE] && (diff > self[MAX_AGE]);
        }
        return stale;
    }
    function trim(self) {
        if (self[LENGTH] > self[MAX]) {
            for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
                // We know that we're about to delete this one, and also
                // what the next least recently used key will be, so just
                // go ahead and set it now.
                var prev = walker.prev;
                del(self, walker);
                walker = prev;
            }
        }
    }
    function del(self, node) {
        if (node) {
            var hit = node.value;
            if (self[DISPOSE]) {
                self[DISPOSE](hit.key, hit.value);
            }
            self[LENGTH] -= hit.length;
            self[CACHE].delete(hit.key);
            self[LRU_LIST].removeNode(node);
        }
    }
    // classy, since V8 prefers predictable objects.
    function Entry(key, value, length, now, maxAge) {
        this.key = key;
        this.value = value;
        this.length = length;
        this.now = now;
        this.maxAge = maxAge || 0;
    }
}
,
/* decamelize/index */ function _(require, module, exports) {
    module.exports = function (str, sep) {
        if (typeof str !== 'string') {
            throw new TypeError('Expected a string');
        }
        sep = typeof sep === 'undefined' ? '_' : sep;
        return str
            .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2')
            .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2')
            .toLowerCase();
    };
}
,
/* delayed-stream/lib/delayed_stream */ function _(require, module, exports) {
    var Stream = require('stream').Stream;
    var util = require('util');
    module.exports = DelayedStream;
    function DelayedStream() {
        this.source = null;
        this.dataSize = 0;
        this.maxDataSize = 1024 * 1024;
        this.pauseStream = true;
        this._maxDataSizeExceeded = false;
        this._released = false;
        this._bufferedEvents = [];
    }
    util.inherits(DelayedStream, Stream);
    DelayedStream.create = function (source, options) {
        var delayedStream = new this();
        options = options || {};
        for (var option in options) {
            delayedStream[option] = options[option];
        }
        delayedStream.source = source;
        var realEmit = source.emit;
        source.emit = function () {
            delayedStream._handleEmit(arguments);
            return realEmit.apply(source, arguments);
        };
        source.on('error', function () { });
        if (delayedStream.pauseStream) {
            source.pause();
        }
        return delayedStream;
    };
    Object.defineProperty(DelayedStream.prototype, 'readable', {
        configurable: true,
        enumerable: true,
        get: function () {
            return this.source.readable;
        }
    });
    DelayedStream.prototype.setEncoding = function () {
        return this.source.setEncoding.apply(this.source, arguments);
    };
    DelayedStream.prototype.resume = function () {
        if (!this._released) {
            this.release();
        }
        this.source.resume();
    };
    DelayedStream.prototype.pause = function () {
        this.source.pause();
    };
    DelayedStream.prototype.release = function () {
        this._released = true;
        this._bufferedEvents.forEach(function (args) {
            this.emit.apply(this, args);
        }.bind(this));
        this._bufferedEvents = [];
    };
    DelayedStream.prototype.pipe = function () {
        var r = Stream.prototype.pipe.apply(this, arguments);
        this.resume();
        return r;
    };
    DelayedStream.prototype._handleEmit = function (args) {
        if (this._released) {
            this.emit.apply(this, args);
            return;
        }
        if (args[0] === 'data') {
            this.dataSize += args[1].length;
            this._checkIfMaxDataSizeExceeded();
        }
        this._bufferedEvents.push(args);
    };
    DelayedStream.prototype._checkIfMaxDataSizeExceeded = function () {
        if (this._maxDataSizeExceeded) {
            return;
        }
        if (this.dataSize <= this.maxDataSize) {
            return;
        }
        this._maxDataSizeExceeded = true;
        var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
        this.emit('error', new Error(message));
    };
}
,
/* ecc-jsbn/index */ function _(require, module, exports) {
    var crypto = require("crypto");
    var BigInteger = require(155) /* jsbn */.BigInteger;
    var ECPointFp = require(101) /* ./lib/ec.js */.ECPointFp;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    exports.ECCurves = require(102) /* ./lib/sec.js */;
    // zero prepad
    function unstupid(hex, len) {
        return (hex.length >= len) ? hex : unstupid("0" + hex, len);
    }
    exports.ECKey = function (curve, key, isPublic) {
        var priv;
        var c = curve();
        var n = c.getN();
        var bytes = Math.floor(n.bitLength() / 8);
        if (key) {
            if (isPublic) {
                var curve = c.getCurve();
                //      var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format
                //      var y = key.slice(bytes+1);
                //      this.P = new ECPointFp(curve,
                //        curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)),
                //        curve.fromBigInteger(new BigInteger(y.toString("hex"), 16)));      
                this.P = curve.decodePointHex(key.toString("hex"));
            }
            else {
                if (key.length != bytes)
                    return false;
                priv = new BigInteger(key.toString("hex"), 16);
            }
        }
        else {
            var n1 = n.subtract(BigInteger.ONE);
            var r = new BigInteger(crypto.randomBytes(n.bitLength()));
            priv = r.mod(n1).add(BigInteger.ONE);
            this.P = c.getG().multiply(priv);
        }
        if (this.P) {
            //  var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2);
            //  this.PublicKey = Buffer.from("04"+pubhex,"hex");
            this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P), "hex");
        }
        if (priv) {
            this.PrivateKey = Buffer.from(unstupid(priv.toString(16), bytes * 2), "hex");
            this.deriveSharedSecret = function (key) {
                if (!key || !key.P)
                    return false;
                var S = key.P.multiply(priv);
                return Buffer.from(unstupid(S.getX().toBigInteger().toString(16), bytes * 2), "hex");
            };
        }
    };
}
,
/* ecc-jsbn/lib/ec */ function _(require, module, exports) {
    // Basic Javascript Elliptic Curve implementation
    // Ported loosely from BouncyCastle's Java EC code
    // Only Fp curves implemented for now
    // Requires jsbn.js and jsbn2.js
    var BigInteger = require(155) /* jsbn */.BigInteger;
    var Barrett = BigInteger.prototype.Barrett;
    // ----------------
    // ECFieldElementFp
    // constructor
    function ECFieldElementFp(q, x) {
        this.x = x;
        // TODO if(x.compareTo(q) >= 0) error
        this.q = q;
    }
    function feFpEquals(other) {
        if (other == this)
            return true;
        return (this.q.equals(other.q) && this.x.equals(other.x));
    }
    function feFpToBigInteger() {
        return this.x;
    }
    function feFpNegate() {
        return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
    }
    function feFpAdd(b) {
        return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
    }
    function feFpSubtract(b) {
        return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
    }
    function feFpMultiply(b) {
        return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
    }
    function feFpSquare() {
        return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
    }
    function feFpDivide(b) {
        return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
    }
    ECFieldElementFp.prototype.equals = feFpEquals;
    ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger;
    ECFieldElementFp.prototype.negate = feFpNegate;
    ECFieldElementFp.prototype.add = feFpAdd;
    ECFieldElementFp.prototype.subtract = feFpSubtract;
    ECFieldElementFp.prototype.multiply = feFpMultiply;
    ECFieldElementFp.prototype.square = feFpSquare;
    ECFieldElementFp.prototype.divide = feFpDivide;
    // ----------------
    // ECPointFp
    // constructor
    function ECPointFp(curve, x, y, z) {
        this.curve = curve;
        this.x = x;
        this.y = y;
        // Projective coordinates: either zinv == null or z * zinv == 1
        // z and zinv are just BigIntegers, not fieldElements
        if (z == null) {
            this.z = BigInteger.ONE;
        }
        else {
            this.z = z;
        }
        this.zinv = null;
        //TODO: compression flag
    }
    function pointFpGetX() {
        if (this.zinv == null) {
            this.zinv = this.z.modInverse(this.curve.q);
        }
        var r = this.x.toBigInteger().multiply(this.zinv);
        this.curve.reduce(r);
        return this.curve.fromBigInteger(r);
    }
    function pointFpGetY() {
        if (this.zinv == null) {
            this.zinv = this.z.modInverse(this.curve.q);
        }
        var r = this.y.toBigInteger().multiply(this.zinv);
        this.curve.reduce(r);
        return this.curve.fromBigInteger(r);
    }
    function pointFpEquals(other) {
        if (other == this)
            return true;
        if (this.isInfinity())
            return other.isInfinity();
        if (other.isInfinity())
            return this.isInfinity();
        var u, v;
        // u = Y2 * Z1 - Y1 * Z2
        u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
        if (!u.equals(BigInteger.ZERO))
            return false;
        // v = X2 * Z1 - X1 * Z2
        v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
        return v.equals(BigInteger.ZERO);
    }
    function pointFpIsInfinity() {
        if ((this.x == null) && (this.y == null))
            return true;
        return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
    }
    function pointFpNegate() {
        return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
    }
    function pointFpAdd(b) {
        if (this.isInfinity())
            return b;
        if (b.isInfinity())
            return this;
        // u = Y2 * Z1 - Y1 * Z2
        var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q);
        // v = X2 * Z1 - X1 * Z2
        var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q);
        if (BigInteger.ZERO.equals(v)) {
            if (BigInteger.ZERO.equals(u)) {
                return this.twice(); // this == b, so double
            }
            return this.curve.getInfinity(); // this = -b, so infinity
        }
        var THREE = new BigInteger("3");
        var x1 = this.x.toBigInteger();
        var y1 = this.y.toBigInteger();
        var x2 = b.x.toBigInteger();
        var y2 = b.y.toBigInteger();
        var v2 = v.square();
        var v3 = v2.multiply(v);
        var x1v2 = x1.multiply(v2);
        var zu2 = u.square().multiply(this.z);
        // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
        var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q);
        // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
        var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q);
        // z3 = v^3 * z1 * z2
        var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q);
        return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
    }
    function pointFpTwice() {
        if (this.isInfinity())
            return this;
        if (this.y.toBigInteger().signum() == 0)
            return this.curve.getInfinity();
        // TODO: optimized handling of constants
        var THREE = new BigInteger("3");
        var x1 = this.x.toBigInteger();
        var y1 = this.y.toBigInteger();
        var y1z1 = y1.multiply(this.z);
        var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q);
        var a = this.curve.a.toBigInteger();
        // w = 3 * x1^2 + a * z1^2
        var w = x1.square().multiply(THREE);
        if (!BigInteger.ZERO.equals(a)) {
            w = w.add(this.z.square().multiply(a));
        }
        w = w.mod(this.curve.q);
        //this.curve.reduce(w);
        // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
        var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q);
        // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
        var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q);
        // z3 = 8 * (y1 * z1)^3
        var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q);
        return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
    }
    // Simple NAF (Non-Adjacent Form) multiplication algorithm
    // TODO: modularize the multiplication algorithm
    function pointFpMultiply(k) {
        if (this.isInfinity())
            return this;
        if (k.signum() == 0)
            return this.curve.getInfinity();
        var e = k;
        var h = e.multiply(new BigInteger("3"));
        var neg = this.negate();
        var R = this;
        var i;
        for (i = h.bitLength() - 2; i > 0; --i) {
            R = R.twice();
            var hBit = h.testBit(i);
            var eBit = e.testBit(i);
            if (hBit != eBit) {
                R = R.add(hBit ? this : neg);
            }
        }
        return R;
    }
    // Compute this*j + x*k (simultaneous multiplication)
    function pointFpMultiplyTwo(j, x, k) {
        var i;
        if (j.bitLength() > k.bitLength())
            i = j.bitLength() - 1;
        else
            i = k.bitLength() - 1;
        var R = this.curve.getInfinity();
        var both = this.add(x);
        while (i >= 0) {
            R = R.twice();
            if (j.testBit(i)) {
                if (k.testBit(i)) {
                    R = R.add(both);
                }
                else {
                    R = R.add(this);
                }
            }
            else {
                if (k.testBit(i)) {
                    R = R.add(x);
                }
            }
            --i;
        }
        return R;
    }
    ECPointFp.prototype.getX = pointFpGetX;
    ECPointFp.prototype.getY = pointFpGetY;
    ECPointFp.prototype.equals = pointFpEquals;
    ECPointFp.prototype.isInfinity = pointFpIsInfinity;
    ECPointFp.prototype.negate = pointFpNegate;
    ECPointFp.prototype.add = pointFpAdd;
    ECPointFp.prototype.twice = pointFpTwice;
    ECPointFp.prototype.multiply = pointFpMultiply;
    ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo;
    // ----------------
    // ECCurveFp
    // constructor
    function ECCurveFp(q, a, b) {
        this.q = q;
        this.a = this.fromBigInteger(a);
        this.b = this.fromBigInteger(b);
        this.infinity = new ECPointFp(this, null, null);
        this.reducer = new Barrett(this.q);
    }
    function curveFpGetQ() {
        return this.q;
    }
    function curveFpGetA() {
        return this.a;
    }
    function curveFpGetB() {
        return this.b;
    }
    function curveFpEquals(other) {
        if (other == this)
            return true;
        return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b));
    }
    function curveFpGetInfinity() {
        return this.infinity;
    }
    function curveFpFromBigInteger(x) {
        return new ECFieldElementFp(this.q, x);
    }
    function curveReduce(x) {
        this.reducer.reduce(x);
    }
    // for now, work with hex strings because they're easier in JS
    function curveFpDecodePointHex(s) {
        switch (parseInt(s.substr(0, 2), 16)) { // first byte
            case 0:
                return this.infinity;
            case 2:
            case 3:
                // point compression not supported yet
                return null;
            case 4:
            case 6:
            case 7:
                var len = (s.length - 2) / 2;
                var xHex = s.substr(2, len);
                var yHex = s.substr(len + 2, len);
                return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16)));
            default: // unsupported
                return null;
        }
    }
    function curveFpEncodePointHex(p) {
        if (p.isInfinity())
            return "00";
        var xHex = p.getX().toBigInteger().toString(16);
        var yHex = p.getY().toBigInteger().toString(16);
        var oLen = this.getQ().toString(16).length;
        if ((oLen % 2) != 0)
            oLen++;
        while (xHex.length < oLen) {
            xHex = "0" + xHex;
        }
        while (yHex.length < oLen) {
            yHex = "0" + yHex;
        }
        return "04" + xHex + yHex;
    }
    ECCurveFp.prototype.getQ = curveFpGetQ;
    ECCurveFp.prototype.getA = curveFpGetA;
    ECCurveFp.prototype.getB = curveFpGetB;
    ECCurveFp.prototype.equals = curveFpEquals;
    ECCurveFp.prototype.getInfinity = curveFpGetInfinity;
    ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger;
    ECCurveFp.prototype.reduce = curveReduce;
    //ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex;
    ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex;
    // from: https://github.com/kaielvin/jsbn-ec-point-compression
    ECCurveFp.prototype.decodePointHex = function (s) {
        var yIsEven;
        switch (parseInt(s.substr(0, 2), 16)) { // first byte
            case 0:
                return this.infinity;
            case 2:
                yIsEven = false;
            case 3:
                if (yIsEven == undefined)
                    yIsEven = true;
                var len = s.length - 2;
                var xHex = s.substr(2, len);
                var x = this.fromBigInteger(new BigInteger(xHex, 16));
                var alpha = x.multiply(x.square().add(this.getA())).add(this.getB());
                var beta = alpha.sqrt();
                if (beta == null)
                    throw "Invalid point compression";
                var betaValue = beta.toBigInteger();
                if (betaValue.testBit(0) != yIsEven) {
                    // Use the other root
                    beta = this.fromBigInteger(this.getQ().subtract(betaValue));
                }
                return new ECPointFp(this, x, beta);
            case 4:
            case 6:
            case 7:
                var len = (s.length - 2) / 2;
                var xHex = s.substr(2, len);
                var yHex = s.substr(len + 2, len);
                return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16)));
            default: // unsupported
                return null;
        }
    };
    ECCurveFp.prototype.encodeCompressedPointHex = function (p) {
        if (p.isInfinity())
            return "00";
        var xHex = p.getX().toBigInteger().toString(16);
        var oLen = this.getQ().toString(16).length;
        if ((oLen % 2) != 0)
            oLen++;
        while (xHex.length < oLen)
            xHex = "0" + xHex;
        var yPrefix;
        if (p.getY().toBigInteger().isEven())
            yPrefix = "02";
        else
            yPrefix = "03";
        return yPrefix + xHex;
    };
    ECFieldElementFp.prototype.getR = function () {
        if (this.r != undefined)
            return this.r;
        this.r = null;
        var bitLength = this.q.bitLength();
        if (bitLength > 128) {
            var firstWord = this.q.shiftRight(bitLength - 64);
            if (firstWord.intValue() == -1) {
                this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q);
            }
        }
        return this.r;
    };
    ECFieldElementFp.prototype.modMult = function (x1, x2) {
        return this.modReduce(x1.multiply(x2));
    };
    ECFieldElementFp.prototype.modReduce = function (x) {
        if (this.getR() != null) {
            var qLen = q.bitLength();
            while (x.bitLength() > (qLen + 1)) {
                var u = x.shiftRight(qLen);
                var v = x.subtract(u.shiftLeft(qLen));
                if (!this.getR().equals(BigInteger.ONE)) {
                    u = u.multiply(this.getR());
                }
                x = u.add(v);
            }
            while (x.compareTo(q) >= 0) {
                x = x.subtract(q);
            }
        }
        else {
            x = x.mod(q);
        }
        return x;
    };
    ECFieldElementFp.prototype.sqrt = function () {
        if (!this.q.testBit(0))
            throw "unsupported";
        // p mod 4 == 3
        if (this.q.testBit(1)) {
            var z = new ECFieldElementFp(this.q, this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE), this.q));
            return z.square().equals(this) ? z : null;
        }
        // p mod 4 == 1
        var qMinusOne = this.q.subtract(BigInteger.ONE);
        var legendreExponent = qMinusOne.shiftRight(1);
        if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) {
            return null;
        }
        var u = qMinusOne.shiftRight(2);
        var k = u.shiftLeft(1).add(BigInteger.ONE);
        var Q = this.x;
        var fourQ = modDouble(modDouble(Q));
        var U, V;
        do {
            var P;
            do {
                P = new BigInteger(this.q.bitLength(), new SecureRandom());
            } while (P.compareTo(this.q) >= 0
                || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne)));
            var result = this.lucasSequence(P, Q, k);
            U = result[0];
            V = result[1];
            if (this.modMult(V, V).equals(fourQ)) {
                // Integer division by 2, mod q
                if (V.testBit(0)) {
                    V = V.add(q);
                }
                V = V.shiftRight(1);
                return new ECFieldElementFp(q, V);
            }
        } while (U.equals(BigInteger.ONE) || U.equals(qMinusOne));
        return null;
    };
    ECFieldElementFp.prototype.lucasSequence = function (P, Q, k) {
        var n = k.bitLength();
        var s = k.getLowestSetBit();
        var Uh = BigInteger.ONE;
        var Vl = BigInteger.TWO;
        var Vh = P;
        var Ql = BigInteger.ONE;
        var Qh = BigInteger.ONE;
        for (var j = n - 1; j >= s + 1; --j) {
            Ql = this.modMult(Ql, Qh);
            if (k.testBit(j)) {
                Qh = this.modMult(Ql, Q);
                Uh = this.modMult(Uh, Vh);
                Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
                Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
            }
            else {
                Qh = Ql;
                Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
                Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
                Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
            }
        }
        Ql = this.modMult(Ql, Qh);
        Qh = this.modMult(Ql, Q);
        Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
        Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
        Ql = this.modMult(Ql, Qh);
        for (var j = 1; j <= s; ++j) {
            Uh = this.modMult(Uh, Vl);
            Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
            Ql = this.modMult(Ql, Ql);
        }
        return [Uh, Vl];
    };
    var exports = {
        ECCurveFp: ECCurveFp,
        ECPointFp: ECPointFp,
        ECFieldElementFp: ECFieldElementFp
    };
    module.exports = exports;
}
,
/* ecc-jsbn/lib/sec */ function _(require, module, exports) {
    // Named EC curves
    // Requires ec.js, jsbn.js, and jsbn2.js
    var BigInteger = require(155) /* jsbn */.BigInteger;
    var ECCurveFp = require(101) /* ./ec.js */.ECCurveFp;
    // ----------------
    // X9ECParameters
    // constructor
    function X9ECParameters(curve, g, n, h) {
        this.curve = curve;
        this.g = g;
        this.n = n;
        this.h = h;
    }
    function x9getCurve() {
        return this.curve;
    }
    function x9getG() {
        return this.g;
    }
    function x9getN() {
        return this.n;
    }
    function x9getH() {
        return this.h;
    }
    X9ECParameters.prototype.getCurve = x9getCurve;
    X9ECParameters.prototype.getG = x9getG;
    X9ECParameters.prototype.getN = x9getN;
    X9ECParameters.prototype.getH = x9getH;
    // ----------------
    // SECNamedCurves
    function fromHex(s) { return new BigInteger(s, 16); }
    function secp128r1() {
        // p = 2^128 - 2^97 - 1
        var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
        var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
        var b = fromHex("E87579C11079F43DD824993C2CEE5ED3");
        //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679");
        var n = fromHex("FFFFFFFE0000000075A30D1B9038A115");
        var h = BigInteger.ONE;
        var curve = new ECCurveFp(p, a, b);
        var G = curve.decodePointHex("04"
            + "161FF7528B899B2D0C28607CA52C5B86"
            + "CF5AC8395BAFEB13C02DA292DDED7A83");
        return new X9ECParameters(curve, G, n, h);
    }
    function secp160k1() {
        // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
        var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
        var a = BigInteger.ZERO;
        var b = fromHex("7");
        //byte[] S = null;
        var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
        var h = BigInteger.ONE;
        var curve = new ECCurveFp(p, a, b);
        var G = curve.decodePointHex("04"
            + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
            + "938CF935318FDCED6BC28286531733C3F03C4FEE");
        return new X9ECParameters(curve, G, n, h);
    }
    function secp160r1() {
        // p = 2^160 - 2^31 - 1
        var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
        var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
        var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
        //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345");
        var n = fromHex("0100000000000000000001F4C8F927AED3CA752257");
        var h = BigInteger.ONE;
        var curve = new ECCurveFp(p, a, b);
        var G = curve.decodePointHex("04"
            + "4A96B5688EF573284664698968C38BB913CBFC82"
            + "23A628553168947D59DCC912042351377AC5FB32");
        return new X9ECParameters(curve, G, n, h);
    }
    function secp192k1() {
        // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
        var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
        var a = BigInteger.ZERO;
        var b = fromHex("3");
        //byte[] S = null;
        var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
        var h = BigInteger.ONE;
        var curve = new ECCurveFp(p, a, b);
        var G = curve.decodePointHex("04"
            + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
            + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
        return new X9ECParameters(curve, G, n, h);
    }
    function secp192r1() {
        // p = 2^192 - 2^64 - 1
        var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
        var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
        var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
        //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
        var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
        var h = BigInteger.ONE;
        var curve = new ECCurveFp(p, a, b);
        var G = curve.decodePointHex("04"
            + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
            + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
        return new X9ECParameters(curve, G, n, h);
    }
    function secp224r1() {
        // p = 2^224 - 2^96 + 1
        var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
        var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
        var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
        //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
        var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
        var h = BigInteger.ONE;
        var curve = new ECCurveFp(p, a, b);
        var G = curve.decodePointHex("04"
            + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
            + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
        return new X9ECParameters(curve, G, n, h);
    }
    function secp256r1() {
        // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
        var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
        var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
        var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
        //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90");
        var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
        var h = BigInteger.ONE;
        var curve = new ECCurveFp(p, a, b);
        var G = curve.decodePointHex("04"
            + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
            + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
        return new X9ECParameters(curve, G, n, h);
    }
    // TODO: make this into a proper hashtable
    function getSECCurveByName(name) {
        if (name == "secp128r1")
            return secp128r1();
        if (name == "secp160k1")
            return secp160k1();
        if (name == "secp160r1")
            return secp160r1();
        if (name == "secp192k1")
            return secp192k1();
        if (name == "secp192r1")
            return secp192r1();
        if (name == "secp224r1")
            return secp224r1();
        if (name == "secp256r1")
            return secp256r1();
        return null;
    }
    module.exports = {
        "secp128r1": secp128r1,
        "secp160k1": secp160k1,
        "secp160r1": secp160r1,
        "secp192k1": secp192k1,
        "secp192r1": secp192r1,
        "secp224r1": secp224r1,
        "secp256r1": secp256r1
    };
}
,
/* execa/index */ function _(require, module, exports) {
    const childProcess = require('child_process');
    const util = require('util');
    const crossSpawn = require(89) /* cross-spawn */;
    const stripEof = require(357) /* strip-eof */;
    const npmRunPath = require(269) /* npm-run-path */;
    const isStream = require(149) /* is-stream */;
    const _getStream = require(116) /* get-stream */;
    const pFinally = require(272) /* p-finally */;
    const onExit = require(316) /* signal-exit */;
    const errname = require(104) /* ./lib/errname */;
    const stdio = require(105) /* ./lib/stdio */;
    const TEN_MEGABYTES = 1000 * 1000 * 10;
    function handleArgs(cmd, args, opts) {
        let parsed;
        if (opts && opts.env && opts.extendEnv !== false) {
            opts.env = Object.assign({}, process.env, opts.env);
        }
        if (opts && opts.__winShell === true) {
            delete opts.__winShell;
            parsed = {
                command: cmd,
                args,
                options: opts,
                file: cmd,
                original: cmd
            };
        }
        else {
            parsed = crossSpawn._parse(cmd, args, opts);
        }
        opts = Object.assign({
            maxBuffer: TEN_MEGABYTES,
            stripEof: true,
            preferLocal: true,
            localDir: parsed.options.cwd || process.cwd(),
            encoding: 'utf8',
            reject: true,
            cleanup: true
        }, parsed.options);
        opts.stdio = stdio(opts);
        if (opts.preferLocal) {
            opts.env = npmRunPath.env(Object.assign({}, opts, { cwd: opts.localDir }));
        }
        return {
            cmd: parsed.command,
            args: parsed.args,
            opts,
            parsed
        };
    }
    function handleInput(spawned, opts) {
        const input = opts.input;
        if (input === null || input === undefined) {
            return;
        }
        if (isStream(input)) {
            input.pipe(spawned.stdin);
        }
        else {
            spawned.stdin.end(input);
        }
    }
    function handleOutput(opts, val) {
        if (val && opts.stripEof) {
            val = stripEof(val);
        }
        return val;
    }
    function handleShell(fn, cmd, opts) {
        let file = '/bin/sh';
        let args = ['-c', cmd];
        opts = Object.assign({}, opts);
        if (process.platform === 'win32') {
            opts.__winShell = true;
            file = process.env.comspec || 'cmd.exe';
            args = ['/s', '/c', `"${cmd}"`];
            opts.windowsVerbatimArguments = true;
        }
        if (opts.shell) {
            file = opts.shell;
            delete opts.shell;
        }
        return fn(file, args, opts);
    }
    function getStream(process, stream, encoding, maxBuffer) {
        if (!process[stream]) {
            return null;
        }
        let ret;
        if (encoding) {
            ret = _getStream(process[stream], {
                encoding,
                maxBuffer
            });
        }
        else {
            ret = _getStream.buffer(process[stream], { maxBuffer });
        }
        return ret.catch(err => {
            err.stream = stream;
            err.message = `${stream} ${err.message}`;
            throw err;
        });
    }
    module.exports = (cmd, args, opts) => {
        let joinedCmd = cmd;
        if (Array.isArray(args) && args.length > 0) {
            joinedCmd += ' ' + args.join(' ');
        }
        const parsed = handleArgs(cmd, args, opts);
        const encoding = parsed.opts.encoding;
        const maxBuffer = parsed.opts.maxBuffer;
        let spawned;
        try {
            spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts);
        }
        catch (err) {
            return Promise.reject(err);
        }
        let removeExitHandler;
        if (parsed.opts.cleanup) {
            removeExitHandler = onExit(() => {
                spawned.kill();
            });
        }
        let timeoutId = null;
        let timedOut = false;
        const cleanupTimeout = () => {
            if (timeoutId) {
                clearTimeout(timeoutId);
                timeoutId = null;
            }
        };
        if (parsed.opts.timeout > 0) {
            timeoutId = setTimeout(() => {
                timeoutId = null;
                timedOut = true;
                spawned.kill(parsed.opts.killSignal);
            }, parsed.opts.timeout);
        }
        const processDone = new Promise(resolve => {
            spawned.on('exit', (code, signal) => {
                cleanupTimeout();
                resolve({ code, signal });
            });
            spawned.on('error', err => {
                cleanupTimeout();
                resolve({ err });
            });
            if (spawned.stdin) {
                spawned.stdin.on('error', err => {
                    cleanupTimeout();
                    resolve({ err });
                });
            }
        });
        function destroy() {
            if (spawned.stdout) {
                spawned.stdout.destroy();
            }
            if (spawned.stderr) {
                spawned.stderr.destroy();
            }
        }
        const promise = pFinally(Promise.all([
            processDone,
            getStream(spawned, 'stdout', encoding, maxBuffer),
            getStream(spawned, 'stderr', encoding, maxBuffer)
        ]).then(arr => {
            const result = arr[0];
            const stdout = arr[1];
            const stderr = arr[2];
            let err = result.err;
            const code = result.code;
            const signal = result.signal;
            if (removeExitHandler) {
                removeExitHandler();
            }
            if (err || code !== 0 || signal !== null) {
                if (!err) {
                    let output = '';
                    if (Array.isArray(parsed.opts.stdio)) {
                        if (parsed.opts.stdio[2] !== 'inherit') {
                            output += output.length > 0 ? stderr : `\n${stderr}`;
                        }
                        if (parsed.opts.stdio[1] !== 'inherit') {
                            output += `\n${stdout}`;
                        }
                    }
                    else if (parsed.opts.stdio !== 'inherit') {
                        output = `\n${stderr}${stdout}`;
                    }
                    err = new Error(`Command failed: ${joinedCmd}${output}`);
                    err.code = code < 0 ? errname(code) : code;
                }
                // TODO: missing some timeout logic for killed
                // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203
                // err.killed = spawned.killed || killed;
                err.killed = err.killed || spawned.killed;
                err.stdout = stdout;
                err.stderr = stderr;
                err.failed = true;
                err.signal = signal || null;
                err.cmd = joinedCmd;
                err.timedOut = timedOut;
                if (!parsed.opts.reject) {
                    return err;
                }
                throw err;
            }
            return {
                stdout: handleOutput(parsed.opts, stdout),
                stderr: handleOutput(parsed.opts, stderr),
                code: 0,
                failed: false,
                killed: false,
                signal: null,
                cmd: joinedCmd,
                timedOut: false
            };
        }), destroy);
        crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
        handleInput(spawned, parsed.opts);
        spawned.then = promise.then.bind(promise);
        spawned.catch = promise.catch.bind(promise);
        return spawned;
    };
    module.exports.stdout = function () {
        // TODO: set `stderr: 'ignore'` when that option is implemented
        return module.exports.apply(null, arguments).then(x => x.stdout);
    };
    module.exports.stderr = function () {
        // TODO: set `stdout: 'ignore'` when that option is implemented
        return module.exports.apply(null, arguments).then(x => x.stderr);
    };
    module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts);
    module.exports.sync = (cmd, args, opts) => {
        const parsed = handleArgs(cmd, args, opts);
        if (isStream(parsed.opts.input)) {
            throw new TypeError('The `input` option cannot be a stream in sync mode');
        }
        const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts);
        if (result.error || result.status !== 0) {
            throw (result.error || new Error(result.stderr === '' ? result.stdout : result.stderr));
        }
        result.stdout = handleOutput(parsed.opts, result.stdout);
        result.stderr = handleOutput(parsed.opts, result.stderr);
        return result;
    };
    module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts);
    module.exports.spawn = util.deprecate(module.exports, 'execa.spawn() is deprecated. Use execa() instead.');
}
,
/* execa/lib/errname */ function _(require, module, exports) {
    // The Node team wants to deprecate `process.bind(...)`.
    //   https://github.com/nodejs/node/pull/2768
    //
    // However, we need the 'uv' binding for errname support.
    // This is a defensive wrapper around it so `execa` will not fail entirely if it stops working someday.
    //
    // If this ever stops working. See: https://github.com/sindresorhus/execa/issues/31#issuecomment-215939939 for another possible solution.
    let uv;
    try {
        uv = process.binding('uv');
        if (typeof uv.errname !== 'function') {
            throw new TypeError('uv.errname is not a function');
        }
    }
    catch (err) {
        console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err);
        uv = null;
    }
    function errname(uv, code) {
        if (uv) {
            return uv.errname(code);
        }
        if (!(code < 0)) {
            throw new Error('err >= 0');
        }
        return `Unknown system error ${code}`;
    }
    module.exports = code => errname(uv, code);
    // Used for testing the fallback behavior
    module.exports.__test__ = errname;
}
,
/* execa/lib/stdio */ function _(require, module, exports) {
    const alias = ['stdin', 'stdout', 'stderr'];
    const hasAlias = opts => alias.some(x => Boolean(opts[x]));
    module.exports = opts => {
        if (!opts) {
            return null;
        }
        if (opts.stdio && hasAlias(opts)) {
            throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`);
        }
        if (typeof opts.stdio === 'string') {
            return opts.stdio;
        }
        const stdio = opts.stdio || [];
        if (!Array.isArray(stdio)) {
            throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
        }
        const result = [];
        const len = Math.max(stdio.length, alias.length);
        for (let i = 0; i < len; i++) {
            let value = null;
            if (stdio[i] !== undefined) {
                value = stdio[i];
            }
            else if (opts[alias[i]] !== undefined) {
                value = opts[alias[i]];
            }
            result[i] = value;
        }
        return result;
    };
}
,
/* extend/index */ function _(require, module, exports) {
    var hasOwn = Object.prototype.hasOwnProperty;
    var toStr = Object.prototype.toString;
    var defineProperty = Object.defineProperty;
    var gOPD = Object.getOwnPropertyDescriptor;
    var isArray = function isArray(arr) {
        if (typeof Array.isArray === 'function') {
            return Array.isArray(arr);
        }
        return toStr.call(arr) === '[object Array]';
    };
    var isPlainObject = function isPlainObject(obj) {
        if (!obj || toStr.call(obj) !== '[object Object]') {
            return false;
        }
        var hasOwnConstructor = hasOwn.call(obj, 'constructor');
        var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
        // Not own constructor property must be Object
        if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
            return false;
        }
        // Own properties are enumerated firstly, so to speed up,
        // if last one is own, then all properties are own.
        var key;
        for (key in obj) { /**/ }
        return typeof key === 'undefined' || hasOwn.call(obj, key);
    };
    // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
    var setProperty = function setProperty(target, options) {
        if (defineProperty && options.name === '__proto__') {
            defineProperty(target, options.name, {
                enumerable: true,
                configurable: true,
                value: options.newValue,
                writable: true
            });
        }
        else {
            target[options.name] = options.newValue;
        }
    };
    // Return undefined instead of __proto__ if '__proto__' is not an own property
    var getProperty = function getProperty(obj, name) {
        if (name === '__proto__') {
            if (!hasOwn.call(obj, name)) {
                return void 0;
            }
            else if (gOPD) {
                // In early versions of node, obj['__proto__'] is buggy when obj has
                // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
                return gOPD(obj, name).value;
            }
        }
        return obj[name];
    };
    module.exports = function extend() {
        var options, name, src, copy, copyIsArray, clone;
        var target = arguments[0];
        var i = 1;
        var length = arguments.length;
        var deep = false;
        // Handle a deep copy situation
        if (typeof target === 'boolean') {
            deep = target;
            target = arguments[1] || {};
            // skip the boolean and the target
            i = 2;
        }
        if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
            target = {};
        }
        for (; i < length; ++i) {
            options = arguments[i];
            // Only deal with non-null/undefined values
            if (options != null) {
                // Extend the base object
                for (name in options) {
                    src = getProperty(target, name);
                    copy = getProperty(options, name);
                    // Prevent never-ending loop
                    if (target !== copy) {
                        // Recurse if we're merging plain objects or arrays
                        if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                            if (copyIsArray) {
                                copyIsArray = false;
                                clone = src && isArray(src) ? src : [];
                            }
                            else {
                                clone = src && isPlainObject(src) ? src : {};
                            }
                            // Never move original objects, clone them
                            setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
                            // Don't bring in undefined values
                        }
                        else if (typeof copy !== 'undefined') {
                            setProperty(target, { name: name, newValue: copy });
                        }
                    }
                }
            }
        }
        // Return the modified object
        return target;
    };
}
,
/* extsprintf/lib/extsprintf */ function _(require, module, exports) {
    /*
     * extsprintf.js: extended POSIX-style sprintf
     */
    var mod_assert = require('assert');
    var mod_util = require('util');
    /*
     * Public interface
     */
    exports.sprintf = jsSprintf;
    exports.printf = jsPrintf;
    exports.fprintf = jsFprintf;
    /*
     * Stripped down version of s[n]printf(3c).  We make a best effort to throw an
     * exception when given a format string we don't understand, rather than
     * ignoring it, so that we won't break existing programs if/when we go implement
     * the rest of this.
     *
     * This implementation currently supports specifying
     *	- field alignment ('-' flag),
     * 	- zero-pad ('0' flag)
     *	- always show numeric sign ('+' flag),
     *	- field width
     *	- conversions for strings, decimal integers, and floats (numbers).
     *	- argument size specifiers.  These are all accepted but ignored, since
     *	  Javascript has no notion of the physical size of an argument.
     *
     * Everything else is currently unsupported, most notably precision, unsigned
     * numbers, non-decimal numbers, and characters.
     */
    function jsSprintf(fmt) {
        var regex = [
            '([^%]*)',
            '%',
            '([\'\\-+ #0]*?)',
            '([1-9]\\d*)?',
            '(\\.([1-9]\\d*))?',
            '[lhjztL]*?',
            '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
        ].join('');
        var re = new RegExp(regex);
        var args = Array.prototype.slice.call(arguments, 1);
        var flags, width, precision, conversion;
        var left, pad, sign, arg, match;
        var ret = '';
        var argn = 1;
        mod_assert.equal('string', typeof (fmt));
        while ((match = re.exec(fmt)) !== null) {
            ret += match[1];
            fmt = fmt.substring(match[0].length);
            flags = match[2] || '';
            width = match[3] || 0;
            precision = match[4] || '';
            conversion = match[6];
            left = false;
            sign = false;
            pad = ' ';
            if (conversion == '%') {
                ret += '%';
                continue;
            }
            if (args.length === 0)
                throw (new Error('too few args to sprintf'));
            arg = args.shift();
            argn++;
            if (flags.match(/[\' #]/))
                throw (new Error('unsupported flags: ' + flags));
            if (precision.length > 0)
                throw (new Error('non-zero precision not supported'));
            if (flags.match(/-/))
                left = true;
            if (flags.match(/0/))
                pad = '0';
            if (flags.match(/\+/))
                sign = true;
            switch (conversion) {
                case 's':
                    if (arg === undefined || arg === null)
                        throw (new Error('argument ' + argn +
                            ': attempted to print undefined or null ' +
                            'as a string'));
                    ret += doPad(pad, width, left, arg.toString());
                    break;
                case 'd':
                    arg = Math.floor(arg);
                /*jsl:fallthru*/
                case 'f':
                    sign = sign && arg > 0 ? '+' : '';
                    ret += sign + doPad(pad, width, left, arg.toString());
                    break;
                case 'x':
                    ret += doPad(pad, width, left, arg.toString(16));
                    break;
                case 'j': /* non-standard */
                    if (width === 0)
                        width = 10;
                    ret += mod_util.inspect(arg, false, width);
                    break;
                case 'r': /* non-standard */
                    ret += dumpException(arg);
                    break;
                default:
                    throw (new Error('unsupported conversion: ' +
                        conversion));
            }
        }
        ret += fmt;
        return (ret);
    }
    function jsPrintf() {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(process.stdout);
        jsFprintf.apply(null, args);
    }
    function jsFprintf(stream) {
        var args = Array.prototype.slice.call(arguments, 1);
        return (stream.write(jsSprintf.apply(this, args)));
    }
    function doPad(chr, width, left, str) {
        var ret = str;
        while (ret.length < width) {
            if (left)
                ret += chr;
            else
                ret = chr + ret;
        }
        return (ret);
    }
    /*
     * This function dumps long stack traces for exceptions having a cause() method.
     * See node-verror for an example.
     */
    function dumpException(ex) {
        var ret;
        if (!(ex instanceof Error))
            throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
        /* Note that V8 prepends "ex.stack" with ex.toString(). */
        ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
        if (ex.cause && typeof (ex.cause) === 'function') {
            var cex = ex.cause();
            if (cex) {
                ret += '\nCaused by: ' + dumpException(cex);
            }
        }
        return (ret);
    }
}
,
/* fast-deep-equal/index */ function _(require, module, exports) {
    var isArray = Array.isArray;
    var keyList = Object.keys;
    var hasProp = Object.prototype.hasOwnProperty;
    module.exports = function equal(a, b) {
        if (a === b)
            return true;
        var arrA = isArray(a), arrB = isArray(b), i, length, key;
        if (arrA && arrB) {
            length = a.length;
            if (length != b.length)
                return false;
            for (i = 0; i < length; i++)
                if (!equal(a[i], b[i]))
                    return false;
            return true;
        }
        if (arrA != arrB)
            return false;
        var dateA = a instanceof Date, dateB = b instanceof Date;
        if (dateA != dateB)
            return false;
        if (dateA && dateB)
            return a.getTime() == b.getTime();
        var regexpA = a instanceof RegExp, regexpB = b instanceof RegExp;
        if (regexpA != regexpB)
            return false;
        if (regexpA && regexpB)
            return a.toString() == b.toString();
        if (a instanceof Object && b instanceof Object) {
            var keys = keyList(a);
            length = keys.length;
            if (length !== keyList(b).length)
                return false;
            for (i = 0; i < length; i++)
                if (!hasProp.call(b, keys[i]))
                    return false;
            for (i = 0; i < length; i++) {
                key = keys[i];
                if (!equal(a[key], b[key]))
                    return false;
            }
            return true;
        }
        return false;
    };
}
,
/* fast-json-stable-stringify/index */ function _(require, module, exports) {
    module.exports = function (data, opts) {
        if (!opts)
            opts = {};
        if (typeof opts === 'function')
            opts = { cmp: opts };
        var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
        var cmp = opts.cmp && (function (f) {
            return function (node) {
                return function (a, b) {
                    var aobj = { key: a, value: node[a] };
                    var bobj = { key: b, value: node[b] };
                    return f(aobj, bobj);
                };
            };
        })(opts.cmp);
        var seen = [];
        return (function stringify(node) {
            if (node && node.toJSON && typeof node.toJSON === 'function') {
                node = node.toJSON();
            }
            if (node === undefined)
                return;
            if (typeof node == 'number')
                return isFinite(node) ? '' + node : 'null';
            if (typeof node !== 'object')
                return JSON.stringify(node);
            var i, out;
            if (Array.isArray(node)) {
                out = '[';
                for (i = 0; i < node.length; i++) {
                    if (i)
                        out += ',';
                    out += stringify(node[i]) || 'null';
                }
                return out + ']';
            }
            if (node === null)
                return 'null';
            if (seen.indexOf(node) !== -1) {
                if (cycles)
                    return JSON.stringify('__cycle__');
                throw new TypeError('Converting circular structure to JSON');
            }
            var seenIndex = seen.push(node) - 1;
            var keys = Object.keys(node).sort(cmp && cmp(node));
            out = '';
            for (i = 0; i < keys.length; i++) {
                var key = keys[i];
                var value = stringify(node[key]);
                if (!value)
                    continue;
                if (out)
                    out += ',';
                out += JSON.stringify(key) + ':' + value;
            }
            seen.splice(seenIndex, 1);
            return '{' + out + '}';
        })(data);
    };
}
,
/* find-up/index */ function _(require, module, exports) {
    const path = require('path');
    const locatePath = require(260) /* locate-path */;
    module.exports = (filename, opts) => {
        opts = opts || {};
        const startDir = path.resolve(opts.cwd || '');
        const root = path.parse(startDir).root;
        const filenames = [].concat(filename);
        return new Promise(resolve => {
            (function find(dir) {
                locatePath(filenames, { cwd: dir }).then(file => {
                    if (file) {
                        resolve(path.join(dir, file));
                    }
                    else if (dir === root) {
                        resolve(null);
                    }
                    else {
                        find(path.dirname(dir));
                    }
                });
            })(startDir);
        });
    };
    module.exports.sync = (filename, opts) => {
        opts = opts || {};
        let dir = path.resolve(opts.cwd || '');
        const root = path.parse(dir).root;
        const filenames = [].concat(filename);
        // eslint-disable-next-line no-constant-condition
        while (true) {
            const file = locatePath.sync(filenames, { cwd: dir });
            if (file) {
                return path.join(dir, file);
            }
            else if (dir === root) {
                return null;
            }
            dir = path.dirname(dir);
        }
    };
}
,
/* forever-agent/index */ function _(require, module, exports) {
    module.exports = ForeverAgent;
    ForeverAgent.SSL = ForeverAgentSSL;
    var util = require('util'), Agent = require('http').Agent, net = require('net'), tls = require('tls'), AgentSSL = require('https').Agent;
    function getConnectionName(host, port) {
        var name = '';
        if (typeof host === 'string') {
            name = host + ':' + port;
        }
        else {
            // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name.
            name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':');
        }
        return name;
    }
    function ForeverAgent(options) {
        var self = this;
        self.options = options || {};
        self.requests = {};
        self.sockets = {};
        self.freeSockets = {};
        self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets;
        self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets;
        self.on('free', function (socket, host, port) {
            var name = getConnectionName(host, port);
            if (self.requests[name] && self.requests[name].length) {
                self.requests[name].shift().onSocket(socket);
            }
            else if (self.sockets[name].length < self.minSockets) {
                if (!self.freeSockets[name])
                    self.freeSockets[name] = [];
                self.freeSockets[name].push(socket);
                // if an error happens while we don't use the socket anyway, meh, throw the socket away
                var onIdleError = function () {
                    socket.destroy();
                };
                socket._onIdleError = onIdleError;
                socket.on('error', onIdleError);
            }
            else {
                // If there are no pending requests just destroy the
                // socket and it will get removed from the pool. This
                // gets us out of timeout issues and allows us to
                // default to Connection:keep-alive.
                socket.destroy();
            }
        });
    }
    util.inherits(ForeverAgent, Agent);
    ForeverAgent.defaultMinSockets = 5;
    ForeverAgent.prototype.createConnection = net.createConnection;
    ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest;
    ForeverAgent.prototype.addRequest = function (req, host, port) {
        var name = getConnectionName(host, port);
        if (typeof host !== 'string') {
            var options = host;
            port = options.port;
            host = options.host;
        }
        if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
            var idleSocket = this.freeSockets[name].pop();
            idleSocket.removeListener('error', idleSocket._onIdleError);
            delete idleSocket._onIdleError;
            req._reusedSocket = true;
            req.onSocket(idleSocket);
        }
        else {
            this.addRequestNoreuse(req, host, port);
        }
    };
    ForeverAgent.prototype.removeSocket = function (s, name, host, port) {
        if (this.sockets[name]) {
            var index = this.sockets[name].indexOf(s);
            if (index !== -1) {
                this.sockets[name].splice(index, 1);
            }
        }
        else if (this.sockets[name] && this.sockets[name].length === 0) {
            // don't leak
            delete this.sockets[name];
            delete this.requests[name];
        }
        if (this.freeSockets[name]) {
            var index = this.freeSockets[name].indexOf(s);
            if (index !== -1) {
                this.freeSockets[name].splice(index, 1);
                if (this.freeSockets[name].length === 0) {
                    delete this.freeSockets[name];
                }
            }
        }
        if (this.requests[name] && this.requests[name].length) {
            // If we have pending requests and a socket gets closed a new one
            // needs to be created to take over in the pool for the one that closed.
            this.createSocket(name, host, port).emit('free');
        }
    };
    function ForeverAgentSSL(options) {
        ForeverAgent.call(this, options);
    }
    util.inherits(ForeverAgentSSL, ForeverAgent);
    ForeverAgentSSL.prototype.createConnection = createConnectionSSL;
    ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest;
    function createConnectionSSL(port, host, options) {
        if (typeof port === 'object') {
            options = port;
        }
        else if (typeof host === 'object') {
            options = host;
        }
        else if (typeof options === 'object') {
            options = options;
        }
        else {
            options = {};
        }
        if (typeof port === 'number') {
            options.port = port;
        }
        if (typeof host === 'string') {
            options.host = host;
        }
        return tls.connect(options);
    }
}
,
/* form-data/lib/form_data */ function _(require, module, exports) {
    var CombinedStream = require(86) /* combined-stream */;
    var util = require('util');
    var path = require('path');
    var http = require('http');
    var https = require('https');
    var parseUrl = require('url').parse;
    var fs = require('fs');
    var mime = require(265) /* mime-types */;
    var asynckit = require(54) /* asynckit */;
    var populate = require(113) /* ./populate.js */;
    // Public API
    module.exports = FormData;
    // make it a Stream
    util.inherits(FormData, CombinedStream);
    /**
     * Create readable "multipart/form-data" streams.
     * Can be used to submit forms
     * and file uploads to other web applications.
     *
     * @constructor
     * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream
     */
    function FormData(options) {
        if (!(this instanceof FormData)) {
            return new FormData();
        }
        this._overheadLength = 0;
        this._valueLength = 0;
        this._valuesToMeasure = [];
        CombinedStream.call(this);
        options = options || {};
        for (var option in options) {
            this[option] = options[option];
        }
    }
    FormData.LINE_BREAK = '\r\n';
    FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
    FormData.prototype.append = function (field, value, options) {
        options = options || {};
        // allow filename as single option
        if (typeof options == 'string') {
            options = { filename: options };
        }
        var append = CombinedStream.prototype.append.bind(this);
        // all that streamy business can't handle numbers
        if (typeof value == 'number') {
            value = '' + value;
        }
        // https://github.com/felixge/node-form-data/issues/38
        if (util.isArray(value)) {
            // Please convert your array into string
            // the way web server expects it
            this._error(new Error('Arrays are not supported.'));
            return;
        }
        var header = this._multiPartHeader(field, value, options);
        var footer = this._multiPartFooter();
        append(header);
        append(value);
        append(footer);
        // pass along options.knownLength
        this._trackLength(header, value, options);
    };
    FormData.prototype._trackLength = function (header, value, options) {
        var valueLength = 0;
        // used w/ getLengthSync(), when length is known.
        // e.g. for streaming directly from a remote server,
        // w/ a known file a size, and not wanting to wait for
        // incoming file to finish to get its size.
        if (options.knownLength != null) {
            valueLength += +options.knownLength;
        }
        else if (Buffer.isBuffer(value)) {
            valueLength = value.length;
        }
        else if (typeof value === 'string') {
            valueLength = Buffer.byteLength(value);
        }
        this._valueLength += valueLength;
        // @check why add CRLF? does this account for custom/multiple CRLFs?
        this._overheadLength +=
            Buffer.byteLength(header) +
                FormData.LINE_BREAK.length;
        // empty or either doesn't have path or not an http response
        if (!value || (!value.path && !(value.readable && value.hasOwnProperty('httpVersion')))) {
            return;
        }
        // no need to bother with the length
        if (!options.knownLength) {
            this._valuesToMeasure.push(value);
        }
    };
    FormData.prototype._lengthRetriever = function (value, callback) {
        if (value.hasOwnProperty('fd')) {
            // take read range into a account
            // `end` = Infinity –> read file till the end
            //
            // TODO: Looks like there is bug in Node fs.createReadStream
            // it doesn't respect `end` options without `start` options
            // Fix it when node fixes it.
            // https://github.com/joyent/node/issues/7819
            if (value.end != undefined && value.end != Infinity && value.start != undefined) {
                // when end specified
                // no need to calculate range
                // inclusive, starts with 0
                callback(null, value.end + 1 - (value.start ? value.start : 0));
                // not that fast snoopy
            }
            else {
                // still need to fetch file size from fs
                fs.stat(value.path, function (err, stat) {
                    var fileSize;
                    if (err) {
                        callback(err);
                        return;
                    }
                    // update final size based on the range options
                    fileSize = stat.size - (value.start ? value.start : 0);
                    callback(null, fileSize);
                });
            }
            // or http response
        }
        else if (value.hasOwnProperty('httpVersion')) {
            callback(null, +value.headers['content-length']);
            // or request stream http://github.com/mikeal/request
        }
        else if (value.hasOwnProperty('httpModule')) {
            // wait till response come back
            value.on('response', function (response) {
                value.pause();
                callback(null, +response.headers['content-length']);
            });
            value.resume();
            // something else
        }
        else {
            callback('Unknown stream');
        }
    };
    FormData.prototype._multiPartHeader = function (field, value, options) {
        // custom header specified (as string)?
        // it becomes responsible for boundary
        // (e.g. to handle extra CRLFs on .NET servers)
        if (typeof options.header == 'string') {
            return options.header;
        }
        var contentDisposition = this._getContentDisposition(value, options);
        var contentType = this._getContentType(value, options);
        var contents = '';
        var headers = {
            // add custom disposition as third element or keep it two elements if not
            'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
            // if no content type. allow it to be empty array
            'Content-Type': [].concat(contentType || [])
        };
        // allow custom headers.
        if (typeof options.header == 'object') {
            populate(headers, options.header);
        }
        var header;
        for (var prop in headers) {
            if (!headers.hasOwnProperty(prop))
                continue;
            header = headers[prop];
            // skip nullish headers.
            if (header == null) {
                continue;
            }
            // convert all headers to arrays.
            if (!Array.isArray(header)) {
                header = [header];
            }
            // add non-empty headers.
            if (header.length) {
                contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
            }
        }
        return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
    };
    FormData.prototype._getContentDisposition = function (value, options) {
        var filename, contentDisposition;
        if (typeof options.filepath === 'string') {
            // custom filepath for relative paths
            filename = path.normalize(options.filepath).replace(/\\/g, '/');
        }
        else if (options.filename || value.name || value.path) {
            // custom filename take precedence
            // formidable and the browser add a name property
            // fs- and request- streams have path property
            filename = path.basename(options.filename || value.name || value.path);
        }
        else if (value.readable && value.hasOwnProperty('httpVersion')) {
            // or try http response
            filename = path.basename(value.client._httpMessage.path);
        }
        if (filename) {
            contentDisposition = 'filename="' + filename + '"';
        }
        return contentDisposition;
    };
    FormData.prototype._getContentType = function (value, options) {
        // use custom content-type above all
        var contentType = options.contentType;
        // or try `name` from formidable, browser
        if (!contentType && value.name) {
            contentType = mime.lookup(value.name);
        }
        // or try `path` from fs-, request- streams
        if (!contentType && value.path) {
            contentType = mime.lookup(value.path);
        }
        // or if it's http-reponse
        if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
            contentType = value.headers['content-type'];
        }
        // or guess it from the filepath or filename
        if (!contentType && (options.filepath || options.filename)) {
            contentType = mime.lookup(options.filepath || options.filename);
        }
        // fallback to the default content type if `value` is not simple value
        if (!contentType && typeof value == 'object') {
            contentType = FormData.DEFAULT_CONTENT_TYPE;
        }
        return contentType;
    };
    FormData.prototype._multiPartFooter = function () {
        return function (next) {
            var footer = FormData.LINE_BREAK;
            var lastPart = (this._streams.length === 0);
            if (lastPart) {
                footer += this._lastBoundary();
            }
            next(footer);
        }.bind(this);
    };
    FormData.prototype._lastBoundary = function () {
        return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
    };
    FormData.prototype.getHeaders = function (userHeaders) {
        var header;
        var formHeaders = {
            'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
        };
        for (header in userHeaders) {
            if (userHeaders.hasOwnProperty(header)) {
                formHeaders[header.toLowerCase()] = userHeaders[header];
            }
        }
        return formHeaders;
    };
    FormData.prototype.getBoundary = function () {
        if (!this._boundary) {
            this._generateBoundary();
        }
        return this._boundary;
    };
    FormData.prototype._generateBoundary = function () {
        // This generates a 50 character boundary similar to those used by Firefox.
        // They are optimized for boyer-moore parsing.
        var boundary = '--------------------------';
        for (var i = 0; i < 24; i++) {
            boundary += Math.floor(Math.random() * 10).toString(16);
        }
        this._boundary = boundary;
    };
    // Note: getLengthSync DOESN'T calculate streams length
    // As workaround one can calculate file size manually
    // and add it as knownLength option
    FormData.prototype.getLengthSync = function () {
        var knownLength = this._overheadLength + this._valueLength;
        // Don't get confused, there are 3 "internal" streams for each keyval pair
        // so it basically checks if there is any value added to the form
        if (this._streams.length) {
            knownLength += this._lastBoundary().length;
        }
        // https://github.com/form-data/form-data/issues/40
        if (!this.hasKnownLength()) {
            // Some async length retrievers are present
            // therefore synchronous length calculation is false.
            // Please use getLength(callback) to get proper length
            this._error(new Error('Cannot calculate proper length in synchronous way.'));
        }
        return knownLength;
    };
    // Public API to check if length of added values is known
    // https://github.com/form-data/form-data/issues/196
    // https://github.com/form-data/form-data/issues/262
    FormData.prototype.hasKnownLength = function () {
        var hasKnownLength = true;
        if (this._valuesToMeasure.length) {
            hasKnownLength = false;
        }
        return hasKnownLength;
    };
    FormData.prototype.getLength = function (cb) {
        var knownLength = this._overheadLength + this._valueLength;
        if (this._streams.length) {
            knownLength += this._lastBoundary().length;
        }
        if (!this._valuesToMeasure.length) {
            process.nextTick(cb.bind(this, null, knownLength));
            return;
        }
        asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function (err, values) {
            if (err) {
                cb(err);
                return;
            }
            values.forEach(function (length) {
                knownLength += length;
            });
            cb(null, knownLength);
        });
    };
    FormData.prototype.submit = function (params, cb) {
        var request, options, defaults = { method: 'post' };
        // parse provided url if it's string
        // or treat it as options object
        if (typeof params == 'string') {
            params = parseUrl(params);
            options = populate({
                port: params.port,
                path: params.pathname,
                host: params.hostname,
                protocol: params.protocol
            }, defaults);
            // use custom params
        }
        else {
            options = populate(params, defaults);
            // if no port provided use default one
            if (!options.port) {
                options.port = options.protocol == 'https:' ? 443 : 80;
            }
        }
        // put that good code in getHeaders to some use
        options.headers = this.getHeaders(params.headers);
        // https if specified, fallback to http in any other case
        if (options.protocol == 'https:') {
            request = https.request(options);
        }
        else {
            request = http.request(options);
        }
        // get content length and fire away
        this.getLength(function (err, length) {
            if (err) {
                this._error(err);
                return;
            }
            // add content length
            request.setHeader('Content-Length', length);
            this.pipe(request);
            if (cb) {
                request.on('error', cb);
                request.on('response', cb.bind(this, null));
            }
        }.bind(this));
        return request;
    };
    FormData.prototype._error = function (err) {
        if (!this.error) {
            this.error = err;
            this.pause();
            this.emit('error', err);
        }
    };
    FormData.prototype.toString = function () {
        return '[object FormData]';
    };
}
,
/* form-data/lib/populate */ function _(require, module, exports) {
    // populates missing values
    module.exports = function (dst, src) {
        Object.keys(src).forEach(function (prop) {
            dst[prop] = dst[prop] || src[prop];
        });
        return dst;
    };
}
,
/* get-caller-file/index */ function _(require, module, exports) {
    // Call this function in a another function to find out the file from
    // which that function was called from. (Inspects the v8 stack trace)
    //
    // Inspired by http://stackoverflow.com/questions/13227489
    module.exports = function getCallerFile(_position) {
        var oldPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = function (err, stack) { return stack; };
        var stack = new Error().stack;
        Error.prepareStackTrace = oldPrepareStackTrace;
        var position = _position ? _position : 2;
        // stack[0] holds this file
        // stack[1] holds where this function was called
        // stack[2] holds the file we're interested in
        return stack[position] ? stack[position].getFileName() : undefined;
    };
}
,
/* get-stream/buffer-stream */ function _(require, module, exports) {
    const PassThrough = require('stream').PassThrough;
    module.exports = opts => {
        opts = Object.assign({}, opts);
        const array = opts.array;
        let encoding = opts.encoding;
        const buffer = encoding === 'buffer';
        let objectMode = false;
        if (array) {
            objectMode = !(encoding || buffer);
        }
        else {
            encoding = encoding || 'utf8';
        }
        if (buffer) {
            encoding = null;
        }
        let len = 0;
        const ret = [];
        const stream = new PassThrough({ objectMode });
        if (encoding) {
            stream.setEncoding(encoding);
        }
        stream.on('data', chunk => {
            ret.push(chunk);
            if (objectMode) {
                len = ret.length;
            }
            else {
                len += chunk.length;
            }
        });
        stream.getBufferedValue = () => {
            if (array) {
                return ret;
            }
            return buffer ? Buffer.concat(ret, len) : ret.join('');
        };
        stream.getBufferedLength = () => len;
        return stream;
    };
}
,
/* get-stream/index */ function _(require, module, exports) {
    const bufferStream = require(115) /* ./buffer-stream */;
    function getStream(inputStream, opts) {
        if (!inputStream) {
            return Promise.reject(new Error('Expected a stream'));
        }
        opts = Object.assign({ maxBuffer: Infinity }, opts);
        const maxBuffer = opts.maxBuffer;
        let stream;
        let clean;
        const p = new Promise((resolve, reject) => {
            const error = err => {
                if (err) { // null check
                    err.bufferedData = stream.getBufferedValue();
                }
                reject(err);
            };
            stream = bufferStream(opts);
            inputStream.once('error', error);
            inputStream.pipe(stream);
            stream.on('data', () => {
                if (stream.getBufferedLength() > maxBuffer) {
                    reject(new Error('maxBuffer exceeded'));
                }
            });
            stream.once('error', error);
            stream.on('end', resolve);
            clean = () => {
                // some streams doesn't implement the `stream.Readable` interface correctly
                if (inputStream.unpipe) {
                    inputStream.unpipe(stream);
                }
            };
        });
        p.then(clean, clean);
        return p.then(() => stream.getBufferedValue());
    }
    module.exports = getStream;
    module.exports.buffer = (stream, opts) => getStream(stream, Object.assign({}, opts, { encoding: 'buffer' }));
    module.exports.array = (stream, opts) => getStream(stream, Object.assign({}, opts, { array: true }));
}
,
/* har-schema/lib/afterRequest.json */ function _(require, module, exports) {
    {
        "$id";
        "afterRequest.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "optional";
        true,
            "required";
        [
            "lastAccess",
            "eTag",
            "hitCount"
        ],
            "properties";
        {
            "expires";
            {
                "type";
                "string",
                    "pattern";
                "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?";
            }
            "lastAccess";
            {
                "type";
                "string",
                    "pattern";
                "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?";
            }
            "eTag";
            {
                "type";
                "string";
            }
            "hitCount";
            {
                "type";
                "integer";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/beforeRequest.json */ function _(require, module, exports) {
    {
        "$id";
        "beforeRequest.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "optional";
        true,
            "required";
        [
            "lastAccess",
            "eTag",
            "hitCount"
        ],
            "properties";
        {
            "expires";
            {
                "type";
                "string",
                    "pattern";
                "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?";
            }
            "lastAccess";
            {
                "type";
                "string",
                    "pattern";
                "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?";
            }
            "eTag";
            {
                "type";
                "string";
            }
            "hitCount";
            {
                "type";
                "integer";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/browser.json */ function _(require, module, exports) {
    {
        "$id";
        "browser.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "name",
            "version"
        ],
            "properties";
        {
            "name";
            {
                "type";
                "string";
            }
            "version";
            {
                "type";
                "string";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/cache.json */ function _(require, module, exports) {
    {
        "$id";
        "cache.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "properties";
        {
            "beforeRequest";
            {
                "oneOf";
                [
                    { "type": "null" },
                    { "$ref": "beforeRequest.json#" }
                ];
            }
            "afterRequest";
            {
                "oneOf";
                [
                    { "type": "null" },
                    { "$ref": "afterRequest.json#" }
                ];
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/content.json */ function _(require, module, exports) {
    {
        "$id";
        "content.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "size",
            "mimeType"
        ],
            "properties";
        {
            "size";
            {
                "type";
                "integer";
            }
            "compression";
            {
                "type";
                "integer";
            }
            "mimeType";
            {
                "type";
                "string";
            }
            "text";
            {
                "type";
                "string";
            }
            "encoding";
            {
                "type";
                "string";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/cookie.json */ function _(require, module, exports) {
    {
        "$id";
        "cookie.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "name",
            "value"
        ],
            "properties";
        {
            "name";
            {
                "type";
                "string";
            }
            "value";
            {
                "type";
                "string";
            }
            "path";
            {
                "type";
                "string";
            }
            "domain";
            {
                "type";
                "string";
            }
            "expires";
            {
                "type";
                ["string", "null"],
                    "format";
                "date-time";
            }
            "httpOnly";
            {
                "type";
                "boolean";
            }
            "secure";
            {
                "type";
                "boolean";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/creator.json */ function _(require, module, exports) {
    {
        "$id";
        "creator.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "name",
            "version"
        ],
            "properties";
        {
            "name";
            {
                "type";
                "string";
            }
            "version";
            {
                "type";
                "string";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/entry.json */ function _(require, module, exports) {
    {
        "$id";
        "entry.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "optional";
        true,
            "required";
        [
            "startedDateTime",
            "time",
            "request",
            "response",
            "cache",
            "timings"
        ],
            "properties";
        {
            "pageref";
            {
                "type";
                "string";
            }
            "startedDateTime";
            {
                "type";
                "string",
                    "format";
                "date-time",
                    "pattern";
                "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))";
            }
            "time";
            {
                "type";
                "number",
                    "min";
                0;
            }
            "request";
            {
                "$ref";
                "request.json#";
            }
            "response";
            {
                "$ref";
                "response.json#";
            }
            "cache";
            {
                "$ref";
                "cache.json#";
            }
            "timings";
            {
                "$ref";
                "timings.json#";
            }
            "serverIPAddress";
            {
                "type";
                "string",
                    "oneOf";
                [
                    { "format": "ipv4" },
                    { "format": "ipv6" }
                ];
            }
            "connection";
            {
                "type";
                "string";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/har.json */ function _(require, module, exports) {
    {
        "$id";
        "har.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "log"
        ],
            "properties";
        {
            "log";
            {
                "$ref";
                "log.json#";
            }
        }
    }
}
,
/* har-schema/lib/header.json */ function _(require, module, exports) {
    {
        "$id";
        "header.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "name",
            "value"
        ],
            "properties";
        {
            "name";
            {
                "type";
                "string";
            }
            "value";
            {
                "type";
                "string";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/index */ function _(require, module, exports) {
    module.exports = {
        afterRequest: require(117) /* ./afterRequest.json */,
        beforeRequest: require(118) /* ./beforeRequest.json */,
        browser: require(119) /* ./browser.json */,
        cache: require(120) /* ./cache.json */,
        content: require(121) /* ./content.json */,
        cookie: require(122) /* ./cookie.json */,
        creator: require(123) /* ./creator.json */,
        entry: require(124) /* ./entry.json */,
        har: require(125) /* ./har.json */,
        header: require(126) /* ./header.json */,
        log: require(128) /* ./log.json */,
        page: require(129) /* ./page.json */,
        pageTimings: require(130) /* ./pageTimings.json */,
        postData: require(131) /* ./postData.json */,
        query: require(132) /* ./query.json */,
        request: require(133) /* ./request.json */,
        response: require(134) /* ./response.json */,
        timings: require(135) /* ./timings.json */
    };
}
,
/* har-schema/lib/log.json */ function _(require, module, exports) {
    {
        "$id";
        "log.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "version",
            "creator",
            "entries"
        ],
            "properties";
        {
            "version";
            {
                "type";
                "string";
            }
            "creator";
            {
                "$ref";
                "creator.json#";
            }
            "browser";
            {
                "$ref";
                "browser.json#";
            }
            "pages";
            {
                "type";
                "array",
                    "items";
                {
                    "$ref";
                    "page.json#";
                }
            }
            "entries";
            {
                "type";
                "array",
                    "items";
                {
                    "$ref";
                    "entry.json#";
                }
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/page.json */ function _(require, module, exports) {
    {
        "$id";
        "page.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "optional";
        true,
            "required";
        [
            "startedDateTime",
            "id",
            "title",
            "pageTimings"
        ],
            "properties";
        {
            "startedDateTime";
            {
                "type";
                "string",
                    "format";
                "date-time",
                    "pattern";
                "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))";
            }
            "id";
            {
                "type";
                "string",
                    "unique";
                true;
            }
            "title";
            {
                "type";
                "string";
            }
            "pageTimings";
            {
                "$ref";
                "pageTimings.json#";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/pageTimings.json */ function _(require, module, exports) {
    {
        "$id";
        "pageTimings.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "properties";
        {
            "onContentLoad";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "onLoad";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/postData.json */ function _(require, module, exports) {
    {
        "$id";
        "postData.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "optional";
        true,
            "required";
        [
            "mimeType"
        ],
            "properties";
        {
            "mimeType";
            {
                "type";
                "string";
            }
            "text";
            {
                "type";
                "string";
            }
            "params";
            {
                "type";
                "array",
                    "required";
                [
                    "name"
                ],
                    "properties";
                {
                    "name";
                    {
                        "type";
                        "string";
                    }
                    "value";
                    {
                        "type";
                        "string";
                    }
                    "fileName";
                    {
                        "type";
                        "string";
                    }
                    "contentType";
                    {
                        "type";
                        "string";
                    }
                    "comment";
                    {
                        "type";
                        "string";
                    }
                }
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/query.json */ function _(require, module, exports) {
    {
        "$id";
        "query.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "name",
            "value"
        ],
            "properties";
        {
            "name";
            {
                "type";
                "string";
            }
            "value";
            {
                "type";
                "string";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/request.json */ function _(require, module, exports) {
    {
        "$id";
        "request.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "method",
            "url",
            "httpVersion",
            "cookies",
            "headers",
            "queryString",
            "headersSize",
            "bodySize"
        ],
            "properties";
        {
            "method";
            {
                "type";
                "string";
            }
            "url";
            {
                "type";
                "string",
                    "format";
                "uri";
            }
            "httpVersion";
            {
                "type";
                "string";
            }
            "cookies";
            {
                "type";
                "array",
                    "items";
                {
                    "$ref";
                    "cookie.json#";
                }
            }
            "headers";
            {
                "type";
                "array",
                    "items";
                {
                    "$ref";
                    "header.json#";
                }
            }
            "queryString";
            {
                "type";
                "array",
                    "items";
                {
                    "$ref";
                    "query.json#";
                }
            }
            "postData";
            {
                "$ref";
                "postData.json#";
            }
            "headersSize";
            {
                "type";
                "integer";
            }
            "bodySize";
            {
                "type";
                "integer";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/response.json */ function _(require, module, exports) {
    {
        "$id";
        "response.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "type";
        "object",
            "required";
        [
            "status",
            "statusText",
            "httpVersion",
            "cookies",
            "headers",
            "content",
            "redirectURL",
            "headersSize",
            "bodySize"
        ],
            "properties";
        {
            "status";
            {
                "type";
                "integer";
            }
            "statusText";
            {
                "type";
                "string";
            }
            "httpVersion";
            {
                "type";
                "string";
            }
            "cookies";
            {
                "type";
                "array",
                    "items";
                {
                    "$ref";
                    "cookie.json#";
                }
            }
            "headers";
            {
                "type";
                "array",
                    "items";
                {
                    "$ref";
                    "header.json#";
                }
            }
            "content";
            {
                "$ref";
                "content.json#";
            }
            "redirectURL";
            {
                "type";
                "string";
            }
            "headersSize";
            {
                "type";
                "integer";
            }
            "bodySize";
            {
                "type";
                "integer";
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-schema/lib/timings.json */ function _(require, module, exports) {
    {
        "$id";
        "timings.json#",
            "$schema";
        "http://json-schema.org/draft-06/schema#",
            "required";
        [
            "send",
            "wait",
            "receive"
        ],
            "properties";
        {
            "dns";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "connect";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "blocked";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "send";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "wait";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "receive";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "ssl";
            {
                "type";
                "number",
                    "min";
                -1;
            }
            "comment";
            {
                "type";
                "string";
            }
        }
    }
}
,
/* har-validator/lib/error */ function _(require, module, exports) {
    function HARError(errors) {
        var message = 'validation failed';
        this.name = 'HARError';
        this.message = message;
        this.errors = errors;
        if (typeof Error.captureStackTrace === 'function') {
            Error.captureStackTrace(this, this.constructor);
        }
        else {
            this.stack = (new Error(message)).stack;
        }
    }
    HARError.prototype = Error.prototype;
    module.exports = HARError;
}
,
/* har-validator/lib/promise */ function _(require, module, exports) {
    var Ajv = require(3) /* ajv */;
    var HARError = require(136) /* ./error */;
    var schemas = require(127) /* har-schema */;
    var ajv;
    function validate(name, data) {
        data = data || {};
        // validator config
        ajv = ajv || new Ajv({
            allErrors: true,
            schemas: schemas
        });
        var validate = ajv.getSchema(name + '.json');
        return new Promise(function (resolve, reject) {
            var valid = validate(data);
            !valid ? reject(new HARError(validate.errors)) : resolve(data);
        });
    }
    exports.afterRequest = function (data) {
        return validate('afterRequest', data);
    };
    exports.beforeRequest = function (data) {
        return validate('beforeRequest', data);
    };
    exports.browser = function (data) {
        return validate('browser', data);
    };
    exports.cache = function (data) {
        return validate('cache', data);
    };
    exports.content = function (data) {
        return validate('content', data);
    };
    exports.cookie = function (data) {
        return validate('cookie', data);
    };
    exports.creator = function (data) {
        return validate('creator', data);
    };
    exports.entry = function (data) {
        return validate('entry', data);
    };
    exports.har = function (data) {
        return validate('har', data);
    };
    exports.header = function (data) {
        return validate('header', data);
    };
    exports.log = function (data) {
        return validate('log', data);
    };
    exports.page = function (data) {
        return validate('page', data);
    };
    exports.pageTimings = function (data) {
        return validate('pageTimings', data);
    };
    exports.postData = function (data) {
        return validate('postData', data);
    };
    exports.query = function (data) {
        return validate('query', data);
    };
    exports.request = function (data) {
        return validate('request', data);
    };
    exports.response = function (data) {
        return validate('response', data);
    };
    exports.timings = function (data) {
        return validate('timings', data);
    };
}
,
/* http-signature/lib/index */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    var parser = require(139) /* ./parser */;
    var signer = require(140) /* ./signer */;
    var verify = require(142) /* ./verify */;
    var utils = require(141) /* ./utils */;
    ///--- API
    module.exports = {
        parse: parser.parseRequest,
        parseRequest: parser.parseRequest,
        sign: signer.signRequest,
        signRequest: signer.signRequest,
        createSigner: signer.createSigner,
        isSigner: signer.isSigner,
        sshKeyToPEM: utils.sshKeyToPEM,
        sshKeyFingerprint: utils.fingerprint,
        pemToRsaSSHKey: utils.pemToRsaSSHKey,
        verify: verify.verifySignature,
        verifySignature: verify.verifySignature,
        verifyHMAC: verify.verifyHMAC
    };
}
,
/* http-signature/lib/parser */ function _(require, module, exports) {
    // Copyright 2012 Joyent, Inc.  All rights reserved.
    var assert = require(53) /* assert-plus */;
    var util = require('util');
    var utils = require(141) /* ./utils */;
    ///--- Globals
    var HASH_ALGOS = utils.HASH_ALGOS;
    var PK_ALGOS = utils.PK_ALGOS;
    var HttpSignatureError = utils.HttpSignatureError;
    var InvalidAlgorithmError = utils.InvalidAlgorithmError;
    var validateAlgorithm = utils.validateAlgorithm;
    var State = {
        New: 0,
        Params: 1
    };
    var ParamsState = {
        Name: 0,
        Quote: 1,
        Value: 2,
        Comma: 3
    };
    ///--- Specific Errors
    function ExpiredRequestError(message) {
        HttpSignatureError.call(this, message, ExpiredRequestError);
    }
    util.inherits(ExpiredRequestError, HttpSignatureError);
    function InvalidHeaderError(message) {
        HttpSignatureError.call(this, message, InvalidHeaderError);
    }
    util.inherits(InvalidHeaderError, HttpSignatureError);
    function InvalidParamsError(message) {
        HttpSignatureError.call(this, message, InvalidParamsError);
    }
    util.inherits(InvalidParamsError, HttpSignatureError);
    function MissingHeaderError(message) {
        HttpSignatureError.call(this, message, MissingHeaderError);
    }
    util.inherits(MissingHeaderError, HttpSignatureError);
    function StrictParsingError(message) {
        HttpSignatureError.call(this, message, StrictParsingError);
    }
    util.inherits(StrictParsingError, HttpSignatureError);
    ///--- Exported API
    module.exports = {
        /**
         * Parses the 'Authorization' header out of an http.ServerRequest object.
         *
         * Note that this API will fully validate the Authorization header, and throw
         * on any error.  It will not however check the signature, or the keyId format
         * as those are specific to your environment.  You can use the options object
         * to pass in extra constraints.
         *
         * As a response object you can expect this:
         *
         *     {
         *       "scheme": "Signature",
         *       "params": {
         *         "keyId": "foo",
         *         "algorithm": "rsa-sha256",
         *         "headers": [
         *           "date" or "x-date",
         *           "digest"
         *         ],
         *         "signature": "base64"
         *       },
         *       "signingString": "ready to be passed to crypto.verify()"
         *     }
         *
         * @param {Object} request an http.ServerRequest.
         * @param {Object} options an optional options object with:
         *                   - clockSkew: allowed clock skew in seconds (default 300).
         *                   - headers: required header names (def: date or x-date)
         *                   - algorithms: algorithms to support (default: all).
         *                   - strict: should enforce latest spec parsing
         *                             (default: false).
         * @return {Object} parsed out object (see above).
         * @throws {TypeError} on invalid input.
         * @throws {InvalidHeaderError} on an invalid Authorization header error.
         * @throws {InvalidParamsError} if the params in the scheme are invalid.
         * @throws {MissingHeaderError} if the params indicate a header not present,
         *                              either in the request headers from the params,
         *                              or not in the params from a required header
         *                              in options.
         * @throws {StrictParsingError} if old attributes are used in strict parsing
         *                              mode.
         * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew.
         */
        parseRequest: function parseRequest(request, options) {
            assert.object(request, 'request');
            assert.object(request.headers, 'request.headers');
            if (options === undefined) {
                options = {};
            }
            if (options.headers === undefined) {
                options.headers = [request.headers['x-date'] ? 'x-date' : 'date'];
            }
            assert.object(options, 'options');
            assert.arrayOfString(options.headers, 'options.headers');
            assert.optionalFinite(options.clockSkew, 'options.clockSkew');
            var authzHeaderName = options.authorizationHeaderName || 'authorization';
            if (!request.headers[authzHeaderName]) {
                throw new MissingHeaderError('no ' + authzHeaderName + ' header ' +
                    'present in the request');
            }
            options.clockSkew = options.clockSkew || 300;
            var i = 0;
            var state = State.New;
            var substate = ParamsState.Name;
            var tmpName = '';
            var tmpValue = '';
            var parsed = {
                scheme: '',
                params: {},
                signingString: ''
            };
            var authz = request.headers[authzHeaderName];
            for (i = 0; i < authz.length; i++) {
                var c = authz.charAt(i);
                switch (Number(state)) {
                    case State.New:
                        if (c !== ' ')
                            parsed.scheme += c;
                        else
                            state = State.Params;
                        break;
                    case State.Params:
                        switch (Number(substate)) {
                            case ParamsState.Name:
                                var code = c.charCodeAt(0);
                                // restricted name of A-Z / a-z
                                if ((code >= 0x41 && code <= 0x5a) || // A-Z
                                    (code >= 0x61 && code <= 0x7a)) { // a-z
                                    tmpName += c;
                                }
                                else if (c === '=') {
                                    if (tmpName.length === 0)
                                        throw new InvalidHeaderError('bad param format');
                                    substate = ParamsState.Quote;
                                }
                                else {
                                    throw new InvalidHeaderError('bad param format');
                                }
                                break;
                            case ParamsState.Quote:
                                if (c === '"') {
                                    tmpValue = '';
                                    substate = ParamsState.Value;
                                }
                                else {
                                    throw new InvalidHeaderError('bad param format');
                                }
                                break;
                            case ParamsState.Value:
                                if (c === '"') {
                                    parsed.params[tmpName] = tmpValue;
                                    substate = ParamsState.Comma;
                                }
                                else {
                                    tmpValue += c;
                                }
                                break;
                            case ParamsState.Comma:
                                if (c === ',') {
                                    tmpName = '';
                                    substate = ParamsState.Name;
                                }
                                else {
                                    throw new InvalidHeaderError('bad param format');
                                }
                                break;
                            default:
                                throw new Error('Invalid substate');
                        }
                        break;
                    default:
                        throw new Error('Invalid substate');
                }
            }
            if (!parsed.params.headers || parsed.params.headers === '') {
                if (request.headers['x-date']) {
                    parsed.params.headers = ['x-date'];
                }
                else {
                    parsed.params.headers = ['date'];
                }
            }
            else {
                parsed.params.headers = parsed.params.headers.split(' ');
            }
            // Minimally validate the parsed object
            if (!parsed.scheme || parsed.scheme !== 'Signature')
                throw new InvalidHeaderError('scheme was not "Signature"');
            if (!parsed.params.keyId)
                throw new InvalidHeaderError('keyId was not specified');
            if (!parsed.params.algorithm)
                throw new InvalidHeaderError('algorithm was not specified');
            if (!parsed.params.signature)
                throw new InvalidHeaderError('signature was not specified');
            // Check the algorithm against the official list
            parsed.params.algorithm = parsed.params.algorithm.toLowerCase();
            try {
                validateAlgorithm(parsed.params.algorithm);
            }
            catch (e) {
                if (e instanceof InvalidAlgorithmError)
                    throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' +
                        'supported'));
                else
                    throw (e);
            }
            // Build the signingString
            for (i = 0; i < parsed.params.headers.length; i++) {
                var h = parsed.params.headers[i].toLowerCase();
                parsed.params.headers[i] = h;
                if (h === 'request-line') {
                    if (!options.strict) {
                        /*
                         * We allow headers from the older spec drafts if strict parsing isn't
                         * specified in options.
                         */
                        parsed.signingString +=
                            request.method + ' ' + request.url + ' HTTP/' + request.httpVersion;
                    }
                    else {
                        /* Strict parsing doesn't allow older draft headers. */
                        throw (new StrictParsingError('request-line is not a valid header ' +
                            'with strict parsing enabled.'));
                    }
                }
                else if (h === '(request-target)') {
                    parsed.signingString +=
                        '(request-target): ' + request.method.toLowerCase() + ' ' +
                            request.url;
                }
                else {
                    var value = request.headers[h];
                    if (value === undefined)
                        throw new MissingHeaderError(h + ' was not in the request');
                    parsed.signingString += h + ': ' + value;
                }
                if ((i + 1) < parsed.params.headers.length)
                    parsed.signingString += '\n';
            }
            // Check against the constraints
            var date;
            if (request.headers.date || request.headers['x-date']) {
                if (request.headers['x-date']) {
                    date = new Date(request.headers['x-date']);
                }
                else {
                    date = new Date(request.headers.date);
                }
                var now = new Date();
                var skew = Math.abs(now.getTime() - date.getTime());
                if (skew > options.clockSkew * 1000) {
                    throw new ExpiredRequestError('clock skew of ' +
                        (skew / 1000) +
                        's was greater than ' +
                        options.clockSkew + 's');
                }
            }
            options.headers.forEach(function (hdr) {
                // Remember that we already checked any headers in the params
                // were in the request, so if this passes we're good.
                if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0)
                    throw new MissingHeaderError(hdr + ' was not a signed header');
            });
            if (options.algorithms) {
                if (options.algorithms.indexOf(parsed.params.algorithm) === -1)
                    throw new InvalidParamsError(parsed.params.algorithm +
                        ' is not a supported algorithm');
            }
            parsed.algorithm = parsed.params.algorithm.toUpperCase();
            parsed.keyId = parsed.params.keyId;
            return parsed;
        }
    };
}
,
/* http-signature/lib/signer */ function _(require, module, exports) {
    // Copyright 2012 Joyent, Inc.  All rights reserved.
    var assert = require(53) /* assert-plus */;
    var crypto = require('crypto');
    var http = require('http');
    var util = require('util');
    var sshpk = require(349) /* sshpk */;
    var jsprim = require(159) /* jsprim */;
    var utils = require(141) /* ./utils */;
    var sprintf = require('util').format;
    var HASH_ALGOS = utils.HASH_ALGOS;
    var PK_ALGOS = utils.PK_ALGOS;
    var InvalidAlgorithmError = utils.InvalidAlgorithmError;
    var HttpSignatureError = utils.HttpSignatureError;
    var validateAlgorithm = utils.validateAlgorithm;
    ///--- Globals
    var AUTHZ_FMT = 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
    ///--- Specific Errors
    function MissingHeaderError(message) {
        HttpSignatureError.call(this, message, MissingHeaderError);
    }
    util.inherits(MissingHeaderError, HttpSignatureError);
    function StrictParsingError(message) {
        HttpSignatureError.call(this, message, StrictParsingError);
    }
    util.inherits(StrictParsingError, HttpSignatureError);
    /* See createSigner() */
    function RequestSigner(options) {
        assert.object(options, 'options');
        var alg = [];
        if (options.algorithm !== undefined) {
            assert.string(options.algorithm, 'options.algorithm');
            alg = validateAlgorithm(options.algorithm);
        }
        this.rs_alg = alg;
        /*
         * RequestSigners come in two varieties: ones with an rs_signFunc, and ones
         * with an rs_signer.
         *
         * rs_signFunc-based RequestSigners have to build up their entire signing
         * string within the rs_lines array and give it to rs_signFunc as a single
         * concat'd blob. rs_signer-based RequestSigners can add a line at a time to
         * their signing state by using rs_signer.update(), thus only needing to
         * buffer the hash function state and one line at a time.
         */
        if (options.sign !== undefined) {
            assert.func(options.sign, 'options.sign');
            this.rs_signFunc = options.sign;
        }
        else if (alg[0] === 'hmac' && options.key !== undefined) {
            assert.string(options.keyId, 'options.keyId');
            this.rs_keyId = options.keyId;
            if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
                throw (new TypeError('options.key for HMAC must be a string or Buffer'));
            /*
             * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their
             * data in chunks rather than requiring it all to be given in one go
             * at the end, so they are more similar to signers than signFuncs.
             */
            this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key);
            this.rs_signer.sign = function () {
                var digest = this.digest('base64');
                return ({
                    hashAlgorithm: alg[1],
                    toString: function () { return (digest); }
                });
            };
        }
        else if (options.key !== undefined) {
            var key = options.key;
            if (typeof (key) === 'string' || Buffer.isBuffer(key))
                key = sshpk.parsePrivateKey(key);
            assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey');
            this.rs_key = key;
            assert.string(options.keyId, 'options.keyId');
            this.rs_keyId = options.keyId;
            if (!PK_ALGOS[key.type]) {
                throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
                    'keys are not supported'));
            }
            if (alg[0] !== undefined && key.type !== alg[0]) {
                throw (new InvalidAlgorithmError('options.key must be a ' +
                    alg[0].toUpperCase() + ' key, was given a ' +
                    key.type.toUpperCase() + ' key instead'));
            }
            this.rs_signer = key.createSign(alg[1]);
        }
        else {
            throw (new TypeError('options.sign (func) or options.key is required'));
        }
        this.rs_headers = [];
        this.rs_lines = [];
    }
    /**
     * Adds a header to be signed, with its value, into this signer.
     *
     * @param {String} header
     * @param {String} value
     * @return {String} value written
     */
    RequestSigner.prototype.writeHeader = function (header, value) {
        assert.string(header, 'header');
        header = header.toLowerCase();
        assert.string(value, 'value');
        this.rs_headers.push(header);
        if (this.rs_signFunc) {
            this.rs_lines.push(header + ': ' + value);
        }
        else {
            var line = header + ': ' + value;
            if (this.rs_headers.length > 0)
                line = '\n' + line;
            this.rs_signer.update(line);
        }
        return (value);
    };
    /**
     * Adds a default Date header, returning its value.
     *
     * @return {String}
     */
    RequestSigner.prototype.writeDateHeader = function () {
        return (this.writeHeader('date', jsprim.rfc1123(new Date())));
    };
    /**
     * Adds the request target line to be signed.
     *
     * @param {String} method, HTTP method (e.g. 'get', 'post', 'put')
     * @param {String} path
     */
    RequestSigner.prototype.writeTarget = function (method, path) {
        assert.string(method, 'method');
        assert.string(path, 'path');
        method = method.toLowerCase();
        this.writeHeader('(request-target)', method + ' ' + path);
    };
    /**
     * Calculate the value for the Authorization header on this request
     * asynchronously.
     *
     * @param {Func} callback (err, authz)
     */
    RequestSigner.prototype.sign = function (cb) {
        assert.func(cb, 'callback');
        if (this.rs_headers.length < 1)
            throw (new Error('At least one header must be signed'));
        var alg, authz;
        if (this.rs_signFunc) {
            var data = this.rs_lines.join('\n');
            var self = this;
            this.rs_signFunc(data, function (err, sig) {
                if (err) {
                    cb(err);
                    return;
                }
                try {
                    assert.object(sig, 'signature');
                    assert.string(sig.keyId, 'signature.keyId');
                    assert.string(sig.algorithm, 'signature.algorithm');
                    assert.string(sig.signature, 'signature.signature');
                    alg = validateAlgorithm(sig.algorithm);
                    authz = sprintf(AUTHZ_FMT, sig.keyId, sig.algorithm, self.rs_headers.join(' '), sig.signature);
                }
                catch (e) {
                    cb(e);
                    return;
                }
                cb(null, authz);
            });
        }
        else {
            try {
                var sigObj = this.rs_signer.sign();
            }
            catch (e) {
                cb(e);
                return;
            }
            alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm;
            var signature = sigObj.toString();
            authz = sprintf(AUTHZ_FMT, this.rs_keyId, alg, this.rs_headers.join(' '), signature);
            cb(null, authz);
        }
    };
    ///--- Exported API
    module.exports = {
        /**
         * Identifies whether a given object is a request signer or not.
         *
         * @param {Object} object, the object to identify
         * @returns {Boolean}
         */
        isSigner: function (obj) {
            if (typeof (obj) === 'object' && obj instanceof RequestSigner)
                return (true);
            return (false);
        },
        /**
         * Creates a request signer, used to asynchronously build a signature
         * for a request (does not have to be an http.ClientRequest).
         *
         * @param {Object} options, either:
         *                   - {String} keyId
         *                   - {String|Buffer} key
         *                   - {String} algorithm (optional, required for HMAC)
         *                 or:
         *                   - {Func} sign (data, cb)
         * @return {RequestSigner}
         */
        createSigner: function createSigner(options) {
            return (new RequestSigner(options));
        },
        /**
         * Adds an 'Authorization' header to an http.ClientRequest object.
         *
         * Note that this API will add a Date header if it's not already set. Any
         * other headers in the options.headers array MUST be present, or this
         * will throw.
         *
         * You shouldn't need to check the return type; it's just there if you want
         * to be pedantic.
         *
         * The optional flag indicates whether parsing should use strict enforcement
         * of the version draft-cavage-http-signatures-04 of the spec or beyond.
         * The default is to be loose and support
         * older versions for compatibility.
         *
         * @param {Object} request an instance of http.ClientRequest.
         * @param {Object} options signing parameters object:
         *                   - {String} keyId required.
         *                   - {String} key required (either a PEM or HMAC key).
         *                   - {Array} headers optional; defaults to ['date'].
         *                   - {String} algorithm optional (unless key is HMAC);
         *                              default is the same as the sshpk default
         *                              signing algorithm for the type of key given
         *                   - {String} httpVersion optional; defaults to '1.1'.
         *                   - {Boolean} strict optional; defaults to 'false'.
         * @return {Boolean} true if Authorization (and optionally Date) were added.
         * @throws {TypeError} on bad parameter types (input).
         * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with
         *                                 the given key.
         * @throws {sshpk.KeyParseError} if key was bad.
         * @throws {MissingHeaderError} if a header to be signed was specified but
         *                              was not present.
         */
        signRequest: function signRequest(request, options) {
            assert.object(request, 'request');
            assert.object(options, 'options');
            assert.optionalString(options.algorithm, 'options.algorithm');
            assert.string(options.keyId, 'options.keyId');
            assert.optionalArrayOfString(options.headers, 'options.headers');
            assert.optionalString(options.httpVersion, 'options.httpVersion');
            if (!request.getHeader('Date'))
                request.setHeader('Date', jsprim.rfc1123(new Date()));
            if (!options.headers)
                options.headers = ['date'];
            if (!options.httpVersion)
                options.httpVersion = '1.1';
            var alg = [];
            if (options.algorithm) {
                options.algorithm = options.algorithm.toLowerCase();
                alg = validateAlgorithm(options.algorithm);
            }
            var i;
            var stringToSign = '';
            for (i = 0; i < options.headers.length; i++) {
                if (typeof (options.headers[i]) !== 'string')
                    throw new TypeError('options.headers must be an array of Strings');
                var h = options.headers[i].toLowerCase();
                if (h === 'request-line') {
                    if (!options.strict) {
                        /**
                         * We allow headers from the older spec drafts if strict parsing isn't
                         * specified in options.
                         */
                        stringToSign +=
                            request.method + ' ' + request.path + ' HTTP/' +
                                options.httpVersion;
                    }
                    else {
                        /* Strict parsing doesn't allow older draft headers. */
                        throw (new StrictParsingError('request-line is not a valid header ' +
                            'with strict parsing enabled.'));
                    }
                }
                else if (h === '(request-target)') {
                    stringToSign +=
                        '(request-target): ' + request.method.toLowerCase() + ' ' +
                            request.path;
                }
                else {
                    var value = request.getHeader(h);
                    if (value === undefined || value === '') {
                        throw new MissingHeaderError(h + ' was not in the request');
                    }
                    stringToSign += h + ': ' + value;
                }
                if ((i + 1) < options.headers.length)
                    stringToSign += '\n';
            }
            /* This is just for unit tests. */
            if (request.hasOwnProperty('_stringToSign')) {
                request._stringToSign = stringToSign;
            }
            var signature;
            if (alg[0] === 'hmac') {
                if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
                    throw (new TypeError('options.key must be a string or Buffer'));
                var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key);
                hmac.update(stringToSign);
                signature = hmac.digest('base64');
            }
            else {
                var key = options.key;
                if (typeof (key) === 'string' || Buffer.isBuffer(key))
                    key = sshpk.parsePrivateKey(options.key);
                assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey');
                if (!PK_ALGOS[key.type]) {
                    throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
                        'keys are not supported'));
                }
                if (alg[0] !== undefined && key.type !== alg[0]) {
                    throw (new InvalidAlgorithmError('options.key must be a ' +
                        alg[0].toUpperCase() + ' key, was given a ' +
                        key.type.toUpperCase() + ' key instead'));
                }
                var signer = key.createSign(alg[1]);
                signer.update(stringToSign);
                var sigObj = signer.sign();
                if (!HASH_ALGOS[sigObj.hashAlgorithm]) {
                    throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() +
                        ' is not a supported hash algorithm'));
                }
                options.algorithm = key.type + '-' + sigObj.hashAlgorithm;
                signature = sigObj.toString();
                assert.notStrictEqual(signature, '', 'empty signature produced');
            }
            var authzHeaderName = options.authorizationHeaderName || 'Authorization';
            request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, options.keyId, options.algorithm, options.headers.join(' '), signature));
            return true;
        }
    };
}
,
/* http-signature/lib/utils */ function _(require, module, exports) {
    // Copyright 2012 Joyent, Inc.  All rights reserved.
    var assert = require(53) /* assert-plus */;
    var sshpk = require(349) /* sshpk */;
    var util = require('util');
    var HASH_ALGOS = {
        'sha1': true,
        'sha256': true,
        'sha512': true
    };
    var PK_ALGOS = {
        'rsa': true,
        'dsa': true,
        'ecdsa': true
    };
    function HttpSignatureError(message, caller) {
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, caller || HttpSignatureError);
        this.message = message;
        this.name = caller.name;
    }
    util.inherits(HttpSignatureError, Error);
    function InvalidAlgorithmError(message) {
        HttpSignatureError.call(this, message, InvalidAlgorithmError);
    }
    util.inherits(InvalidAlgorithmError, HttpSignatureError);
    function validateAlgorithm(algorithm) {
        var alg = algorithm.toLowerCase().split('-');
        if (alg.length !== 2) {
            throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' +
                'valid algorithm'));
        }
        if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) {
            throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' +
                'are not supported'));
        }
        if (!HASH_ALGOS[alg[1]]) {
            throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' +
                'supported hash algorithm'));
        }
        return (alg);
    }
    ///--- API
    module.exports = {
        HASH_ALGOS: HASH_ALGOS,
        PK_ALGOS: PK_ALGOS,
        HttpSignatureError: HttpSignatureError,
        InvalidAlgorithmError: InvalidAlgorithmError,
        validateAlgorithm: validateAlgorithm,
        /**
         * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
         *
         * The intent of this module is to interoperate with OpenSSL only,
         * specifically the node crypto module's `verify` method.
         *
         * @param {String} key an OpenSSH public key.
         * @return {String} PEM encoded form of the RSA public key.
         * @throws {TypeError} on bad input.
         * @throws {Error} on invalid ssh key formatted data.
         */
        sshKeyToPEM: function sshKeyToPEM(key) {
            assert.string(key, 'ssh_key');
            var k = sshpk.parseKey(key, 'ssh');
            return (k.toString('pem'));
        },
        /**
         * Generates an OpenSSH fingerprint from an ssh public key.
         *
         * @param {String} key an OpenSSH public key.
         * @return {String} key fingerprint.
         * @throws {TypeError} on bad input.
         * @throws {Error} if what you passed doesn't look like an ssh public key.
         */
        fingerprint: function fingerprint(key) {
            assert.string(key, 'ssh_key');
            var k = sshpk.parseKey(key, 'ssh');
            return (k.fingerprint('md5').toString('hex'));
        },
        /**
         * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
         *
         * The reverse of the above function.
         */
        pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
            assert.equal('string', typeof (pem), 'typeof pem');
            var k = sshpk.parseKey(pem, 'pem');
            k.comment = comment;
            return (k.toString('ssh'));
        }
    };
}
,
/* http-signature/lib/verify */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    var assert = require(53) /* assert-plus */;
    var crypto = require('crypto');
    var sshpk = require(349) /* sshpk */;
    var utils = require(141) /* ./utils */;
    var HASH_ALGOS = utils.HASH_ALGOS;
    var PK_ALGOS = utils.PK_ALGOS;
    var InvalidAlgorithmError = utils.InvalidAlgorithmError;
    var HttpSignatureError = utils.HttpSignatureError;
    var validateAlgorithm = utils.validateAlgorithm;
    ///--- Exported API
    module.exports = {
        /**
         * Verify RSA/DSA signature against public key.  You are expected to pass in
         * an object that was returned from `parse()`.
         *
         * @param {Object} parsedSignature the object you got from `parse`.
         * @param {String} pubkey RSA/DSA private key PEM.
         * @return {Boolean} true if valid, false otherwise.
         * @throws {TypeError} if you pass in bad arguments.
         * @throws {InvalidAlgorithmError}
         */
        verifySignature: function verifySignature(parsedSignature, pubkey) {
            assert.object(parsedSignature, 'parsedSignature');
            if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey))
                pubkey = sshpk.parseKey(pubkey);
            assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key');
            var alg = validateAlgorithm(parsedSignature.algorithm);
            if (alg[0] === 'hmac' || alg[0] !== pubkey.type)
                return (false);
            var v = pubkey.createVerify(alg[1]);
            v.update(parsedSignature.signingString);
            return (v.verify(parsedSignature.params.signature, 'base64'));
        },
        /**
         * Verify HMAC against shared secret.  You are expected to pass in an object
         * that was returned from `parse()`.
         *
         * @param {Object} parsedSignature the object you got from `parse`.
         * @param {String} secret HMAC shared secret.
         * @return {Boolean} true if valid, false otherwise.
         * @throws {TypeError} if you pass in bad arguments.
         * @throws {InvalidAlgorithmError}
         */
        verifyHMAC: function verifyHMAC(parsedSignature, secret) {
            assert.object(parsedSignature, 'parsedHMAC');
            assert.string(secret, 'secret');
            var alg = validateAlgorithm(parsedSignature.algorithm);
            if (alg[0] !== 'hmac')
                return (false);
            var hashAlg = alg[1].toUpperCase();
            var hmac = crypto.createHmac(hashAlg, secret);
            hmac.update(parsedSignature.signingString);
            /*
             * Now double-hash to avoid leaking timing information - there's
             * no easy constant-time compare in JS, so we use this approach
             * instead. See for more info:
             * https://www.isecpartners.com/blog/2011/february/double-hmac-
             * verification.aspx
             */
            var h1 = crypto.createHmac(hashAlg, secret);
            h1.update(hmac.digest());
            h1 = h1.digest();
            var h2 = crypto.createHmac(hashAlg, secret);
            h2.update(new Buffer(parsedSignature.params.signature, 'base64'));
            h2 = h2.digest();
            /* Node 0.8 returns strings from .digest(). */
            if (typeof (h1) === 'string')
                return (h1 === h2);
            /* And node 0.10 lacks the .equals() method on Buffers. */
            if (Buffer.isBuffer(h1) && !h1.equals)
                return (h1.toString('binary') === h2.toString('binary'));
            return (h1.equals(h2));
        }
    };
}
,
/* image-size/lib/detector */ function _(require, module, exports) {
    var typeMap = {};
    var types = require(145) /* ./types */;
    // load all available handlers
    types.forEach(function (type) {
        typeMap[type] = require('./types/' + type).detect;
    });
    module.exports = function (buffer, filepath) {
        var type, result;
        for (type in typeMap) {
            result = typeMap[type](buffer, filepath);
            if (result) {
                return type;
            }
        }
    };
}
,
/* image-size/lib/index */ function _(require, module, exports) {
    var fs = require('fs');
    var path = require('path');
    var detector = require(143) /* ./detector */;
    var handlers = {};
    var types = require(145) /* ./types */;
    // load all available handlers
    types.forEach(function (type) {
        handlers[type] = require('./types/' + type);
    });
    // Maximum buffer size, with a default of 128 kilobytes.
    // TO-DO: make this adaptive based on the initial signature of the image
    var MaxBufferSize = 128 * 1024;
    function lookup(buffer, filepath) {
        // detect the file type.. don't rely on the extension
        var type = detector(buffer, filepath);
        // find an appropriate handler for this file type
        if (type in handlers) {
            var size = handlers[type].calculate(buffer, filepath);
            if (size !== false) {
                size.type = type;
                return size;
            }
        }
        // throw up, if we don't understand the file
        throw new TypeError('unsupported file type: ' + type + ' (file: ' + filepath + ')');
    }
    function asyncFileToBuffer(filepath, callback) {
        // open the file in read only mode
        fs.open(filepath, 'r', function (err, descriptor) {
            if (err) {
                return callback(err);
            }
            var size = fs.fstatSync(descriptor).size;
            if (size <= 0) {
                return callback(new Error("File size is not greater than 0 —— " + filepath));
            }
            var bufferSize = Math.min(size, MaxBufferSize);
            var buffer = new Buffer(bufferSize);
            // read first buffer block from the file, asynchronously
            fs.read(descriptor, buffer, 0, bufferSize, 0, function (err) {
                if (err) {
                    return callback(err);
                }
                // close the file, we are done
                fs.close(descriptor, function (err) {
                    callback(err, buffer);
                });
            });
        });
    }
    function syncFileToBuffer(filepath) {
        // read from the file, synchronously
        var descriptor = fs.openSync(filepath, 'r');
        var size = fs.fstatSync(descriptor).size;
        var bufferSize = Math.min(size, MaxBufferSize);
        var buffer = new Buffer(bufferSize);
        fs.readSync(descriptor, buffer, 0, bufferSize, 0);
        fs.closeSync(descriptor);
        return buffer;
    }
    /**
     * @params input - buffer or relative/absolute path of the image file
     * @params callback - optional function for async detection
     */
    module.exports = function (input, callback) {
        // Handle buffer input
        if (Buffer.isBuffer(input)) {
            return lookup(input);
        }
        // input should be a string at this point
        if (typeof input !== 'string') {
            throw new TypeError('invalid invocation');
        }
        // resolve the file path
        var filepath = path.resolve(input);
        if (typeof callback === 'function') {
            asyncFileToBuffer(filepath, function (err, buffer) {
                if (err) {
                    return callback(err);
                }
                // return the dimensions
                var dimensions;
                try {
                    dimensions = lookup(buffer, filepath);
                }
                catch (e) {
                    err = e;
                }
                callback(err, dimensions);
            });
        }
        else {
            var buffer = syncFileToBuffer(filepath);
            return lookup(buffer, filepath);
        }
    };
    module.exports.types = types;
}
,
/* image-size/lib/types */ function _(require, module, exports) {
    module.exports = [
        'bmp',
        'gif',
        'jpg',
        'png',
        'psd',
        'svg',
        'tiff',
        'webp',
        'dds'
    ];
}
,
/* invert-kv/index */ function _(require, module, exports) {
    module.exports = function (obj) {
        if (typeof obj !== 'object') {
            throw new TypeError('Expected an object');
        }
        var ret = {};
        for (var key in obj) {
            var val = obj[key];
            ret[val] = key;
        }
        return ret;
    };
}
,
/* is-buffer/index */ function _(require, module, exports) {
    /*!
     * Determine if an object is a Buffer
     *
     * @author   Feross Aboukhadijeh <https://feross.org>
     * @license  MIT
     */
    // 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);
    }
    // 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));
    }
}
,
/* is-fullwidth-code-point/index */ function _(require, module, exports) {
    /* eslint-disable yoda */
    module.exports = x => {
        if (Number.isNaN(x)) {
            return false;
        }
        // code points are derived from:
        // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
        if (x >= 0x1100 && (x <= 0x115f || // Hangul Jamo
            x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
            x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
            // CJK Radicals Supplement .. Enclosed CJK Letters and Months
            (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
            // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
            (0x3250 <= x && x <= 0x4dbf) ||
            // CJK Unified Ideographs .. Yi Radicals
            (0x4e00 <= x && x <= 0xa4c6) ||
            // Hangul Jamo Extended-A
            (0xa960 <= x && x <= 0xa97c) ||
            // Hangul Syllables
            (0xac00 <= x && x <= 0xd7a3) ||
            // CJK Compatibility Ideographs
            (0xf900 <= x && x <= 0xfaff) ||
            // Vertical Forms
            (0xfe10 <= x && x <= 0xfe19) ||
            // CJK Compatibility Forms .. Small Form Variants
            (0xfe30 <= x && x <= 0xfe6b) ||
            // Halfwidth and Fullwidth Forms
            (0xff01 <= x && x <= 0xff60) ||
            (0xffe0 <= x && x <= 0xffe6) ||
            // Kana Supplement
            (0x1b000 <= x && x <= 0x1b001) ||
            // Enclosed Ideographic Supplement
            (0x1f200 <= x && x <= 0x1f251) ||
            // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
            (0x20000 <= x && x <= 0x3fffd))) {
            return true;
        }
        return false;
    };
}
,
/* is-stream/index */ function _(require, module, exports) {
    var isStream = module.exports = function (stream) {
        return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function';
    };
    isStream.writable = function (stream) {
        return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object';
    };
    isStream.readable = function (stream) {
        return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object';
    };
    isStream.duplex = function (stream) {
        return isStream.writable(stream) && isStream.readable(stream);
    };
    isStream.transform = function (stream) {
        return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object';
    };
}
,
/* is-typedarray/index */ function _(require, module, exports) {
    module.exports = isTypedArray;
    isTypedArray.strict = isStrictTypedArray;
    isTypedArray.loose = isLooseTypedArray;
    var toString = Object.prototype.toString;
    var names = {
        '[object Int8Array]': true,
        '[object Int16Array]': true,
        '[object Int32Array]': true,
        '[object Uint8Array]': true,
        '[object Uint8ClampedArray]': true,
        '[object Uint16Array]': true,
        '[object Uint32Array]': true,
        '[object Float32Array]': true,
        '[object Float64Array]': true
    };
    function isTypedArray(arr) {
        return (isStrictTypedArray(arr)
            || isLooseTypedArray(arr));
    }
    function isStrictTypedArray(arr) {
        return (arr instanceof Int8Array
            || arr instanceof Int16Array
            || arr instanceof Int32Array
            || arr instanceof Uint8Array
            || arr instanceof Uint8ClampedArray
            || arr instanceof Uint16Array
            || arr instanceof Uint32Array
            || arr instanceof Float32Array
            || arr instanceof Float64Array);
    }
    function isLooseTypedArray(arr) {
        return names[toString.call(arr)];
    }
}
,
/* isexe/index */ function _(require, module, exports) {
    var fs = require('fs');
    var core;
    if (process.platform === 'win32' || global.TESTING_WINDOWS) {
        core = require(153) /* ./windows.js */;
    }
    else {
        core = require(152) /* ./mode.js */;
    }
    module.exports = isexe;
    isexe.sync = sync;
    function isexe(path, options, cb) {
        if (typeof options === 'function') {
            cb = options;
            options = {};
        }
        if (!cb) {
            if (typeof Promise !== 'function') {
                throw new TypeError('callback not provided');
            }
            return new Promise(function (resolve, reject) {
                isexe(path, options || {}, function (er, is) {
                    if (er) {
                        reject(er);
                    }
                    else {
                        resolve(is);
                    }
                });
            });
        }
        core(path, options || {}, function (er, is) {
            // ignore EACCES because that just means we aren't allowed to run it
            if (er) {
                if (er.code === 'EACCES' || options && options.ignoreErrors) {
                    er = null;
                    is = false;
                }
            }
            cb(er, is);
        });
    }
    function sync(path, options) {
        // my kingdom for a filtered catch
        try {
            return core.sync(path, options || {});
        }
        catch (er) {
            if (options && options.ignoreErrors || er.code === 'EACCES') {
                return false;
            }
            else {
                throw er;
            }
        }
    }
}
,
/* isexe/mode */ function _(require, module, exports) {
    module.exports = isexe;
    isexe.sync = sync;
    var fs = require('fs');
    function isexe(path, options, cb) {
        fs.stat(path, function (er, stat) {
            cb(er, er ? false : checkStat(stat, options));
        });
    }
    function sync(path, options) {
        return checkStat(fs.statSync(path), options);
    }
    function checkStat(stat, options) {
        return stat.isFile() && checkMode(stat, options);
    }
    function checkMode(stat, options) {
        var mod = stat.mode;
        var uid = stat.uid;
        var gid = stat.gid;
        var myUid = options.uid !== undefined ?
            options.uid : process.getuid && process.getuid();
        var myGid = options.gid !== undefined ?
            options.gid : process.getgid && process.getgid();
        var u = parseInt('100', 8);
        var g = parseInt('010', 8);
        var o = parseInt('001', 8);
        var ug = u | g;
        var ret = (mod & o) ||
            (mod & g) && gid === myGid ||
            (mod & u) && uid === myUid ||
            (mod & ug) && myUid === 0;
        return ret;
    }
}
,
/* isexe/windows */ function _(require, module, exports) {
    module.exports = isexe;
    isexe.sync = sync;
    var fs = require('fs');
    function checkPathExt(path, options) {
        var pathext = options.pathExt !== undefined ?
            options.pathExt : process.env.PATHEXT;
        if (!pathext) {
            return true;
        }
        pathext = pathext.split(';');
        if (pathext.indexOf('') !== -1) {
            return true;
        }
        for (var i = 0; i < pathext.length; i++) {
            var p = pathext[i].toLowerCase();
            if (p && path.substr(-p.length).toLowerCase() === p) {
                return true;
            }
        }
        return false;
    }
    function checkStat(stat, path, options) {
        if (!stat.isSymbolicLink() && !stat.isFile()) {
            return false;
        }
        return checkPathExt(path, options);
    }
    function isexe(path, options, cb) {
        fs.stat(path, function (er, stat) {
            cb(er, er ? false : checkStat(stat, path, options));
        });
    }
    function sync(path, options) {
        return checkStat(fs.statSync(path), path, options);
    }
}
,
/* isstream/isstream */ function _(require, module, exports) {
    var stream = require('stream');
    function isStream(obj) {
        return obj instanceof stream.Stream;
    }
    function isReadable(obj) {
        return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object';
    }
    function isWritable(obj) {
        return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object';
    }
    function isDuplex(obj) {
        return isReadable(obj) && isWritable(obj);
    }
    module.exports = isStream;
    module.exports.isReadable = isReadable;
    module.exports.isWritable = isWritable;
    module.exports.isDuplex = isDuplex;
}
,
/* jsbn/index */ function _(require, module, exports) {
    (function () {
        // Copyright (c) 2005  Tom Wu
        // All Rights Reserved.
        // See "LICENSE" for details.
        // Basic JavaScript BN library - subset useful for RSA encryption.
        // Bits per digit
        var dbits;
        // JavaScript engine analysis
        var canary = 0xdeadbeefcafe;
        var j_lm = ((canary & 0xffffff) == 0xefcafe);
        // (public) Constructor
        function BigInteger(a, b, c) {
            if (a != null)
                if ("number" == typeof a)
                    this.fromNumber(a, b, c);
                else if (b == null && "string" != typeof a)
                    this.fromString(a, 256);
                else
                    this.fromString(a, b);
        }
        // return new, unset BigInteger
        function nbi() { return new BigInteger(null); }
        // am: Compute w_j += (x*this_i), propagate carries,
        // c is initial carry, returns final carry.
        // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
        // We need to select the fastest one that works in this environment.
        // am1: use a single mult and divide to get the high bits,
        // max digit bits should be 26 because
        // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
        function am1(i, x, w, j, c, n) {
            while (--n >= 0) {
                var v = x * this[i++] + w[j] + c;
                c = Math.floor(v / 0x4000000);
                w[j++] = v & 0x3ffffff;
            }
            return c;
        }
        // am2 avoids a big mult-and-extract completely.
        // Max digit bits should be <= 30 because we do bitwise ops
        // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
        function am2(i, x, w, j, c, n) {
            var xl = x & 0x7fff, xh = x >> 15;
            while (--n >= 0) {
                var l = this[i] & 0x7fff;
                var h = this[i++] >> 15;
                var m = xh * l + h * xl;
                l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
                c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
                w[j++] = l & 0x3fffffff;
            }
            return c;
        }
        // Alternately, set max digit bits to 28 since some
        // browsers slow down when dealing with 32-bit numbers.
        function am3(i, x, w, j, c, n) {
            var xl = x & 0x3fff, xh = x >> 14;
            while (--n >= 0) {
                var l = this[i] & 0x3fff;
                var h = this[i++] >> 14;
                var m = xh * l + h * xl;
                l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
                c = (l >> 28) + (m >> 14) + xh * h;
                w[j++] = l & 0xfffffff;
            }
            return c;
        }
        var inBrowser = typeof navigator !== "undefined";
        if (inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
            BigInteger.prototype.am = am2;
            dbits = 30;
        }
        else if (inBrowser && j_lm && (navigator.appName != "Netscape")) {
            BigInteger.prototype.am = am1;
            dbits = 26;
        }
        else { // Mozilla/Netscape seems to prefer am3
            BigInteger.prototype.am = am3;
            dbits = 28;
        }
        BigInteger.prototype.DB = dbits;
        BigInteger.prototype.DM = ((1 << dbits) - 1);
        BigInteger.prototype.DV = (1 << dbits);
        var BI_FP = 52;
        BigInteger.prototype.FV = Math.pow(2, BI_FP);
        BigInteger.prototype.F1 = BI_FP - dbits;
        BigInteger.prototype.F2 = 2 * dbits - BI_FP;
        // Digit conversions
        var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
        var BI_RC = new Array();
        var rr, vv;
        rr = "0".charCodeAt(0);
        for (vv = 0; vv <= 9; ++vv)
            BI_RC[rr++] = vv;
        rr = "a".charCodeAt(0);
        for (vv = 10; vv < 36; ++vv)
            BI_RC[rr++] = vv;
        rr = "A".charCodeAt(0);
        for (vv = 10; vv < 36; ++vv)
            BI_RC[rr++] = vv;
        function int2char(n) { return BI_RM.charAt(n); }
        function intAt(s, i) {
            var c = BI_RC[s.charCodeAt(i)];
            return (c == null) ? -1 : c;
        }
        // (protected) copy this to r
        function bnpCopyTo(r) {
            for (var i = this.t - 1; i >= 0; --i)
                r[i] = this[i];
            r.t = this.t;
            r.s = this.s;
        }
        // (protected) set from integer value x, -DV <= x < DV
        function bnpFromInt(x) {
            this.t = 1;
            this.s = (x < 0) ? -1 : 0;
            if (x > 0)
                this[0] = x;
            else if (x < -1)
                this[0] = x + this.DV;
            else
                this.t = 0;
        }
        // return bigint initialized to value
        function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
        // (protected) set from string and radix
        function bnpFromString(s, b) {
            var k;
            if (b == 16)
                k = 4;
            else if (b == 8)
                k = 3;
            else if (b == 256)
                k = 8; // byte array
            else if (b == 2)
                k = 1;
            else if (b == 32)
                k = 5;
            else if (b == 4)
                k = 2;
            else {
                this.fromRadix(s, b);
                return;
            }
            this.t = 0;
            this.s = 0;
            var i = s.length, mi = false, sh = 0;
            while (--i >= 0) {
                var x = (k == 8) ? s[i] & 0xff : intAt(s, i);
                if (x < 0) {
                    if (s.charAt(i) == "-")
                        mi = true;
                    continue;
                }
                mi = false;
                if (sh == 0)
                    this[this.t++] = x;
                else if (sh + k > this.DB) {
                    this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
                    this[this.t++] = (x >> (this.DB - sh));
                }
                else
                    this[this.t - 1] |= x << sh;
                sh += k;
                if (sh >= this.DB)
                    sh -= this.DB;
            }
            if (k == 8 && (s[0] & 0x80) != 0) {
                this.s = -1;
                if (sh > 0)
                    this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
            }
            this.clamp();
            if (mi)
                BigInteger.ZERO.subTo(this, this);
        }
        // (protected) clamp off excess high words
        function bnpClamp() {
            var c = this.s & this.DM;
            while (this.t > 0 && this[this.t - 1] == c)
                --this.t;
        }
        // (public) return string representation in given radix
        function bnToString(b) {
            if (this.s < 0)
                return "-" + this.negate().toString(b);
            var k;
            if (b == 16)
                k = 4;
            else if (b == 8)
                k = 3;
            else if (b == 2)
                k = 1;
            else if (b == 32)
                k = 5;
            else if (b == 4)
                k = 2;
            else
                return this.toRadix(b);
            var km = (1 << k) - 1, d, m = false, r = "", i = this.t;
            var p = this.DB - (i * this.DB) % k;
            if (i-- > 0) {
                if (p < this.DB && (d = this[i] >> p) > 0) {
                    m = true;
                    r = int2char(d);
                }
                while (i >= 0) {
                    if (p < k) {
                        d = (this[i] & ((1 << p) - 1)) << (k - p);
                        d |= this[--i] >> (p += this.DB - k);
                    }
                    else {
                        d = (this[i] >> (p -= k)) & km;
                        if (p <= 0) {
                            p += this.DB;
                            --i;
                        }
                    }
                    if (d > 0)
                        m = true;
                    if (m)
                        r += int2char(d);
                }
            }
            return m ? r : "0";
        }
        // (public) -this
        function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; }
        // (public) |this|
        function bnAbs() { return (this.s < 0) ? this.negate() : this; }
        // (public) return + if this > a, - if this < a, 0 if equal
        function bnCompareTo(a) {
            var r = this.s - a.s;
            if (r != 0)
                return r;
            var i = this.t;
            r = i - a.t;
            if (r != 0)
                return (this.s < 0) ? -r : r;
            while (--i >= 0)
                if ((r = this[i] - a[i]) != 0)
                    return r;
            return 0;
        }
        // returns bit length of the integer x
        function nbits(x) {
            var r = 1, t;
            if ((t = x >>> 16) != 0) {
                x = t;
                r += 16;
            }
            if ((t = x >> 8) != 0) {
                x = t;
                r += 8;
            }
            if ((t = x >> 4) != 0) {
                x = t;
                r += 4;
            }
            if ((t = x >> 2) != 0) {
                x = t;
                r += 2;
            }
            if ((t = x >> 1) != 0) {
                x = t;
                r += 1;
            }
            return r;
        }
        // (public) return the number of bits in "this"
        function bnBitLength() {
            if (this.t <= 0)
                return 0;
            return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
        }
        // (protected) r = this << n*DB
        function bnpDLShiftTo(n, r) {
            var i;
            for (i = this.t - 1; i >= 0; --i)
                r[i + n] = this[i];
            for (i = n - 1; i >= 0; --i)
                r[i] = 0;
            r.t = this.t + n;
            r.s = this.s;
        }
        // (protected) r = this >> n*DB
        function bnpDRShiftTo(n, r) {
            for (var i = n; i < this.t; ++i)
                r[i - n] = this[i];
            r.t = Math.max(this.t - n, 0);
            r.s = this.s;
        }
        // (protected) r = this << n
        function bnpLShiftTo(n, r) {
            var bs = n % this.DB;
            var cbs = this.DB - bs;
            var bm = (1 << cbs) - 1;
            var ds = Math.floor(n / this.DB), c = (this.s << bs) & this.DM, i;
            for (i = this.t - 1; i >= 0; --i) {
                r[i + ds + 1] = (this[i] >> cbs) | c;
                c = (this[i] & bm) << bs;
            }
            for (i = ds - 1; i >= 0; --i)
                r[i] = 0;
            r[ds] = c;
            r.t = this.t + ds + 1;
            r.s = this.s;
            r.clamp();
        }
        // (protected) r = this >> n
        function bnpRShiftTo(n, r) {
            r.s = this.s;
            var ds = Math.floor(n / this.DB);
            if (ds >= this.t) {
                r.t = 0;
                return;
            }
            var bs = n % this.DB;
            var cbs = this.DB - bs;
            var bm = (1 << bs) - 1;
            r[0] = this[ds] >> bs;
            for (var i = ds + 1; i < this.t; ++i) {
                r[i - ds - 1] |= (this[i] & bm) << cbs;
                r[i - ds] = this[i] >> bs;
            }
            if (bs > 0)
                r[this.t - ds - 1] |= (this.s & bm) << cbs;
            r.t = this.t - ds;
            r.clamp();
        }
        // (protected) r = this - a
        function bnpSubTo(a, r) {
            var i = 0, c = 0, m = Math.min(a.t, this.t);
            while (i < m) {
                c += this[i] - a[i];
                r[i++] = c & this.DM;
                c >>= this.DB;
            }
            if (a.t < this.t) {
                c -= a.s;
                while (i < this.t) {
                    c += this[i];
                    r[i++] = c & this.DM;
                    c >>= this.DB;
                }
                c += this.s;
            }
            else {
                c += this.s;
                while (i < a.t) {
                    c -= a[i];
                    r[i++] = c & this.DM;
                    c >>= this.DB;
                }
                c -= a.s;
            }
            r.s = (c < 0) ? -1 : 0;
            if (c < -1)
                r[i++] = this.DV + c;
            else if (c > 0)
                r[i++] = c;
            r.t = i;
            r.clamp();
        }
        // (protected) r = this * a, r != this,a (HAC 14.12)
        // "this" should be the larger one if appropriate.
        function bnpMultiplyTo(a, r) {
            var x = this.abs(), y = a.abs();
            var i = x.t;
            r.t = i + y.t;
            while (--i >= 0)
                r[i] = 0;
            for (i = 0; i < y.t; ++i)
                r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
            r.s = 0;
            r.clamp();
            if (this.s != a.s)
                BigInteger.ZERO.subTo(r, r);
        }
        // (protected) r = this^2, r != this (HAC 14.16)
        function bnpSquareTo(r) {
            var x = this.abs();
            var i = r.t = 2 * x.t;
            while (--i >= 0)
                r[i] = 0;
            for (i = 0; i < x.t - 1; ++i) {
                var c = x.am(i, x[i], r, 2 * i, 0, 1);
                if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
                    r[i + x.t] -= x.DV;
                    r[i + x.t + 1] = 1;
                }
            }
            if (r.t > 0)
                r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
            r.s = 0;
            r.clamp();
        }
        // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
        // r != q, this != m.  q or r may be null.
        function bnpDivRemTo(m, q, r) {
            var pm = m.abs();
            if (pm.t <= 0)
                return;
            var pt = this.abs();
            if (pt.t < pm.t) {
                if (q != null)
                    q.fromInt(0);
                if (r != null)
                    this.copyTo(r);
                return;
            }
            if (r == null)
                r = nbi();
            var y = nbi(), ts = this.s, ms = m.s;
            var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
            if (nsh > 0) {
                pm.lShiftTo(nsh, y);
                pt.lShiftTo(nsh, r);
            }
            else {
                pm.copyTo(y);
                pt.copyTo(r);
            }
            var ys = y.t;
            var y0 = y[ys - 1];
            if (y0 == 0)
                return;
            var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
            var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2;
            var i = r.t, j = i - ys, t = (q == null) ? nbi() : q;
            y.dlShiftTo(j, t);
            if (r.compareTo(t) >= 0) {
                r[r.t++] = 1;
                r.subTo(t, r);
            }
            BigInteger.ONE.dlShiftTo(ys, t);
            t.subTo(y, y); // "negative" y so we can replace sub with am later
            while (y.t < ys)
                y[y.t++] = 0;
            while (--j >= 0) {
                // Estimate quotient digit
                var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
                if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
                    y.dlShiftTo(j, t);
                    r.subTo(t, r);
                    while (r[i] < --qd)
                        r.subTo(t, r);
                }
            }
            if (q != null) {
                r.drShiftTo(ys, q);
                if (ts != ms)
                    BigInteger.ZERO.subTo(q, q);
            }
            r.t = ys;
            r.clamp();
            if (nsh > 0)
                r.rShiftTo(nsh, r); // Denormalize remainder
            if (ts < 0)
                BigInteger.ZERO.subTo(r, r);
        }
        // (public) this mod a
        function bnMod(a) {
            var r = nbi();
            this.abs().divRemTo(a, null, r);
            if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0)
                a.subTo(r, r);
            return r;
        }
        // Modular reduction using "classic" algorithm
        function Classic(m) { this.m = m; }
        function cConvert(x) {
            if (x.s < 0 || x.compareTo(this.m) >= 0)
                return x.mod(this.m);
            else
                return x;
        }
        function cRevert(x) { return x; }
        function cReduce(x) { x.divRemTo(this.m, null, x); }
        function cMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); }
        function cSqrTo(x, r) { x.squareTo(r); this.reduce(r); }
        Classic.prototype.convert = cConvert;
        Classic.prototype.revert = cRevert;
        Classic.prototype.reduce = cReduce;
        Classic.prototype.mulTo = cMulTo;
        Classic.prototype.sqrTo = cSqrTo;
        // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
        // justification:
        //         xy == 1 (mod m)
        //         xy =  1+km
        //   xy(2-xy) = (1+km)(1-km)
        // x[y(2-xy)] = 1-k^2m^2
        // x[y(2-xy)] == 1 (mod m^2)
        // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
        // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
        // JS multiply "overflows" differently from C/C++, so care is needed here.
        function bnpInvDigit() {
            if (this.t < 1)
                return 0;
            var x = this[0];
            if ((x & 1) == 0)
                return 0;
            var y = x & 3; // y == 1/x mod 2^2
            y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
            y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
            y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
            // last step - calculate inverse mod DV directly;
            // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
            y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
            // we really want the negative inverse, and -DV < y < DV
            return (y > 0) ? this.DV - y : -y;
        }
        // Montgomery reduction
        function Montgomery(m) {
            this.m = m;
            this.mp = m.invDigit();
            this.mpl = this.mp & 0x7fff;
            this.mph = this.mp >> 15;
            this.um = (1 << (m.DB - 15)) - 1;
            this.mt2 = 2 * m.t;
        }
        // xR mod m
        function montConvert(x) {
            var r = nbi();
            x.abs().dlShiftTo(this.m.t, r);
            r.divRemTo(this.m, null, r);
            if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0)
                this.m.subTo(r, r);
            return r;
        }
        // x/R mod m
        function montRevert(x) {
            var r = nbi();
            x.copyTo(r);
            this.reduce(r);
            return r;
        }
        // x = x/R mod m (HAC 14.32)
        function montReduce(x) {
            while (x.t <= this.mt2) // pad x so am has enough room later
                x[x.t++] = 0;
            for (var i = 0; i < this.m.t; ++i) {
                // faster way of calculating u0 = x[i]*mp mod DV
                var j = x[i] & 0x7fff;
                var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
                // use am to combine the multiply-shift-add into one call
                j = i + this.m.t;
                x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
                // propagate carry
                while (x[j] >= x.DV) {
                    x[j] -= x.DV;
                    x[++j]++;
                }
            }
            x.clamp();
            x.drShiftTo(this.m.t, x);
            if (x.compareTo(this.m) >= 0)
                x.subTo(this.m, x);
        }
        // r = "x^2/R mod m"; x != r
        function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); }
        // r = "xy/R mod m"; x,y != r
        function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); }
        Montgomery.prototype.convert = montConvert;
        Montgomery.prototype.revert = montRevert;
        Montgomery.prototype.reduce = montReduce;
        Montgomery.prototype.mulTo = montMulTo;
        Montgomery.prototype.sqrTo = montSqrTo;
        // (protected) true iff this is even
        function bnpIsEven() { return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; }
        // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
        function bnpExp(e, z) {
            if (e > 0xffffffff || e < 1)
                return BigInteger.ONE;
            var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1;
            g.copyTo(r);
            while (--i >= 0) {
                z.sqrTo(r, r2);
                if ((e & (1 << i)) > 0)
                    z.mulTo(r2, g, r);
                else {
                    var t = r;
                    r = r2;
                    r2 = t;
                }
            }
            return z.revert(r);
        }
        // (public) this^e % m, 0 <= e < 2^32
        function bnModPowInt(e, m) {
            var z;
            if (e < 256 || m.isEven())
                z = new Classic(m);
            else
                z = new Montgomery(m);
            return this.exp(e, z);
        }
        // protected
        BigInteger.prototype.copyTo = bnpCopyTo;
        BigInteger.prototype.fromInt = bnpFromInt;
        BigInteger.prototype.fromString = bnpFromString;
        BigInteger.prototype.clamp = bnpClamp;
        BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
        BigInteger.prototype.drShiftTo = bnpDRShiftTo;
        BigInteger.prototype.lShiftTo = bnpLShiftTo;
        BigInteger.prototype.rShiftTo = bnpRShiftTo;
        BigInteger.prototype.subTo = bnpSubTo;
        BigInteger.prototype.multiplyTo = bnpMultiplyTo;
        BigInteger.prototype.squareTo = bnpSquareTo;
        BigInteger.prototype.divRemTo = bnpDivRemTo;
        BigInteger.prototype.invDigit = bnpInvDigit;
        BigInteger.prototype.isEven = bnpIsEven;
        BigInteger.prototype.exp = bnpExp;
        // public
        BigInteger.prototype.toString = bnToString;
        BigInteger.prototype.negate = bnNegate;
        BigInteger.prototype.abs = bnAbs;
        BigInteger.prototype.compareTo = bnCompareTo;
        BigInteger.prototype.bitLength = bnBitLength;
        BigInteger.prototype.mod = bnMod;
        BigInteger.prototype.modPowInt = bnModPowInt;
        // "constants"
        BigInteger.ZERO = nbv(0);
        BigInteger.ONE = nbv(1);
        // Copyright (c) 2005-2009  Tom Wu
        // All Rights Reserved.
        // See "LICENSE" for details.
        // Extended JavaScript BN functions, required for RSA private ops.
        // Version 1.1: new BigInteger("0", 10) returns "proper" zero
        // Version 1.2: square() API, isProbablePrime fix
        // (public)
        function bnClone() { var r = nbi(); this.copyTo(r); return r; }
        // (public) return value as integer
        function bnIntValue() {
            if (this.s < 0) {
                if (this.t == 1)
                    return this[0] - this.DV;
                else if (this.t == 0)
                    return -1;
            }
            else if (this.t == 1)
                return this[0];
            else if (this.t == 0)
                return 0;
            // assumes 16 < DB < 32
            return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
        }
        // (public) return value as byte
        function bnByteValue() { return (this.t == 0) ? this.s : (this[0] << 24) >> 24; }
        // (public) return value as short (assumes DB>=16)
        function bnShortValue() { return (this.t == 0) ? this.s : (this[0] << 16) >> 16; }
        // (protected) return x s.t. r^x < DV
        function bnpChunkSize(r) { return Math.floor(Math.LN2 * this.DB / Math.log(r)); }
        // (public) 0 if this == 0, 1 if this > 0
        function bnSigNum() {
            if (this.s < 0)
                return -1;
            else if (this.t <= 0 || (this.t == 1 && this[0] <= 0))
                return 0;
            else
                return 1;
        }
        // (protected) convert to radix string
        function bnpToRadix(b) {
            if (b == null)
                b = 10;
            if (this.signum() == 0 || b < 2 || b > 36)
                return "0";
            var cs = this.chunkSize(b);
            var a = Math.pow(b, cs);
            var d = nbv(a), y = nbi(), z = nbi(), r = "";
            this.divRemTo(d, y, z);
            while (y.signum() > 0) {
                r = (a + z.intValue()).toString(b).substr(1) + r;
                y.divRemTo(d, y, z);
            }
            return z.intValue().toString(b) + r;
        }
        // (protected) convert from radix string
        function bnpFromRadix(s, b) {
            this.fromInt(0);
            if (b == null)
                b = 10;
            var cs = this.chunkSize(b);
            var d = Math.pow(b, cs), mi = false, j = 0, w = 0;
            for (var i = 0; i < s.length; ++i) {
                var x = intAt(s, i);
                if (x < 0) {
                    if (s.charAt(i) == "-" && this.signum() == 0)
                        mi = true;
                    continue;
                }
                w = b * w + x;
                if (++j >= cs) {
                    this.dMultiply(d);
                    this.dAddOffset(w, 0);
                    j = 0;
                    w = 0;
                }
            }
            if (j > 0) {
                this.dMultiply(Math.pow(b, j));
                this.dAddOffset(w, 0);
            }
            if (mi)
                BigInteger.ZERO.subTo(this, this);
        }
        // (protected) alternate constructor
        function bnpFromNumber(a, b, c) {
            if ("number" == typeof b) {
                // new BigInteger(int,int,RNG)
                if (a < 2)
                    this.fromInt(1);
                else {
                    this.fromNumber(a, c);
                    if (!this.testBit(a - 1)) // force MSB set
                        this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
                    if (this.isEven())
                        this.dAddOffset(1, 0); // force odd
                    while (!this.isProbablePrime(b)) {
                        this.dAddOffset(2, 0);
                        if (this.bitLength() > a)
                            this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
                    }
                }
            }
            else {
                // new BigInteger(int,RNG)
                var x = new Array(), t = a & 7;
                x.length = (a >> 3) + 1;
                b.nextBytes(x);
                if (t > 0)
                    x[0] &= ((1 << t) - 1);
                else
                    x[0] = 0;
                this.fromString(x, 256);
            }
        }
        // (public) convert to bigendian byte array
        function bnToByteArray() {
            var i = this.t, r = new Array();
            r[0] = this.s;
            var p = this.DB - (i * this.DB) % 8, d, k = 0;
            if (i-- > 0) {
                if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p)
                    r[k++] = d | (this.s << (this.DB - p));
                while (i >= 0) {
                    if (p < 8) {
                        d = (this[i] & ((1 << p) - 1)) << (8 - p);
                        d |= this[--i] >> (p += this.DB - 8);
                    }
                    else {
                        d = (this[i] >> (p -= 8)) & 0xff;
                        if (p <= 0) {
                            p += this.DB;
                            --i;
                        }
                    }
                    if ((d & 0x80) != 0)
                        d |= -256;
                    if (k == 0 && (this.s & 0x80) != (d & 0x80))
                        ++k;
                    if (k > 0 || d != this.s)
                        r[k++] = d;
                }
            }
            return r;
        }
        function bnEquals(a) { return (this.compareTo(a) == 0); }
        function bnMin(a) { return (this.compareTo(a) < 0) ? this : a; }
        function bnMax(a) { return (this.compareTo(a) > 0) ? this : a; }
        // (protected) r = this op a (bitwise)
        function bnpBitwiseTo(a, op, r) {
            var i, f, m = Math.min(a.t, this.t);
            for (i = 0; i < m; ++i)
                r[i] = op(this[i], a[i]);
            if (a.t < this.t) {
                f = a.s & this.DM;
                for (i = m; i < this.t; ++i)
                    r[i] = op(this[i], f);
                r.t = this.t;
            }
            else {
                f = this.s & this.DM;
                for (i = m; i < a.t; ++i)
                    r[i] = op(f, a[i]);
                r.t = a.t;
            }
            r.s = op(this.s, a.s);
            r.clamp();
        }
        // (public) this & a
        function op_and(x, y) { return x & y; }
        function bnAnd(a) { var r = nbi(); this.bitwiseTo(a, op_and, r); return r; }
        // (public) this | a
        function op_or(x, y) { return x | y; }
        function bnOr(a) { var r = nbi(); this.bitwiseTo(a, op_or, r); return r; }
        // (public) this ^ a
        function op_xor(x, y) { return x ^ y; }
        function bnXor(a) { var r = nbi(); this.bitwiseTo(a, op_xor, r); return r; }
        // (public) this & ~a
        function op_andnot(x, y) { return x & ~y; }
        function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a, op_andnot, r); return r; }
        // (public) ~this
        function bnNot() {
            var r = nbi();
            for (var i = 0; i < this.t; ++i)
                r[i] = this.DM & ~this[i];
            r.t = this.t;
            r.s = ~this.s;
            return r;
        }
        // (public) this << n
        function bnShiftLeft(n) {
            var r = nbi();
            if (n < 0)
                this.rShiftTo(-n, r);
            else
                this.lShiftTo(n, r);
            return r;
        }
        // (public) this >> n
        function bnShiftRight(n) {
            var r = nbi();
            if (n < 0)
                this.lShiftTo(-n, r);
            else
                this.rShiftTo(n, r);
            return r;
        }
        // return index of lowest 1-bit in x, x < 2^31
        function lbit(x) {
            if (x == 0)
                return -1;
            var r = 0;
            if ((x & 0xffff) == 0) {
                x >>= 16;
                r += 16;
            }
            if ((x & 0xff) == 0) {
                x >>= 8;
                r += 8;
            }
            if ((x & 0xf) == 0) {
                x >>= 4;
                r += 4;
            }
            if ((x & 3) == 0) {
                x >>= 2;
                r += 2;
            }
            if ((x & 1) == 0)
                ++r;
            return r;
        }
        // (public) returns index of lowest 1-bit (or -1 if none)
        function bnGetLowestSetBit() {
            for (var i = 0; i < this.t; ++i)
                if (this[i] != 0)
                    return i * this.DB + lbit(this[i]);
            if (this.s < 0)
                return this.t * this.DB;
            return -1;
        }
        // return number of 1 bits in x
        function cbit(x) {
            var r = 0;
            while (x != 0) {
                x &= x - 1;
                ++r;
            }
            return r;
        }
        // (public) return number of set bits
        function bnBitCount() {
            var r = 0, x = this.s & this.DM;
            for (var i = 0; i < this.t; ++i)
                r += cbit(this[i] ^ x);
            return r;
        }
        // (public) true iff nth bit is set
        function bnTestBit(n) {
            var j = Math.floor(n / this.DB);
            if (j >= this.t)
                return (this.s != 0);
            return ((this[j] & (1 << (n % this.DB))) != 0);
        }
        // (protected) this op (1<<n)
        function bnpChangeBit(n, op) {
            var r = BigInteger.ONE.shiftLeft(n);
            this.bitwiseTo(r, op, r);
            return r;
        }
        // (public) this | (1<<n)
        function bnSetBit(n) { return this.changeBit(n, op_or); }
        // (public) this & ~(1<<n)
        function bnClearBit(n) { return this.changeBit(n, op_andnot); }
        // (public) this ^ (1<<n)
        function bnFlipBit(n) { return this.changeBit(n, op_xor); }
        // (protected) r = this + a
        function bnpAddTo(a, r) {
            var i = 0, c = 0, m = Math.min(a.t, this.t);
            while (i < m) {
                c += this[i] + a[i];
                r[i++] = c & this.DM;
                c >>= this.DB;
            }
            if (a.t < this.t) {
                c += a.s;
                while (i < this.t) {
                    c += this[i];
                    r[i++] = c & this.DM;
                    c >>= this.DB;
                }
                c += this.s;
            }
            else {
                c += this.s;
                while (i < a.t) {
                    c += a[i];
                    r[i++] = c & this.DM;
                    c >>= this.DB;
                }
                c += a.s;
            }
            r.s = (c < 0) ? -1 : 0;
            if (c > 0)
                r[i++] = c;
            else if (c < -1)
                r[i++] = this.DV + c;
            r.t = i;
            r.clamp();
        }
        // (public) this + a
        function bnAdd(a) { var r = nbi(); this.addTo(a, r); return r; }
        // (public) this - a
        function bnSubtract(a) { var r = nbi(); this.subTo(a, r); return r; }
        // (public) this * a
        function bnMultiply(a) { var r = nbi(); this.multiplyTo(a, r); return r; }
        // (public) this^2
        function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
        // (public) this / a
        function bnDivide(a) { var r = nbi(); this.divRemTo(a, r, null); return r; }
        // (public) this % a
        function bnRemainder(a) { var r = nbi(); this.divRemTo(a, null, r); return r; }
        // (public) [this/a,this%a]
        function bnDivideAndRemainder(a) {
            var q = nbi(), r = nbi();
            this.divRemTo(a, q, r);
            return new Array(q, r);
        }
        // (protected) this *= n, this >= 0, 1 < n < DV
        function bnpDMultiply(n) {
            this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
            ++this.t;
            this.clamp();
        }
        // (protected) this += n << w words, this >= 0
        function bnpDAddOffset(n, w) {
            if (n == 0)
                return;
            while (this.t <= w)
                this[this.t++] = 0;
            this[w] += n;
            while (this[w] >= this.DV) {
                this[w] -= this.DV;
                if (++w >= this.t)
                    this[this.t++] = 0;
                ++this[w];
            }
        }
        // A "null" reducer
        function NullExp() { }
        function nNop(x) { return x; }
        function nMulTo(x, y, r) { x.multiplyTo(y, r); }
        function nSqrTo(x, r) { x.squareTo(r); }
        NullExp.prototype.convert = nNop;
        NullExp.prototype.revert = nNop;
        NullExp.prototype.mulTo = nMulTo;
        NullExp.prototype.sqrTo = nSqrTo;
        // (public) this^e
        function bnPow(e) { return this.exp(e, new NullExp()); }
        // (protected) r = lower n words of "this * a", a.t <= n
        // "this" should be the larger one if appropriate.
        function bnpMultiplyLowerTo(a, n, r) {
            var i = Math.min(this.t + a.t, n);
            r.s = 0; // assumes a,this >= 0
            r.t = i;
            while (i > 0)
                r[--i] = 0;
            var j;
            for (j = r.t - this.t; i < j; ++i)
                r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
            for (j = Math.min(a.t, n); i < j; ++i)
                this.am(0, a[i], r, i, 0, n - i);
            r.clamp();
        }
        // (protected) r = "this * a" without lower n words, n > 0
        // "this" should be the larger one if appropriate.
        function bnpMultiplyUpperTo(a, n, r) {
            --n;
            var i = r.t = this.t + a.t - n;
            r.s = 0; // assumes a,this >= 0
            while (--i >= 0)
                r[i] = 0;
            for (i = Math.max(n - this.t, 0); i < a.t; ++i)
                r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
            r.clamp();
            r.drShiftTo(1, r);
        }
        // Barrett modular reduction
        function Barrett(m) {
            // setup Barrett
            this.r2 = nbi();
            this.q3 = nbi();
            BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
            this.mu = this.r2.divide(m);
            this.m = m;
        }
        function barrettConvert(x) {
            if (x.s < 0 || x.t > 2 * this.m.t)
                return x.mod(this.m);
            else if (x.compareTo(this.m) < 0)
                return x;
            else {
                var r = nbi();
                x.copyTo(r);
                this.reduce(r);
                return r;
            }
        }
        function barrettRevert(x) { return x; }
        // x = x mod m (HAC 14.42)
        function barrettReduce(x) {
            x.drShiftTo(this.m.t - 1, this.r2);
            if (x.t > this.m.t + 1) {
                x.t = this.m.t + 1;
                x.clamp();
            }
            this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
            this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
            while (x.compareTo(this.r2) < 0)
                x.dAddOffset(1, this.m.t + 1);
            x.subTo(this.r2, x);
            while (x.compareTo(this.m) >= 0)
                x.subTo(this.m, x);
        }
        // r = x^2 mod m; x != r
        function barrettSqrTo(x, r) { x.squareTo(r); this.reduce(r); }
        // r = x*y mod m; x,y != r
        function barrettMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); }
        Barrett.prototype.convert = barrettConvert;
        Barrett.prototype.revert = barrettRevert;
        Barrett.prototype.reduce = barrettReduce;
        Barrett.prototype.mulTo = barrettMulTo;
        Barrett.prototype.sqrTo = barrettSqrTo;
        // (public) this^e % m (HAC 14.85)
        function bnModPow(e, m) {
            var i = e.bitLength(), k, r = nbv(1), z;
            if (i <= 0)
                return r;
            else if (i < 18)
                k = 1;
            else if (i < 48)
                k = 3;
            else if (i < 144)
                k = 4;
            else if (i < 768)
                k = 5;
            else
                k = 6;
            if (i < 8)
                z = new Classic(m);
            else if (m.isEven())
                z = new Barrett(m);
            else
                z = new Montgomery(m);
            // precomputation
            var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1;
            g[1] = z.convert(this);
            if (k > 1) {
                var g2 = nbi();
                z.sqrTo(g[1], g2);
                while (n <= km) {
                    g[n] = nbi();
                    z.mulTo(g2, g[n - 2], g[n]);
                    n += 2;
                }
            }
            var j = e.t - 1, w, is1 = true, r2 = nbi(), t;
            i = nbits(e[j]) - 1;
            while (j >= 0) {
                if (i >= k1)
                    w = (e[j] >> (i - k1)) & km;
                else {
                    w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
                    if (j > 0)
                        w |= e[j - 1] >> (this.DB + i - k1);
                }
                n = k;
                while ((w & 1) == 0) {
                    w >>= 1;
                    --n;
                }
                if ((i -= n) < 0) {
                    i += this.DB;
                    --j;
                }
                if (is1) { // ret == 1, don't bother squaring or multiplying it
                    g[w].copyTo(r);
                    is1 = false;
                }
                else {
                    while (n > 1) {
                        z.sqrTo(r, r2);
                        z.sqrTo(r2, r);
                        n -= 2;
                    }
                    if (n > 0)
                        z.sqrTo(r, r2);
                    else {
                        t = r;
                        r = r2;
                        r2 = t;
                    }
                    z.mulTo(r2, g[w], r);
                }
                while (j >= 0 && (e[j] & (1 << i)) == 0) {
                    z.sqrTo(r, r2);
                    t = r;
                    r = r2;
                    r2 = t;
                    if (--i < 0) {
                        i = this.DB - 1;
                        --j;
                    }
                }
            }
            return z.revert(r);
        }
        // (public) gcd(this,a) (HAC 14.54)
        function bnGCD(a) {
            var x = (this.s < 0) ? this.negate() : this.clone();
            var y = (a.s < 0) ? a.negate() : a.clone();
            if (x.compareTo(y) < 0) {
                var t = x;
                x = y;
                y = t;
            }
            var i = x.getLowestSetBit(), g = y.getLowestSetBit();
            if (g < 0)
                return x;
            if (i < g)
                g = i;
            if (g > 0) {
                x.rShiftTo(g, x);
                y.rShiftTo(g, y);
            }
            while (x.signum() > 0) {
                if ((i = x.getLowestSetBit()) > 0)
                    x.rShiftTo(i, x);
                if ((i = y.getLowestSetBit()) > 0)
                    y.rShiftTo(i, y);
                if (x.compareTo(y) >= 0) {
                    x.subTo(y, x);
                    x.rShiftTo(1, x);
                }
                else {
                    y.subTo(x, y);
                    y.rShiftTo(1, y);
                }
            }
            if (g > 0)
                y.lShiftTo(g, y);
            return y;
        }
        // (protected) this % n, n < 2^26
        function bnpModInt(n) {
            if (n <= 0)
                return 0;
            var d = this.DV % n, r = (this.s < 0) ? n - 1 : 0;
            if (this.t > 0)
                if (d == 0)
                    r = this[0] % n;
                else
                    for (var i = this.t - 1; i >= 0; --i)
                        r = (d * r + this[i]) % n;
            return r;
        }
        // (public) 1/this % m (HAC 14.61)
        function bnModInverse(m) {
            var ac = m.isEven();
            if ((this.isEven() && ac) || m.signum() == 0)
                return BigInteger.ZERO;
            var u = m.clone(), v = this.clone();
            var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
            while (u.signum() != 0) {
                while (u.isEven()) {
                    u.rShiftTo(1, u);
                    if (ac) {
                        if (!a.isEven() || !b.isEven()) {
                            a.addTo(this, a);
                            b.subTo(m, b);
                        }
                        a.rShiftTo(1, a);
                    }
                    else if (!b.isEven())
                        b.subTo(m, b);
                    b.rShiftTo(1, b);
                }
                while (v.isEven()) {
                    v.rShiftTo(1, v);
                    if (ac) {
                        if (!c.isEven() || !d.isEven()) {
                            c.addTo(this, c);
                            d.subTo(m, d);
                        }
                        c.rShiftTo(1, c);
                    }
                    else if (!d.isEven())
                        d.subTo(m, d);
                    d.rShiftTo(1, d);
                }
                if (u.compareTo(v) >= 0) {
                    u.subTo(v, u);
                    if (ac)
                        a.subTo(c, a);
                    b.subTo(d, b);
                }
                else {
                    v.subTo(u, v);
                    if (ac)
                        c.subTo(a, c);
                    d.subTo(b, d);
                }
            }
            if (v.compareTo(BigInteger.ONE) != 0)
                return BigInteger.ZERO;
            if (d.compareTo(m) >= 0)
                return d.subtract(m);
            if (d.signum() < 0)
                d.addTo(m, d);
            else
                return d;
            if (d.signum() < 0)
                return d.add(m);
            else
                return d;
        }
        var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
        var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
        // (public) test primality with certainty >= 1-.5^t
        function bnIsProbablePrime(t) {
            var i, x = this.abs();
            if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
                for (i = 0; i < lowprimes.length; ++i)
                    if (x[0] == lowprimes[i])
                        return true;
                return false;
            }
            if (x.isEven())
                return false;
            i = 1;
            while (i < lowprimes.length) {
                var m = lowprimes[i], j = i + 1;
                while (j < lowprimes.length && m < lplim)
                    m *= lowprimes[j++];
                m = x.modInt(m);
                while (i < j)
                    if (m % lowprimes[i++] == 0)
                        return false;
            }
            return x.millerRabin(t);
        }
        // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
        function bnpMillerRabin(t) {
            var n1 = this.subtract(BigInteger.ONE);
            var k = n1.getLowestSetBit();
            if (k <= 0)
                return false;
            var r = n1.shiftRight(k);
            t = (t + 1) >> 1;
            if (t > lowprimes.length)
                t = lowprimes.length;
            var a = nbi();
            for (var i = 0; i < t; ++i) {
                //Pick bases at random, instead of starting at 2
                a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
                var y = a.modPow(r, this);
                if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
                    var j = 1;
                    while (j++ < k && y.compareTo(n1) != 0) {
                        y = y.modPowInt(2, this);
                        if (y.compareTo(BigInteger.ONE) == 0)
                            return false;
                    }
                    if (y.compareTo(n1) != 0)
                        return false;
                }
            }
            return true;
        }
        // protected
        BigInteger.prototype.chunkSize = bnpChunkSize;
        BigInteger.prototype.toRadix = bnpToRadix;
        BigInteger.prototype.fromRadix = bnpFromRadix;
        BigInteger.prototype.fromNumber = bnpFromNumber;
        BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
        BigInteger.prototype.changeBit = bnpChangeBit;
        BigInteger.prototype.addTo = bnpAddTo;
        BigInteger.prototype.dMultiply = bnpDMultiply;
        BigInteger.prototype.dAddOffset = bnpDAddOffset;
        BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
        BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
        BigInteger.prototype.modInt = bnpModInt;
        BigInteger.prototype.millerRabin = bnpMillerRabin;
        // public
        BigInteger.prototype.clone = bnClone;
        BigInteger.prototype.intValue = bnIntValue;
        BigInteger.prototype.byteValue = bnByteValue;
        BigInteger.prototype.shortValue = bnShortValue;
        BigInteger.prototype.signum = bnSigNum;
        BigInteger.prototype.toByteArray = bnToByteArray;
        BigInteger.prototype.equals = bnEquals;
        BigInteger.prototype.min = bnMin;
        BigInteger.prototype.max = bnMax;
        BigInteger.prototype.and = bnAnd;
        BigInteger.prototype.or = bnOr;
        BigInteger.prototype.xor = bnXor;
        BigInteger.prototype.andNot = bnAndNot;
        BigInteger.prototype.not = bnNot;
        BigInteger.prototype.shiftLeft = bnShiftLeft;
        BigInteger.prototype.shiftRight = bnShiftRight;
        BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
        BigInteger.prototype.bitCount = bnBitCount;
        BigInteger.prototype.testBit = bnTestBit;
        BigInteger.prototype.setBit = bnSetBit;
        BigInteger.prototype.clearBit = bnClearBit;
        BigInteger.prototype.flipBit = bnFlipBit;
        BigInteger.prototype.add = bnAdd;
        BigInteger.prototype.subtract = bnSubtract;
        BigInteger.prototype.multiply = bnMultiply;
        BigInteger.prototype.divide = bnDivide;
        BigInteger.prototype.remainder = bnRemainder;
        BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
        BigInteger.prototype.modPow = bnModPow;
        BigInteger.prototype.modInverse = bnModInverse;
        BigInteger.prototype.pow = bnPow;
        BigInteger.prototype.gcd = bnGCD;
        BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
        // JSBN-specific extension
        BigInteger.prototype.square = bnSquare;
        // Expose the Barrett function
        BigInteger.prototype.Barrett = Barrett;
        // BigInteger interfaces not implemented in jsbn:
        // BigInteger(int signum, byte[] magnitude)
        // double doubleValue()
        // float floatValue()
        // int hashCode()
        // long longValue()
        // static BigInteger valueOf(long val)
        // Random number generator - requires a PRNG backend, e.g. prng4.js
        // For best results, put code like
        // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
        // in your main HTML document.
        var rng_state;
        var rng_pool;
        var rng_pptr;
        // Mix in a 32-bit integer into the pool
        function rng_seed_int(x) {
            rng_pool[rng_pptr++] ^= x & 255;
            rng_pool[rng_pptr++] ^= (x >> 8) & 255;
            rng_pool[rng_pptr++] ^= (x >> 16) & 255;
            rng_pool[rng_pptr++] ^= (x >> 24) & 255;
            if (rng_pptr >= rng_psize)
                rng_pptr -= rng_psize;
        }
        // Mix in the current time (w/milliseconds) into the pool
        function rng_seed_time() {
            rng_seed_int(new Date().getTime());
        }
        // Initialize the pool with junk if needed.
        if (rng_pool == null) {
            rng_pool = new Array();
            rng_pptr = 0;
            var t;
            if (typeof window !== "undefined" && window.crypto) {
                if (window.crypto.getRandomValues) {
                    // Use webcrypto if available
                    var ua = new Uint8Array(32);
                    window.crypto.getRandomValues(ua);
                    for (t = 0; t < 32; ++t)
                        rng_pool[rng_pptr++] = ua[t];
                }
                else if (navigator.appName == "Netscape" && navigator.appVersion < "5") {
                    // Extract entropy (256 bits) from NS4 RNG if available
                    var z = window.crypto.random(32);
                    for (t = 0; t < z.length; ++t)
                        rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
                }
            }
            while (rng_pptr < rng_psize) { // extract some randomness from Math.random()
                t = Math.floor(65536 * Math.random());
                rng_pool[rng_pptr++] = t >>> 8;
                rng_pool[rng_pptr++] = t & 255;
            }
            rng_pptr = 0;
            rng_seed_time();
            //rng_seed_int(window.screenX);
            //rng_seed_int(window.screenY);
        }
        function rng_get_byte() {
            if (rng_state == null) {
                rng_seed_time();
                rng_state = prng_newstate();
                rng_state.init(rng_pool);
                for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
                    rng_pool[rng_pptr] = 0;
                rng_pptr = 0;
                //rng_pool = null;
            }
            // TODO: allow reseeding after first request
            return rng_state.next();
        }
        function rng_get_bytes(ba) {
            var i;
            for (i = 0; i < ba.length; ++i)
                ba[i] = rng_get_byte();
        }
        function SecureRandom() { }
        SecureRandom.prototype.nextBytes = rng_get_bytes;
        // prng4.js - uses Arcfour as a PRNG
        function Arcfour() {
            this.i = 0;
            this.j = 0;
            this.S = new Array();
        }
        // Initialize arcfour context from key, an array of ints, each from [0..255]
        function ARC4init(key) {
            var i, j, t;
            for (i = 0; i < 256; ++i)
                this.S[i] = i;
            j = 0;
            for (i = 0; i < 256; ++i) {
                j = (j + this.S[i] + key[i % key.length]) & 255;
                t = this.S[i];
                this.S[i] = this.S[j];
                this.S[j] = t;
            }
            this.i = 0;
            this.j = 0;
        }
        function ARC4next() {
            var t;
            this.i = (this.i + 1) & 255;
            this.j = (this.j + this.S[this.i]) & 255;
            t = this.S[this.i];
            this.S[this.i] = this.S[this.j];
            this.S[this.j] = t;
            return this.S[(t + this.S[this.i]) & 255];
        }
        Arcfour.prototype.init = ARC4init;
        Arcfour.prototype.next = ARC4next;
        // Plug in your RNG constructor here
        function prng_newstate() {
            return new Arcfour();
        }
        // Pool size must be a multiple of 4 and greater than 32.
        // An array of bytes the size of the pool will be passed to init()
        var rng_psize = 256;
        BigInteger.SecureRandom = SecureRandom;
        BigInteger.BigInteger = BigInteger;
        if (typeof exports !== 'undefined') {
            exports = module.exports = BigInteger;
        }
        else {
            this.BigInteger = BigInteger;
            this.SecureRandom = SecureRandom;
        }
    }).call(this);
}
,
/* json-schema-traverse/index */ function _(require, module, exports) {
    var traverse = module.exports = function (schema, opts, cb) {
        if (typeof opts == 'function') {
            cb = opts;
            opts = {};
        }
        _traverse(opts, cb, schema, '', schema);
    };
    traverse.keywords = {
        additionalItems: true,
        items: true,
        contains: true,
        additionalProperties: true,
        propertyNames: true,
        not: true
    };
    traverse.arrayKeywords = {
        items: true,
        allOf: true,
        anyOf: true,
        oneOf: true
    };
    traverse.propsKeywords = {
        definitions: true,
        properties: true,
        patternProperties: true,
        dependencies: true
    };
    traverse.skipKeywords = {
        enum: true,
        const: true,
        required: true,
        maximum: true,
        minimum: true,
        exclusiveMaximum: true,
        exclusiveMinimum: true,
        multipleOf: true,
        maxLength: true,
        minLength: true,
        pattern: true,
        format: true,
        maxItems: true,
        minItems: true,
        uniqueItems: true,
        maxProperties: true,
        minProperties: true
    };
    function _traverse(opts, cb, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
        if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
            cb(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
            for (var key in schema) {
                var sch = schema[key];
                if (Array.isArray(sch)) {
                    if (key in traverse.arrayKeywords) {
                        for (var i = 0; i < sch.length; i++)
                            _traverse(opts, cb, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
                    }
                }
                else if (key in traverse.propsKeywords) {
                    if (sch && typeof sch == 'object') {
                        for (var prop in sch)
                            _traverse(opts, cb, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
                    }
                }
                else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
                    _traverse(opts, cb, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
                }
            }
        }
    }
    function escapeJsonPtr(str) {
        return str.replace(/~/g, '~0').replace(/\//g, '~1');
    }
}
,
/* json-schema/lib/validate */ function _(require, module, exports) {
    /**
     * JSONSchema Validator - Validates JavaScript objects using JSON Schemas
     *	(http://www.json.com/json-schema-proposal/)
     *
     * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
     * Licensed under the MIT (MIT-LICENSE.txt) license.
    To use the validator call the validate function with an instance object and an optional schema object.
    If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
    that schema will be used to validate and the schema parameter is not necessary (if both exist,
    both validations will occur).
    The validate method will return an array of validation errors. If there are no errors, then an
    empty list will be returned. A validation error will have two properties:
    "property" which indicates which property had the error
    "message" which indicates what the error was
     */
    (function (root, factory) {
        if (typeof define === 'function' && define.amd) {
            // AMD. Register as an anonymous module.
            define([], function () {
                return factory();
            });
        }
        else if (typeof module === 'object' && module.exports) {
            // Node. Does not work with strict CommonJS, but
            // only CommonJS-like environments that support module.exports,
            // like Node.
            module.exports = factory();
        }
        else {
            // Browser globals
            root.jsonSchema = factory();
        }
    }(this, function () {
        var exports = validate;
        exports.Integer = { type: "integer" };
        var primitiveConstructors = {
            String: String,
            Boolean: Boolean,
            Number: Number,
            Object: Object,
            Array: Array,
            Date: Date
        };
        exports.validate = validate;
        function validate(/*Any*/ instance, /*Object*/ schema) {
            // Summary:
            //  	To use the validator call JSONSchema.validate with an instance object and an optional schema object.
            // 		If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
            // 		that schema will be used to validate and the schema parameter is not necessary (if both exist,
            // 		both validations will occur).
            // 		The validate method will return an object with two properties:
            // 			valid: A boolean indicating if the instance is valid by the schema
            // 			errors: An array of validation errors. If there are no errors, then an
            // 					empty list will be returned. A validation error will have two properties:
            // 						property: which indicates which property had the error
            // 						message: which indicates what the error was
            //
            return validate(instance, schema, { changing: false }); //, coerce: false, existingOnly: false});
        }
        ;
        exports.checkPropertyChange = function (/*Any*/ value, /*Object*/ schema, /*String*/ property) {
            // Summary:
            // 		The checkPropertyChange method will check to see if an value can legally be in property with the given schema
            // 		This is slightly different than the validate method in that it will fail if the schema is readonly and it will
            // 		not check for self-validation, it is assumed that the passed in value is already internally valid.
            // 		The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for
            // 		information.
            //
            return validate(value, schema, { changing: property || "property" });
        };
        var validate = exports._validate = function (/*Any*/ instance, /*Object*/ schema, /*Object*/ options) {
            if (!options)
                options = {};
            var _changing = options.changing;
            function getType(schema) {
                return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase());
            }
            var errors = [];
            // validate a value against a property definition
            function checkProp(value, schema, path, i) {
                var l;
                path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i;
                function addError(message) {
                    errors.push({ property: path, message: message });
                }
                if ((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))) {
                    if (typeof schema == 'function') {
                        if (!(value instanceof schema)) {
                            addError("is not an instance of the class/constructor " + schema.name);
                        }
                    }
                    else if (schema) {
                        addError("Invalid schema/property definition " + schema);
                    }
                    return null;
                }
                if (_changing && schema.readonly) {
                    addError("is a readonly field, it can not be changed");
                }
                if (schema['extends']) { // if it extends another schema, it must pass that schema as well
                    checkProp(value, schema['extends'], path, i);
                }
                // validate a value against a type definition
                function checkType(type, value) {
                    if (type) {
                        if (typeof type == 'string' && type != 'any' &&
                            (type == 'null' ? value !== null : typeof value != type) &&
                            !(value instanceof Array && type == 'array') &&
                            !(value instanceof Date && type == 'date') &&
                            !(type == 'integer' && value % 1 === 0)) {
                            return [{ property: path, message: (typeof value) + " value found, but a " + type + " is required" }];
                        }
                        if (type instanceof Array) {
                            var unionErrors = [];
                            for (var j = 0; j < type.length; j++) { // a union type
                                if (!(unionErrors = checkType(type[j], value)).length) {
                                    break;
                                }
                            }
                            if (unionErrors.length) {
                                return unionErrors;
                            }
                        }
                        else if (typeof type == 'object') {
                            var priorErrors = errors;
                            errors = [];
                            checkProp(value, type, path);
                            var theseErrors = errors;
                            errors = priorErrors;
                            return theseErrors;
                        }
                    }
                    return [];
                }
                if (value === undefined) {
                    if (schema.required) {
                        addError("is missing and it is required");
                    }
                }
                else {
                    errors = errors.concat(checkType(getType(schema), value));
                    if (schema.disallow && !checkType(schema.disallow, value).length) {
                        addError(" disallowed value was matched");
                    }
                    if (value !== null) {
                        if (value instanceof Array) {
                            if (schema.items) {
                                var itemsIsArray = schema.items instanceof Array;
                                var propDef = schema.items;
                                for (i = 0, l = value.length; i < l; i += 1) {
                                    if (itemsIsArray)
                                        propDef = schema.items[i];
                                    if (options.coerce)
                                        value[i] = options.coerce(value[i], propDef);
                                    errors.concat(checkProp(value[i], propDef, path, i));
                                }
                            }
                            if (schema.minItems && value.length < schema.minItems) {
                                addError("There must be a minimum of " + schema.minItems + " in the array");
                            }
                            if (schema.maxItems && value.length > schema.maxItems) {
                                addError("There must be a maximum of " + schema.maxItems + " in the array");
                            }
                        }
                        else if (schema.properties || schema.additionalProperties) {
                            errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties));
                        }
                        if (schema.pattern && typeof value == 'string' && !value.match(schema.pattern)) {
                            addError("does not match the regex pattern " + schema.pattern);
                        }
                        if (schema.maxLength && typeof value == 'string' && value.length > schema.maxLength) {
                            addError("may only be " + schema.maxLength + " characters long");
                        }
                        if (schema.minLength && typeof value == 'string' && value.length < schema.minLength) {
                            addError("must be at least " + schema.minLength + " characters long");
                        }
                        if (typeof schema.minimum !== undefined && typeof value == typeof schema.minimum &&
                            schema.minimum > value) {
                            addError("must have a minimum value of " + schema.minimum);
                        }
                        if (typeof schema.maximum !== undefined && typeof value == typeof schema.maximum &&
                            schema.maximum < value) {
                            addError("must have a maximum value of " + schema.maximum);
                        }
                        if (schema['enum']) {
                            var enumer = schema['enum'];
                            l = enumer.length;
                            var found;
                            for (var j = 0; j < l; j++) {
                                if (enumer[j] === value) {
                                    found = 1;
                                    break;
                                }
                            }
                            if (!found) {
                                addError("does not have a value in the enumeration " + enumer.join(", "));
                            }
                        }
                        if (typeof schema.maxDecimal == 'number' &&
                            (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))) {
                            addError("may only have " + schema.maxDecimal + " digits of decimal places");
                        }
                    }
                }
                return null;
            }
            // validate an object against a schema
            function checkObj(instance, objTypeDef, path, additionalProp) {
                if (typeof objTypeDef == 'object') {
                    if (typeof instance != 'object' || instance instanceof Array) {
                        errors.push({ property: path, message: "an object is required" });
                    }
                    for (var i in objTypeDef) {
                        if (objTypeDef.hasOwnProperty(i)) {
                            var value = instance[i];
                            // skip _not_ specified properties
                            if (value === undefined && options.existingOnly)
                                continue;
                            var propDef = objTypeDef[i];
                            // set default
                            if (value === undefined && propDef["default"]) {
                                value = instance[i] = propDef["default"];
                            }
                            if (options.coerce && i in instance) {
                                value = instance[i] = options.coerce(value, propDef);
                            }
                            checkProp(value, propDef, path, i);
                        }
                    }
                }
                for (i in instance) {
                    if (instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp === false) {
                        if (options.filter) {
                            delete instance[i];
                            continue;
                        }
                        else {
                            errors.push({ property: path, message: (typeof value) + "The property " + i +
                                    " is not defined in the schema and the schema does not allow additional properties" });
                        }
                    }
                    var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
                    if (requires && !(requires in instance)) {
                        errors.push({ property: path, message: "the presence of the property " + i + " requires that " + requires + " also be present" });
                    }
                    value = instance[i];
                    if (additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))) {
                        if (options.coerce) {
                            value = instance[i] = options.coerce(value, additionalProp);
                        }
                        checkProp(value, additionalProp, path, i);
                    }
                    if (!_changing && value && value.$schema) {
                        errors = errors.concat(checkProp(value, value.$schema, path, i));
                    }
                }
                return errors;
            }
            if (schema) {
                checkProp(instance, schema, '', _changing || '');
            }
            if (!_changing && instance && instance.$schema) {
                checkProp(instance, instance.$schema, '', '');
            }
            return { valid: !errors.length, errors: errors };
        };
        exports.mustBeValid = function (result) {
            //	summary:
            //		This checks to ensure that the result is valid and will throw an appropriate error message if it is not
            // result: the result returned from checkPropertyChange or validate
            if (!result.valid) {
                throw new TypeError(result.errors.map(function (error) { return "for property " + error.property + ': ' + error.message; }).join(", \n"));
            }
        };
        return exports;
    }));
}
,
/* json-stringify-safe/stringify */ function _(require, module, exports) {
    exports = module.exports = stringify;
    exports.getSerialize = serializer;
    function stringify(obj, replacer, spaces, cycleReplacer) {
        return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);
    }
    function serializer(replacer, cycleReplacer) {
        var stack = [], keys = [];
        if (cycleReplacer == null)
            cycleReplacer = function (key, value) {
                if (stack[0] === value)
                    return "[Circular ~]";
                return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
            };
        return function (key, value) {
            if (stack.length > 0) {
                var thisPos = stack.indexOf(this);
                ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
                ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
                if (~stack.indexOf(value))
                    value = cycleReplacer.call(this, key, value);
            }
            else
                stack.push(value);
            return replacer == null ? value : replacer.call(this, key, value);
        };
    }
}
,
/* jsprim/lib/jsprim */ function _(require, module, exports) {
    /*
     * lib/jsprim.js: utilities for primitive JavaScript types
     */
    var mod_assert = require(53) /* assert-plus */;
    var mod_util = require('util');
    var mod_extsprintf = require(107) /* extsprintf */;
    var mod_verror = require(371) /* verror */;
    var mod_jsonschema = require(157) /* json-schema */;
    /*
     * Public interface
     */
    exports.deepCopy = deepCopy;
    exports.deepEqual = deepEqual;
    exports.isEmpty = isEmpty;
    exports.hasKey = hasKey;
    exports.forEachKey = forEachKey;
    exports.pluck = pluck;
    exports.flattenObject = flattenObject;
    exports.flattenIter = flattenIter;
    exports.validateJsonObject = validateJsonObjectJS;
    exports.validateJsonObjectJS = validateJsonObjectJS;
    exports.randElt = randElt;
    exports.extraProperties = extraProperties;
    exports.mergeObjects = mergeObjects;
    exports.startsWith = startsWith;
    exports.endsWith = endsWith;
    exports.parseInteger = parseInteger;
    exports.iso8601 = iso8601;
    exports.rfc1123 = rfc1123;
    exports.parseDateTime = parseDateTime;
    exports.hrtimediff = hrtimeDiff;
    exports.hrtimeDiff = hrtimeDiff;
    exports.hrtimeAccum = hrtimeAccum;
    exports.hrtimeAdd = hrtimeAdd;
    exports.hrtimeNanosec = hrtimeNanosec;
    exports.hrtimeMicrosec = hrtimeMicrosec;
    exports.hrtimeMillisec = hrtimeMillisec;
    /*
     * Deep copy an acyclic *basic* Javascript object.  This only handles basic
     * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects
     * containing these.  This does *not* handle instances of other classes.
     */
    function deepCopy(obj) {
        var ret, key;
        var marker = '__deepCopy';
        if (obj && obj[marker])
            throw (new Error('attempted deep copy of cyclic object'));
        if (obj && obj.constructor == Object) {
            ret = {};
            obj[marker] = true;
            for (key in obj) {
                if (key == marker)
                    continue;
                ret[key] = deepCopy(obj[key]);
            }
            delete (obj[marker]);
            return (ret);
        }
        if (obj && obj.constructor == Array) {
            ret = [];
            obj[marker] = true;
            for (key = 0; key < obj.length; key++)
                ret.push(deepCopy(obj[key]));
            delete (obj[marker]);
            return (ret);
        }
        /*
         * It must be a primitive type -- just return it.
         */
        return (obj);
    }
    function deepEqual(obj1, obj2) {
        if (typeof (obj1) != typeof (obj2))
            return (false);
        if (obj1 === null || obj2 === null || typeof (obj1) != 'object')
            return (obj1 === obj2);
        if (obj1.constructor != obj2.constructor)
            return (false);
        var k;
        for (k in obj1) {
            if (!obj2.hasOwnProperty(k))
                return (false);
            if (!deepEqual(obj1[k], obj2[k]))
                return (false);
        }
        for (k in obj2) {
            if (!obj1.hasOwnProperty(k))
                return (false);
        }
        return (true);
    }
    function isEmpty(obj) {
        var key;
        for (key in obj)
            return (false);
        return (true);
    }
    function hasKey(obj, key) {
        mod_assert.equal(typeof (key), 'string');
        return (Object.prototype.hasOwnProperty.call(obj, key));
    }
    function forEachKey(obj, callback) {
        for (var key in obj) {
            if (hasKey(obj, key)) {
                callback(key, obj[key]);
            }
        }
    }
    function pluck(obj, key) {
        mod_assert.equal(typeof (key), 'string');
        return (pluckv(obj, key));
    }
    function pluckv(obj, key) {
        if (obj === null || typeof (obj) !== 'object')
            return (undefined);
        if (obj.hasOwnProperty(key))
            return (obj[key]);
        var i = key.indexOf('.');
        if (i == -1)
            return (undefined);
        var key1 = key.substr(0, i);
        if (!obj.hasOwnProperty(key1))
            return (undefined);
        return (pluckv(obj[key1], key.substr(i + 1)));
    }
    /*
     * Invoke callback(row) for each entry in the array that would be returned by
     * flattenObject(data, depth).  This is just like flattenObject(data,
     * depth).forEach(callback), except that the intermediate array is never
     * created.
     */
    function flattenIter(data, depth, callback) {
        doFlattenIter(data, depth, [], callback);
    }
    function doFlattenIter(data, depth, accum, callback) {
        var each;
        var key;
        if (depth === 0) {
            each = accum.slice(0);
            each.push(data);
            callback(each);
            return;
        }
        mod_assert.ok(data !== null);
        mod_assert.equal(typeof (data), 'object');
        mod_assert.equal(typeof (depth), 'number');
        mod_assert.ok(depth >= 0);
        for (key in data) {
            each = accum.slice(0);
            each.push(key);
            doFlattenIter(data[key], depth - 1, each, callback);
        }
    }
    function flattenObject(data, depth) {
        if (depth === 0)
            return ([data]);
        mod_assert.ok(data !== null);
        mod_assert.equal(typeof (data), 'object');
        mod_assert.equal(typeof (depth), 'number');
        mod_assert.ok(depth >= 0);
        var rv = [];
        var key;
        for (key in data) {
            flattenObject(data[key], depth - 1).forEach(function (p) {
                rv.push([key].concat(p));
            });
        }
        return (rv);
    }
    function startsWith(str, prefix) {
        return (str.substr(0, prefix.length) == prefix);
    }
    function endsWith(str, suffix) {
        return (str.substr(str.length - suffix.length, suffix.length) == suffix);
    }
    function iso8601(d) {
        if (typeof (d) == 'number')
            d = new Date(d);
        mod_assert.ok(d.constructor === Date);
        return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ', d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()));
    }
    var RFC1123_MONTHS = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    ];
    var RFC1123_DAYS = [
        'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
    ];
    function rfc1123(date) {
        return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT', RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(), RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()));
    }
    /*
     * Parses a date expressed as a string, as either a number of milliseconds since
     * the epoch or any string format that Date accepts, giving preference to the
     * former where these two sets overlap (e.g., small numbers).
     */
    function parseDateTime(str) {
        /*
         * This is irritatingly implicit, but significantly more concise than
         * alternatives.  The "+str" will convert a string containing only a
         * number directly to a Number, or NaN for other strings.  Thus, if the
         * conversion succeeds, we use it (this is the milliseconds-since-epoch
         * case).  Otherwise, we pass the string directly to the Date
         * constructor to parse.
         */
        var numeric = +str;
        if (!isNaN(numeric)) {
            return (new Date(numeric));
        }
        else {
            return (new Date(str));
        }
    }
    /*
     * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode
     * the ES6 definitions here, while allowing for them to someday be higher.
     */
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
    var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
    /*
     * Default options for parseInteger().
     */
    var PI_DEFAULTS = {
        base: 10,
        allowSign: true,
        allowPrefix: false,
        allowTrailing: false,
        allowImprecise: false,
        trimWhitespace: false,
        leadingZeroIsOctal: false
    };
    var CP_0 = 0x30;
    var CP_9 = 0x39;
    var CP_A = 0x41;
    var CP_B = 0x42;
    var CP_O = 0x4f;
    var CP_T = 0x54;
    var CP_X = 0x58;
    var CP_Z = 0x5a;
    var CP_a = 0x61;
    var CP_b = 0x62;
    var CP_o = 0x6f;
    var CP_t = 0x74;
    var CP_x = 0x78;
    var CP_z = 0x7a;
    var PI_CONV_DEC = 0x30;
    var PI_CONV_UC = 0x37;
    var PI_CONV_LC = 0x57;
    /*
     * A stricter version of parseInt() that provides options for changing what
     * is an acceptable string (for example, disallowing trailing characters).
     */
    function parseInteger(str, uopts) {
        mod_assert.string(str, 'str');
        mod_assert.optionalObject(uopts, 'options');
        var baseOverride = false;
        var options = PI_DEFAULTS;
        if (uopts) {
            baseOverride = hasKey(uopts, 'base');
            options = mergeObjects(options, uopts);
            mod_assert.number(options.base, 'options.base');
            mod_assert.ok(options.base >= 2, 'options.base >= 2');
            mod_assert.ok(options.base <= 36, 'options.base <= 36');
            mod_assert.bool(options.allowSign, 'options.allowSign');
            mod_assert.bool(options.allowPrefix, 'options.allowPrefix');
            mod_assert.bool(options.allowTrailing, 'options.allowTrailing');
            mod_assert.bool(options.allowImprecise, 'options.allowImprecise');
            mod_assert.bool(options.trimWhitespace, 'options.trimWhitespace');
            mod_assert.bool(options.leadingZeroIsOctal, 'options.leadingZeroIsOctal');
            if (options.leadingZeroIsOctal) {
                mod_assert.ok(!baseOverride, '"base" and "leadingZeroIsOctal" are ' +
                    'mutually exclusive');
            }
        }
        var c;
        var pbase = -1;
        var base = options.base;
        var start;
        var mult = 1;
        var value = 0;
        var idx = 0;
        var len = str.length;
        /* Trim any whitespace on the left side. */
        if (options.trimWhitespace) {
            while (idx < len && isSpace(str.charCodeAt(idx))) {
                ++idx;
            }
        }
        /* Check the number for a leading sign. */
        if (options.allowSign) {
            if (str[idx] === '-') {
                idx += 1;
                mult = -1;
            }
            else if (str[idx] === '+') {
                idx += 1;
            }
        }
        /* Parse the base-indicating prefix if there is one. */
        if (str[idx] === '0') {
            if (options.allowPrefix) {
                pbase = prefixToBase(str.charCodeAt(idx + 1));
                if (pbase !== -1 && (!baseOverride || pbase === base)) {
                    base = pbase;
                    idx += 2;
                }
            }
            if (pbase === -1 && options.leadingZeroIsOctal) {
                base = 8;
            }
        }
        /* Parse the actual digits. */
        for (start = idx; idx < len; ++idx) {
            c = translateDigit(str.charCodeAt(idx));
            if (c !== -1 && c < base) {
                value *= base;
                value += c;
            }
            else {
                break;
            }
        }
        /* If we didn't parse any digits, we have an invalid number. */
        if (start === idx) {
            return (new Error('invalid number: ' + JSON.stringify(str)));
        }
        /* Trim any whitespace on the right side. */
        if (options.trimWhitespace) {
            while (idx < len && isSpace(str.charCodeAt(idx))) {
                ++idx;
            }
        }
        /* Check for trailing characters. */
        if (idx < len && !options.allowTrailing) {
            return (new Error('trailing characters after number: ' +
                JSON.stringify(str.slice(idx))));
        }
        /* If our value is 0, we return now, to avoid returning -0. */
        if (value === 0) {
            return (0);
        }
        /* Calculate our final value. */
        var result = value * mult;
        /*
         * If the string represents a value that cannot be precisely represented
         * by JavaScript, then we want to check that:
         *
         * - We never increased the value past MAX_SAFE_INTEGER
         * - We don't make the result negative and below MIN_SAFE_INTEGER
         *
         * Because we only ever increment the value during parsing, there's no
         * chance of moving past MAX_SAFE_INTEGER and then dropping below it
         * again, losing precision in the process. This means that we only need
         * to do our checks here, at the end.
         */
        if (!options.allowImprecise &&
            (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) {
            return (new Error('number is outside of the supported range: ' +
                JSON.stringify(str.slice(start, idx))));
        }
        return (result);
    }
    /*
     * Interpret a character code as a base-36 digit.
     */
    function translateDigit(d) {
        if (d >= CP_0 && d <= CP_9) {
            /* '0' to '9' -> 0 to 9 */
            return (d - PI_CONV_DEC);
        }
        else if (d >= CP_A && d <= CP_Z) {
            /* 'A' - 'Z' -> 10 to 35 */
            return (d - PI_CONV_UC);
        }
        else if (d >= CP_a && d <= CP_z) {
            /* 'a' - 'z' -> 10 to 35 */
            return (d - PI_CONV_LC);
        }
        else {
            /* Invalid character code */
            return (-1);
        }
    }
    /*
     * Test if a value matches the ECMAScript definition of trimmable whitespace.
     */
    function isSpace(c) {
        return (c === 0x20) ||
            (c >= 0x0009 && c <= 0x000d) ||
            (c === 0x00a0) ||
            (c === 0x1680) ||
            (c === 0x180e) ||
            (c >= 0x2000 && c <= 0x200a) ||
            (c === 0x2028) ||
            (c === 0x2029) ||
            (c === 0x202f) ||
            (c === 0x205f) ||
            (c === 0x3000) ||
            (c === 0xfeff);
    }
    /*
     * Determine which base a character indicates (e.g., 'x' indicates hex).
     */
    function prefixToBase(c) {
        if (c === CP_b || c === CP_B) {
            /* 0b/0B (binary) */
            return (2);
        }
        else if (c === CP_o || c === CP_O) {
            /* 0o/0O (octal) */
            return (8);
        }
        else if (c === CP_t || c === CP_T) {
            /* 0t/0T (decimal) */
            return (10);
        }
        else if (c === CP_x || c === CP_X) {
            /* 0x/0X (hexadecimal) */
            return (16);
        }
        else {
            /* Not a meaningful character */
            return (-1);
        }
    }
    function validateJsonObjectJS(schema, input) {
        var report = mod_jsonschema.validate(input, schema);
        if (report.errors.length === 0)
            return (null);
        /* Currently, we only do anything useful with the first error. */
        var error = report.errors[0];
        /* The failed property is given by a URI with an irrelevant prefix. */
        var propname = error['property'];
        var reason = error['message'].toLowerCase();
        var i, j;
        /*
         * There's at least one case where the property error message is
         * confusing at best.  We work around this here.
         */
        if ((i = reason.indexOf('the property ')) != -1 &&
            (j = reason.indexOf(' is not defined in the schema and the ' +
                'schema does not allow additional properties')) != -1) {
            i += 'the property '.length;
            if (propname === '')
                propname = reason.substr(i, j - i);
            else
                propname = propname + '.' + reason.substr(i, j - i);
            reason = 'unsupported property';
        }
        var rv = new mod_verror.VError('property "%s": %s', propname, reason);
        rv.jsv_details = error;
        return (rv);
    }
    function randElt(arr) {
        mod_assert.ok(Array.isArray(arr) && arr.length > 0, 'randElt argument must be a non-empty array');
        return (arr[Math.floor(Math.random() * arr.length)]);
    }
    function assertHrtime(a) {
        mod_assert.ok(a[0] >= 0 && a[1] >= 0, 'negative numbers not allowed in hrtimes');
        mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow');
    }
    /*
     * Compute the time elapsed between hrtime readings A and B, where A is later
     * than B.  hrtime readings come from Node's process.hrtime().  There is no
     * defined way to represent negative deltas, so it's illegal to diff B from A
     * where the time denoted by B is later than the time denoted by A.  If this
     * becomes valuable, we can define a representation and extend the
     * implementation to support it.
     */
    function hrtimeDiff(a, b) {
        assertHrtime(a);
        assertHrtime(b);
        mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]), 'negative differences not allowed');
        var rv = [a[0] - b[0], 0];
        if (a[1] >= b[1]) {
            rv[1] = a[1] - b[1];
        }
        else {
            rv[0]--;
            rv[1] = 1e9 - (b[1] - a[1]);
        }
        return (rv);
    }
    /*
     * Convert a hrtime reading from the array format returned by Node's
     * process.hrtime() into a scalar number of nanoseconds.
     */
    function hrtimeNanosec(a) {
        assertHrtime(a);
        return (Math.floor(a[0] * 1e9 + a[1]));
    }
    /*
     * Convert a hrtime reading from the array format returned by Node's
     * process.hrtime() into a scalar number of microseconds.
     */
    function hrtimeMicrosec(a) {
        assertHrtime(a);
        return (Math.floor(a[0] * 1e6 + a[1] / 1e3));
    }
    /*
     * Convert a hrtime reading from the array format returned by Node's
     * process.hrtime() into a scalar number of milliseconds.
     */
    function hrtimeMillisec(a) {
        assertHrtime(a);
        return (Math.floor(a[0] * 1e3 + a[1] / 1e6));
    }
    /*
     * Add two hrtime readings A and B, overwriting A with the result of the
     * addition.  This function is useful for accumulating several hrtime intervals
     * into a counter.  Returns A.
     */
    function hrtimeAccum(a, b) {
        assertHrtime(a);
        assertHrtime(b);
        /*
         * Accumulate the nanosecond component.
         */
        a[1] += b[1];
        if (a[1] >= 1e9) {
            /*
             * The nanosecond component overflowed, so carry to the seconds
             * field.
             */
            a[0]++;
            a[1] -= 1e9;
        }
        /*
         * Accumulate the seconds component.
         */
        a[0] += b[0];
        return (a);
    }
    /*
     * Add two hrtime readings A and B, returning the result as a new hrtime array.
     * Does not modify either input argument.
     */
    function hrtimeAdd(a, b) {
        assertHrtime(a);
        var rv = [a[0], a[1]];
        return (hrtimeAccum(rv, b));
    }
    /*
     * Check an object for unexpected properties.  Accepts the object to check, and
     * an array of allowed property names (strings).  Returns an array of key names
     * that were found on the object, but did not appear in the list of allowed
     * properties.  If no properties were found, the returned array will be of
     * zero length.
     */
    function extraProperties(obj, allowed) {
        mod_assert.ok(typeof (obj) === 'object' && obj !== null, 'obj argument must be a non-null object');
        mod_assert.ok(Array.isArray(allowed), 'allowed argument must be an array of strings');
        for (var i = 0; i < allowed.length; i++) {
            mod_assert.ok(typeof (allowed[i]) === 'string', 'allowed argument must be an array of strings');
        }
        return (Object.keys(obj).filter(function (key) {
            return (allowed.indexOf(key) === -1);
        }));
    }
    /*
     * Given three sets of properties "provided" (may be undefined), "overrides"
     * (required), and "defaults" (may be undefined), construct an object containing
     * the union of these sets with "overrides" overriding "provided", and
     * "provided" overriding "defaults".  None of the input objects are modified.
     */
    function mergeObjects(provided, overrides, defaults) {
        var rv, k;
        rv = {};
        if (defaults) {
            for (k in defaults)
                rv[k] = defaults[k];
        }
        if (provided) {
            for (k in provided)
                rv[k] = provided[k];
        }
        if (overrides) {
            for (k in overrides)
                rv[k] = overrides[k];
        }
        return (rv);
    }
}
,
/* kind-of/index */ function _(require, module, exports) {
    var isBuffer = require(147) /* is-buffer */;
    var toString = Object.prototype.toString;
    /**
     * Get the native `typeof` a value.
     *
     * @param  {*} `val`
     * @return {*} Native javascript type
     */
    module.exports = function kindOf(val) {
        // primitivies
        if (typeof val === 'undefined') {
            return 'undefined';
        }
        if (val === null) {
            return 'null';
        }
        if (val === true || val === false || val instanceof Boolean) {
            return 'boolean';
        }
        if (typeof val === 'string' || val instanceof String) {
            return 'string';
        }
        if (typeof val === 'number' || val instanceof Number) {
            return 'number';
        }
        // functions
        if (typeof val === 'function' || val instanceof Function) {
            return 'function';
        }
        // array
        if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
            return 'array';
        }
        // check for instances of RegExp and Date before calling `toString`
        if (val instanceof RegExp) {
            return 'regexp';
        }
        if (val instanceof Date) {
            return 'date';
        }
        // other objects
        var type = toString.call(val);
        if (type === '[object RegExp]') {
            return 'regexp';
        }
        if (type === '[object Date]') {
            return 'date';
        }
        if (type === '[object Arguments]') {
            return 'arguments';
        }
        if (type === '[object Error]') {
            return 'error';
        }
        // buffer
        if (isBuffer(val)) {
            return 'buffer';
        }
        // es6: Map, WeakMap, Set, WeakSet
        if (type === '[object Set]') {
            return 'set';
        }
        if (type === '[object WeakSet]') {
            return 'weakset';
        }
        if (type === '[object Map]') {
            return 'map';
        }
        if (type === '[object WeakMap]') {
            return 'weakmap';
        }
        if (type === '[object Symbol]') {
            return 'symbol';
        }
        // typed arrays
        if (type === '[object Int8Array]') {
            return 'int8array';
        }
        if (type === '[object Uint8Array]') {
            return 'uint8array';
        }
        if (type === '[object Uint8ClampedArray]') {
            return 'uint8clampedarray';
        }
        if (type === '[object Int16Array]') {
            return 'int16array';
        }
        if (type === '[object Uint16Array]') {
            return 'uint16array';
        }
        if (type === '[object Int32Array]') {
            return 'int32array';
        }
        if (type === '[object Uint32Array]') {
            return 'uint32array';
        }
        if (type === '[object Float32Array]') {
            return 'float32array';
        }
        if (type === '[object Float64Array]') {
            return 'float64array';
        }
        // must be a plain object
        return 'object';
    };
}
,
/* lazy-cache/index */ function _(require, module, exports) {
    /**
     * Cache results of the first function call to ensure only calling once.
     *
     * ```js
     * var utils = require('lazy-cache')(require);
     * // cache the call to `require('ansi-yellow')`
     * utils('ansi-yellow', 'yellow');
     * // use `ansi-yellow`
     * console.log(utils.yellow('this is yellow'));
     * ```
     *
     * @param  {Function} `fn` Function that will be called only once.
     * @return {Function} Function that can be called to get the cached function
     * @api public
     */
    function lazyCache(fn) {
        var cache = {};
        var proxy = function (mod, name) {
            name = name || camelcase(mod);
            // check both boolean and string in case `process.env` cases to string
            if (process.env.UNLAZY === 'true' || process.env.UNLAZY === true || process.env.TRAVIS) {
                cache[name] = fn(mod);
            }
            Object.defineProperty(proxy, name, {
                enumerable: true,
                configurable: true,
                get: getter
            });
            function getter() {
                if (cache.hasOwnProperty(name)) {
                    return cache[name];
                }
                return (cache[name] = fn(mod));
            }
            return getter;
        };
        return proxy;
    }
    /**
     * Used to camelcase the name to be stored on the `lazy` object.
     *
     * @param  {String} `str` String containing `_`, `.`, `-` or whitespace that will be camelcased.
     * @return {String} camelcased string.
     */
    function camelcase(str) {
        if (str.length === 1) {
            return str.toLowerCase();
        }
        str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
        return str.replace(/[\W_]+(\w|$)/g, function (_, ch) {
            return ch.toUpperCase();
        });
    }
    /**
     * Expose `lazyCache`
     */
    module.exports = lazyCache;
}
,
/* lcid/index */ function _(require, module, exports) {
    var invertKv = require(146) /* invert-kv */;
    var all = require(163) /* ./lcid.json */;
    var inverted = invertKv(all);
    exports.from = function (lcidCode) {
        if (typeof lcidCode !== 'number') {
            throw new TypeError('Expected a number');
        }
        return inverted[lcidCode];
    };
    exports.to = function (localeId) {
        if (typeof localeId !== 'string') {
            throw new TypeError('Expected a string');
        }
        return all[localeId];
    };
    exports.all = all;
}
,
/* lcid/lcid.json */ function _(require, module, exports) {
    {
        "af_ZA";
        1078,
            "am_ET";
        1118,
            "ar_AE";
        14337,
            "ar_BH";
        15361,
            "ar_DZ";
        5121,
            "ar_EG";
        3073,
            "ar_IQ";
        2049,
            "ar_JO";
        11265,
            "ar_KW";
        13313,
            "ar_LB";
        12289,
            "ar_LY";
        4097,
            "ar_MA";
        6145,
            "ar_OM";
        8193,
            "ar_QA";
        16385,
            "ar_SA";
        1025,
            "ar_SY";
        10241,
            "ar_TN";
        7169,
            "ar_YE";
        9217,
            "arn_CL";
        1146,
            "as_IN";
        1101,
            "az_AZ";
        2092,
            "ba_RU";
        1133,
            "be_BY";
        1059,
            "bg_BG";
        1026,
            "bn_IN";
        1093,
            "bo_BT";
        2129,
            "bo_CN";
        1105,
            "br_FR";
        1150,
            "bs_BA";
        8218,
            "ca_ES";
        1027,
            "co_FR";
        1155,
            "cs_CZ";
        1029,
            "cy_GB";
        1106,
            "da_DK";
        1030,
            "de_AT";
        3079,
            "de_CH";
        2055,
            "de_DE";
        1031,
            "de_LI";
        5127,
            "de_LU";
        4103,
            "div_MV";
        1125,
            "dsb_DE";
        2094,
            "el_GR";
        1032,
            "en_AU";
        3081,
            "en_BZ";
        10249,
            "en_CA";
        4105,
            "en_CB";
        9225,
            "en_GB";
        2057,
            "en_IE";
        6153,
            "en_IN";
        18441,
            "en_JA";
        8201,
            "en_MY";
        17417,
            "en_NZ";
        5129,
            "en_PH";
        13321,
            "en_TT";
        11273,
            "en_US";
        1033,
            "en_ZA";
        7177,
            "en_ZW";
        12297,
            "es_AR";
        11274,
            "es_BO";
        16394,
            "es_CL";
        13322,
            "es_CO";
        9226,
            "es_CR";
        5130,
            "es_DO";
        7178,
            "es_EC";
        12298,
            "es_ES";
        3082,
            "es_GT";
        4106,
            "es_HN";
        18442,
            "es_MX";
        2058,
            "es_NI";
        19466,
            "es_PA";
        6154,
            "es_PE";
        10250,
            "es_PR";
        20490,
            "es_PY";
        15370,
            "es_SV";
        17418,
            "es_UR";
        14346,
            "es_US";
        21514,
            "es_VE";
        8202,
            "et_EE";
        1061,
            "eu_ES";
        1069,
            "fa_IR";
        1065,
            "fi_FI";
        1035,
            "fil_PH";
        1124,
            "fo_FO";
        1080,
            "fr_BE";
        2060,
            "fr_CA";
        3084,
            "fr_CH";
        4108,
            "fr_FR";
        1036,
            "fr_LU";
        5132,
            "fr_MC";
        6156,
            "fy_NL";
        1122,
            "ga_IE";
        2108,
            "gbz_AF";
        1164,
            "gl_ES";
        1110,
            "gsw_FR";
        1156,
            "gu_IN";
        1095,
            "ha_NG";
        1128,
            "he_IL";
        1037,
            "hi_IN";
        1081,
            "hr_BA";
        4122,
            "hr_HR";
        1050,
            "hu_HU";
        1038,
            "hy_AM";
        1067,
            "id_ID";
        1057,
            "ii_CN";
        1144,
            "is_IS";
        1039,
            "it_CH";
        2064,
            "it_IT";
        1040,
            "iu_CA";
        2141,
            "ja_JP";
        1041,
            "ka_GE";
        1079,
            "kh_KH";
        1107,
            "kk_KZ";
        1087,
            "kl_GL";
        1135,
            "kn_IN";
        1099,
            "ko_KR";
        1042,
            "kok_IN";
        1111,
            "ky_KG";
        1088,
            "lb_LU";
        1134,
            "lo_LA";
        1108,
            "lt_LT";
        1063,
            "lv_LV";
        1062,
            "mi_NZ";
        1153,
            "mk_MK";
        1071,
            "ml_IN";
        1100,
            "mn_CN";
        2128,
            "mn_MN";
        1104,
            "moh_CA";
        1148,
            "mr_IN";
        1102,
            "ms_BN";
        2110,
            "ms_MY";
        1086,
            "mt_MT";
        1082,
            "my_MM";
        1109,
            "nb_NO";
        1044,
            "ne_NP";
        1121,
            "nl_BE";
        2067,
            "nl_NL";
        1043,
            "nn_NO";
        2068,
            "ns_ZA";
        1132,
            "oc_FR";
        1154,
            "or_IN";
        1096,
            "pa_IN";
        1094,
            "pl_PL";
        1045,
            "ps_AF";
        1123,
            "pt_BR";
        1046,
            "pt_PT";
        2070,
            "qut_GT";
        1158,
            "quz_BO";
        1131,
            "quz_EC";
        2155,
            "quz_PE";
        3179,
            "rm_CH";
        1047,
            "ro_RO";
        1048,
            "ru_RU";
        1049,
            "rw_RW";
        1159,
            "sa_IN";
        1103,
            "sah_RU";
        1157,
            "se_FI";
        3131,
            "se_NO";
        1083,
            "se_SE";
        2107,
            "si_LK";
        1115,
            "sk_SK";
        1051,
            "sl_SI";
        1060,
            "sma_NO";
        6203,
            "sma_SE";
        7227,
            "smj_NO";
        4155,
            "smj_SE";
        5179,
            "smn_FI";
        9275,
            "sms_FI";
        8251,
            "sq_AL";
        1052,
            "sr_BA";
        7194,
            "sr_SP";
        3098,
            "sv_FI";
        2077,
            "sv_SE";
        1053,
            "sw_KE";
        1089,
            "syr_SY";
        1114,
            "ta_IN";
        1097,
            "te_IN";
        1098,
            "tg_TJ";
        1064,
            "th_TH";
        1054,
            "tk_TM";
        1090,
            "tmz_DZ";
        2143,
            "tn_ZA";
        1074,
            "tr_TR";
        1055,
            "tt_RU";
        1092,
            "ug_CN";
        1152,
            "uk_UA";
        1058,
            "ur_IN";
        2080,
            "ur_PK";
        1056,
            "uz_UZ";
        2115,
            "vi_VN";
        1066,
            "wen_DE";
        1070,
            "wo_SN";
        1160,
            "xh_ZA";
        1076,
            "yo_NG";
        1130,
            "zh_CHS";
        4,
            "zh_CHT";
        31748,
            "zh_CN";
        2052,
            "zh_HK";
        3076,
            "zh_MO";
        5124,
            "zh_SG";
        4100,
            "zh_TW";
        1028,
            "zu_ZA";
        1077;
    }
}
,
/* less/index */ function _(require, module, exports) {
    module.exports = require(169) /* ./lib/less-node */;
}
,
/* less/lib/less-node/environment */ function _(require, module, exports) {
    module.exports = {
        encodeBase64: function encodeBase64(str) {
            return new Buffer(str).toString('base64');
        },
        mimeLookup: function (filename) {
            return require(266) /* mime */.lookup(filename);
        },
        charsetLookup: function (mime) {
            return require(266) /* mime */.charsets.lookup(mime);
        },
        getSourceMapGenerator: function getSourceMapGenerator() {
            return require(319) /* source-map */.SourceMapGenerator;
        }
    };
}
,
/* less/lib/less-node/file-manager */ function _(require, module, exports) {
    var path = require('path'), fs = require(167) /* ./fs */, PromiseConstructor = typeof Promise === 'undefined' ? require(279) /* promise */ : Promise, AbstractFileManager = require(178) /* ../less/environment/abstract-file-manager.js */;
    var FileManager = function () {
        this.contents = {};
    };
    FileManager.prototype = new AbstractFileManager();
    FileManager.prototype.supports = function (filename, currentDirectory, options, environment) {
        return true;
    };
    FileManager.prototype.supportsSync = function (filename, currentDirectory, options, environment) {
        return true;
    };
    FileManager.prototype.loadFile = function (filename, currentDirectory, options, environment, callback) {
        var fullFilename, isAbsoluteFilename = this.isPathAbsolute(filename), filenamesTried = [], self = this, prefix = filename.slice(0, 1), explicit = prefix === "." || prefix === "/", result = null, isNodeModule = false, npmPrefix = 'npm://';
        options = options || {};
        var paths = isAbsoluteFilename ? [''] : [currentDirectory];
        if (options.paths) {
            paths.push.apply(paths, options.paths);
        }
        if (!isAbsoluteFilename && paths.indexOf('.') === -1) {
            paths.push('.');
        }
        var prefixes = options.prefixes || [''];
        var fileParts = this.extractUrlParts(filename);
        if (options.syncImport) {
            getFileData(returnData, returnData);
            if (callback) {
                callback(result.error, result);
            }
            else {
                return result;
            }
        }
        else {
            // promise is guaranteed to be asyncronous
            // which helps as it allows the file handle
            // to be closed before it continues with the next file
            return new PromiseConstructor(getFileData);
        }
        function returnData(data) {
            if (!data.filename) {
                result = { error: data };
            }
            else {
                result = data;
            }
        }
        function getFileData(fulfill, reject) {
            (function tryPathIndex(i) {
                if (i < paths.length) {
                    (function tryPrefix(j) {
                        if (j < prefixes.length) {
                            isNodeModule = false;
                            fullFilename = fileParts.rawPath + prefixes[j] + fileParts.filename;
                            if (paths[i]) {
                                fullFilename = path.join(paths[i], fullFilename);
                            }
                            if (!explicit && paths[i] === '.') {
                                try {
                                    fullFilename = require.resolve(fullFilename);
                                    isNodeModule = true;
                                }
                                catch (e) {
                                    filenamesTried.push(npmPrefix + fullFilename);
                                    tryWithExtension();
                                }
                            }
                            else {
                                tryWithExtension();
                            }
                            function tryWithExtension() {
                                var extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;
                                if (extFilename !== fullFilename && !explicit && paths[i] === '.') {
                                    try {
                                        fullFilename = require.resolve(extFilename);
                                        isNodeModule = true;
                                    }
                                    catch (e) {
                                        filenamesTried.push(npmPrefix + extFilename);
                                        fullFilename = extFilename;
                                    }
                                }
                                else {
                                    fullFilename = extFilename;
                                }
                            }
                            if (self.contents[fullFilename]) {
                                fulfill({ contents: self.contents[fullFilename], filename: fullFilename });
                            }
                            else {
                                var readFileArgs = [fullFilename];
                                if (!options.rawBuffer) {
                                    readFileArgs.push('utf-8');
                                }
                                if (options.syncImport) {
                                    try {
                                        var data = fs.readFileSync.apply(this, readFileArgs);
                                        self.contents[fullFilename] = data;
                                        fulfill({ contents: data, filename: fullFilename });
                                    }
                                    catch (e) {
                                        filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
                                        return tryPrefix(j + 1);
                                    }
                                }
                                else {
                                    readFileArgs.push(function (e, data) {
                                        if (e) {
                                            filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
                                            return tryPrefix(j + 1);
                                        }
                                        self.contents[fullFilename] = data;
                                        fulfill({ contents: data, filename: fullFilename });
                                    });
                                    fs.readFile.apply(this, readFileArgs);
                                }
                            }
                        }
                        else {
                            tryPathIndex(i + 1);
                        }
                    })(0);
                }
                else {
                    reject({ type: 'File', message: "'" + filename + "' wasn't found. Tried - " + filenamesTried.join(",") });
                }
            }(0));
        }
    };
    FileManager.prototype.loadFileSync = function (filename, currentDirectory, options, environment) {
        options.syncImport = true;
        return this.loadFile(filename, currentDirectory, options, environment);
    };
    module.exports = FileManager;
}
,
/* less/lib/less-node/fs */ function _(require, module, exports) {
    var fs;
    try {
        fs = require(257) /* graceful-fs */;
    }
    catch (e) {
        fs = require("fs");
    }
    module.exports = fs;
}
,
/* less/lib/less-node/image-size */ function _(require, module, exports) {
    module.exports = function (environment) {
        var Dimension = require(221) /* ../less/tree/dimension */, Expression = require(223) /* ../less/tree/expression */, functionRegistry = require(187) /* ./../less/functions/function-registry */;
        function imageSize(functionContext, filePathNode) {
            var filePath = filePathNode.value;
            var currentFileInfo = functionContext.currentFileInfo;
            var currentDirectory = currentFileInfo.relativeUrls ?
                currentFileInfo.currentDirectory : currentFileInfo.entryPath;
            var fragmentStart = filePath.indexOf('#');
            var fragment = '';
            if (fragmentStart !== -1) {
                fragment = filePath.slice(fragmentStart);
                filePath = filePath.slice(0, fragmentStart);
            }
            var fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
            if (!fileManager) {
                throw {
                    type: "File",
                    message: "Can not set up FileManager for " + filePathNode
                };
            }
            var fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
            if (fileSync.error) {
                throw fileSync.error;
            }
            var sizeOf = require(144) /* image-size */;
            return sizeOf(fileSync.filename);
        }
        var imageFunctions = {
            "image-size": function (filePathNode) {
                var size = imageSize(this, filePathNode);
                return new Expression([
                    new Dimension(size.width, "px"),
                    new Dimension(size.height, "px")
                ]);
            },
            "image-width": function (filePathNode) {
                var size = imageSize(this, filePathNode);
                return new Dimension(size.width, "px");
            },
            "image-height": function (filePathNode) {
                var size = imageSize(this, filePathNode);
                return new Dimension(size.height, "px");
            }
        };
        functionRegistry.addMultiple(imageFunctions);
    };
}
,
/* less/lib/less-node/index */ function _(require, module, exports) {
    var environment = require(165) /* ./environment */, FileManager = require(166) /* ./file-manager */, UrlFileManager = require(172) /* ./url-file-manager */, createFromEnvironment = require(196) /* ../less */, less = createFromEnvironment(environment, [new FileManager(), new UrlFileManager()]), lesscHelper = require(170) /* ./lessc-helper */, path = require('path');
    // allow people to create less with their own environment
    less.createFromEnvironment = createFromEnvironment;
    less.lesscHelper = lesscHelper;
    less.PluginLoader = require(171) /* ./plugin-loader */;
    less.fs = require(167) /* ./fs */;
    less.FileManager = FileManager;
    less.UrlFileManager = UrlFileManager;
    // Set up options
    less.options = require(177) /* ../less/default-options */();
    // provide image-size functionality
    require(168) /* ./image-size */(less.environment);
    module.exports = less;
}
,
/* less/lib/less-node/lessc-helper */ function _(require, module, exports) {
    // lessc_helper.js
    //
    //      helper functions for lessc
    var lessc_helper = {
        // Stylize a string
        stylize: function (str, style) {
            var styles = {
                'reset': [0, 0],
                'bold': [1, 22],
                'inverse': [7, 27],
                'underline': [4, 24],
                'yellow': [33, 39],
                'green': [32, 39],
                'red': [31, 39],
                'grey': [90, 39]
            };
            return '\x1b[' + styles[style][0] + 'm' + str +
                '\x1b[' + styles[style][1] + 'm';
        },
        // Print command line options
        printUsage: function () {
            console.log("usage: lessc [option option=parameter ...] <source> [destination]");
            console.log("");
            console.log("If source is set to `-' (dash or hyphen-minus), input is read from stdin.");
            console.log("");
            console.log("options:");
            console.log("  -h, --help                   Prints help (this message) and exit.");
            console.log("  --include-path=PATHS         Sets include paths. Separated by `:'. `;' also supported on windows.");
            console.log("  -M, --depends                Outputs a makefile import dependency list to stdout.");
            console.log("  --no-color                   Disables colorized output.");
            console.log("  --ie-compat                  Enables IE8 compatibility checks.");
            console.log("  --js                         Enables inline JavaScript in less files");
            console.log("  -l, --lint                   Syntax check only (lint).");
            console.log("  -s, --silent                 Suppresses output of error messages.");
            console.log("  --strict-imports             Forces evaluation of imports.");
            console.log("  --insecure                   Allows imports from insecure https hosts.");
            console.log("  -v, --version                Prints version number and exit.");
            console.log("  --verbose                    Be verbose.");
            console.log("  --source-map[=FILENAME]      Outputs a v3 sourcemap to the filename (or output filename.map).");
            console.log("  --source-map-rootpath=X      Adds this path onto the sourcemap filename and less file paths.");
            console.log("  --source-map-basepath=X      Sets sourcemap base path, defaults to current working directory.");
            console.log("  --source-map-include-source  Puts the less files into the map instead of referencing them.");
            console.log("  --source-map-inline          Puts the map (and any less files) as a base64 data uri into the output css file.");
            console.log("  --source-map-url=URL         Sets a custom URL to map file, for sourceMappingURL comment");
            console.log("                               in generated CSS file.");
            console.log("  -rp, --rootpath=URL          Sets rootpath for url rewriting in relative imports and urls");
            console.log("                               Works with or without the relative-urls option.");
            console.log("  -ru, --relative-urls         Re-writes relative urls to the base less file.");
            console.log("  -sm=on|off                   Turns on or off strict math, where in strict mode, math.");
            console.log("  --strict-math=on|off         Requires brackets. This option may default to on and then");
            console.log("                               be removed in the future.");
            console.log("  -su=on|off                   Allows mixed units, e.g. 1px+1em or 1px*1px which have units");
            console.log("  --strict-units=on|off        that cannot be represented.");
            console.log("  --global-var='VAR=VALUE'     Defines a variable that can be referenced by the file.");
            console.log("  --modify-var='VAR=VALUE'     Modifies a variable already declared in the file.");
            console.log("  --url-args='QUERYSTRING'     Adds params into url tokens (e.g. 42, cb=42 or 'a=1&b=2')");
            console.log("  --plugin=PLUGIN=OPTIONS      Loads a plugin. You can also omit the --plugin= if the plugin begins");
            console.log("                               less-plugin. E.g. the clean css plugin is called less-plugin-clean-css");
            console.log("                               once installed (npm install less-plugin-clean-css), use either with");
            console.log("                               --plugin=less-plugin-clean-css or just --clean-css");
            console.log("                               specify options afterwards e.g. --plugin=less-plugin-clean-css=\"advanced\"");
            console.log("                               or --clean-css=\"advanced\"");
            console.log("");
            console.log("-------------------------- Deprecated ----------------");
            console.log("  --line-numbers=TYPE      Outputs filename and line numbers.");
            console.log("                           TYPE can be either 'comments', which will output");
            console.log("                           the debug info within comments, 'mediaquery'");
            console.log("                           that will output the information within a fake");
            console.log("                           media query which is compatible with the SASS");
            console.log("                           format, and 'all' which will do both.");
            console.log("  -x, --compress           Compresses output by removing some whitespaces.");
            console.log("                           We recommend you use a dedicated minifer like less-plugin-clean-css");
            console.log("");
            console.log("Report bugs to: http://github.com/less/less.js/issues");
            console.log("Home page: <http://lesscss.org/>");
        }
    };
    // Exports helper functions
    for (var h in lessc_helper) {
        if (lessc_helper.hasOwnProperty(h)) {
            exports[h] = lessc_helper[h];
        }
    }
}
,
/* less/lib/less-node/plugin-loader */ function _(require, module, exports) {
    var path = require("path"), PromiseConstructor = typeof Promise === 'undefined' ? require(279) /* promise */ : Promise, AbstractPluginLoader = require(179) /* ../less/environment/abstract-plugin-loader.js */;
    /**
     * Node Plugin Loader
     */
    var PluginLoader = function (less) {
        this.less = less;
        this.require = require;
        this.requireRelative = function (prefix) {
            prefix = path.dirname(prefix);
            return function (id) {
                var str = id.substr(0, 2);
                if (str === '..' || str === './') {
                    return require(path.join(prefix, id));
                }
                else {
                    return require(id);
                }
            };
        };
    };
    PluginLoader.prototype = new AbstractPluginLoader();
    PluginLoader.prototype.loadPlugin = function (filename, basePath, context, environment, fileManager) {
        var self = this;
        var prefix = filename.slice(0, 1);
        var explicit = prefix === "." || prefix === "/" || filename.slice(-3).toLowerCase() === ".js";
        if (!explicit) {
            context.prefixes = ['less-plugin-', ''];
        }
        return new PromiseConstructor(function (fulfill, reject) {
            fileManager.loadFile(filename, basePath, context, environment).then(function (data) {
                try {
                    self.require = self.requireRelative(data.filename);
                    fulfill(data);
                }
                catch (e) {
                    console.log(e);
                    reject(e);
                }
            }).catch(function (err) {
                reject(err);
            });
        });
    };
    module.exports = PluginLoader;
}
,
/* less/lib/less-node/url-file-manager */ function _(require, module, exports) {
    var isUrlRe = /^(?:https?:)?\/\//i, url = require('url'), request, PromiseConstructor, AbstractFileManager = require(178) /* ../less/environment/abstract-file-manager.js */, logger = require(198) /* ../less/logger */;
    var UrlFileManager = function () {
    };
    UrlFileManager.prototype = new AbstractFileManager();
    UrlFileManager.prototype.supports = function (filename, currentDirectory, options, environment) {
        return isUrlRe.test(filename) || isUrlRe.test(currentDirectory);
    };
    UrlFileManager.prototype.loadFile = function (filename, currentDirectory, options, environment) {
        if (!PromiseConstructor) {
            PromiseConstructor = typeof Promise === 'undefined' ? require(279) /* promise */ : Promise;
        }
        return new PromiseConstructor(function (fulfill, reject) {
            if (request === undefined) {
                try {
                    request = require(295) /* request */;
                }
                catch (e) {
                    request = null;
                }
            }
            if (!request) {
                reject({ type: 'File', message: "optional dependency 'request' required to import over http(s)\n" });
                return;
            }
            var urlStr = isUrlRe.test(filename) ? filename : url.resolve(currentDirectory, filename), urlObj = url.parse(urlStr);
            if (!urlObj.protocol) {
                urlObj.protocol = "http";
                urlStr = urlObj.format();
            }
            request.get({ uri: urlStr, strictSSL: !options.insecure }, function (error, res, body) {
                if (error) {
                    reject({ type: 'File', message: "resource '" + urlStr + "' gave this Error:\n  " + error + "\n" });
                    return;
                }
                if (res && res.statusCode === 404) {
                    reject({ type: 'File', message: "resource '" + urlStr + "' was not found\n" });
                    return;
                }
                if (!body) {
                    logger.warn('Warning: Empty body (HTTP ' + res.statusCode + ') returned by "' + urlStr + '"');
                }
                fulfill({ contents: body, filename: urlStr });
            });
        });
    };
    module.exports = UrlFileManager;
}
,
/* less/lib/less/contexts */ function _(require, module, exports) {
    var contexts = {};
    module.exports = contexts;
    var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
        if (!original) {
            return;
        }
        for (var i = 0; i < propertiesToCopy.length; i++) {
            if (original.hasOwnProperty(propertiesToCopy[i])) {
                destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
            }
        }
    };
    /*
     parse is used whilst parsing
     */
    var parseCopyProperties = [
        // options
        'paths',
        'relativeUrls',
        'rootpath',
        'strictImports',
        'insecure',
        'dumpLineNumbers',
        'compress',
        'syncImport',
        'chunkInput',
        'mime',
        'useFileCache',
        // context
        'processImports',
        // Used by the import manager to stop multiple import visitors being created.
        'pluginManager' // Used as the plugin manager for the session
    ];
    contexts.Parse = function (options) {
        copyFromOriginal(options, this, parseCopyProperties);
        if (typeof this.paths === "string") {
            this.paths = [this.paths];
        }
    };
    var evalCopyProperties = [
        'paths',
        'compress',
        'ieCompat',
        'strictMath',
        'strictUnits',
        'sourceMap',
        'importMultiple',
        'urlArgs',
        'javascriptEnabled',
        'pluginManager',
        'importantScope' // used to bubble up !important statements
    ];
    contexts.Eval = function (options, frames) {
        copyFromOriginal(options, this, evalCopyProperties);
        if (typeof this.paths === "string") {
            this.paths = [this.paths];
        }
        this.frames = frames || [];
        this.importantScope = this.importantScope || [];
    };
    contexts.Eval.prototype.inParenthesis = function () {
        if (!this.parensStack) {
            this.parensStack = [];
        }
        this.parensStack.push(true);
    };
    contexts.Eval.prototype.outOfParenthesis = function () {
        this.parensStack.pop();
    };
    contexts.Eval.prototype.mathOn = true;
    contexts.Eval.prototype.isMathOn = function () {
        if (!this.mathOn) {
            return false;
        }
        return this.strictMath ? (this.parensStack && this.parensStack.length) : true;
    };
    contexts.Eval.prototype.isPathRelative = function (path) {
        return !/^(?:[a-z-]+:|\/|#)/i.test(path);
    };
    contexts.Eval.prototype.normalizePath = function (path) {
        var segments = path.split("/").reverse(), segment;
        path = [];
        while (segments.length !== 0) {
            segment = segments.pop();
            switch (segment) {
                case ".":
                    break;
                case "..":
                    if ((path.length === 0) || (path[path.length - 1] === "..")) {
                        path.push(segment);
                    }
                    else {
                        path.pop();
                    }
                    break;
                default:
                    path.push(segment);
                    break;
            }
        }
        return path.join("/");
    };
}
,
/* less/lib/less/data/colors */ function _(require, module, exports) {
    module.exports = {
        'aliceblue': '#f0f8ff',
        'antiquewhite': '#faebd7',
        'aqua': '#00ffff',
        'aquamarine': '#7fffd4',
        'azure': '#f0ffff',
        'beige': '#f5f5dc',
        'bisque': '#ffe4c4',
        'black': '#000000',
        'blanchedalmond': '#ffebcd',
        'blue': '#0000ff',
        'blueviolet': '#8a2be2',
        'brown': '#a52a2a',
        'burlywood': '#deb887',
        'cadetblue': '#5f9ea0',
        'chartreuse': '#7fff00',
        'chocolate': '#d2691e',
        'coral': '#ff7f50',
        'cornflowerblue': '#6495ed',
        'cornsilk': '#fff8dc',
        'crimson': '#dc143c',
        'cyan': '#00ffff',
        'darkblue': '#00008b',
        'darkcyan': '#008b8b',
        'darkgoldenrod': '#b8860b',
        'darkgray': '#a9a9a9',
        'darkgrey': '#a9a9a9',
        'darkgreen': '#006400',
        'darkkhaki': '#bdb76b',
        'darkmagenta': '#8b008b',
        'darkolivegreen': '#556b2f',
        'darkorange': '#ff8c00',
        'darkorchid': '#9932cc',
        'darkred': '#8b0000',
        'darksalmon': '#e9967a',
        'darkseagreen': '#8fbc8f',
        'darkslateblue': '#483d8b',
        'darkslategray': '#2f4f4f',
        'darkslategrey': '#2f4f4f',
        'darkturquoise': '#00ced1',
        'darkviolet': '#9400d3',
        'deeppink': '#ff1493',
        'deepskyblue': '#00bfff',
        'dimgray': '#696969',
        'dimgrey': '#696969',
        'dodgerblue': '#1e90ff',
        'firebrick': '#b22222',
        'floralwhite': '#fffaf0',
        'forestgreen': '#228b22',
        'fuchsia': '#ff00ff',
        'gainsboro': '#dcdcdc',
        'ghostwhite': '#f8f8ff',
        'gold': '#ffd700',
        'goldenrod': '#daa520',
        'gray': '#808080',
        'grey': '#808080',
        'green': '#008000',
        'greenyellow': '#adff2f',
        'honeydew': '#f0fff0',
        'hotpink': '#ff69b4',
        'indianred': '#cd5c5c',
        'indigo': '#4b0082',
        'ivory': '#fffff0',
        'khaki': '#f0e68c',
        'lavender': '#e6e6fa',
        'lavenderblush': '#fff0f5',
        'lawngreen': '#7cfc00',
        'lemonchiffon': '#fffacd',
        'lightblue': '#add8e6',
        'lightcoral': '#f08080',
        'lightcyan': '#e0ffff',
        'lightgoldenrodyellow': '#fafad2',
        'lightgray': '#d3d3d3',
        'lightgrey': '#d3d3d3',
        'lightgreen': '#90ee90',
        'lightpink': '#ffb6c1',
        'lightsalmon': '#ffa07a',
        'lightseagreen': '#20b2aa',
        'lightskyblue': '#87cefa',
        'lightslategray': '#778899',
        'lightslategrey': '#778899',
        'lightsteelblue': '#b0c4de',
        'lightyellow': '#ffffe0',
        'lime': '#00ff00',
        'limegreen': '#32cd32',
        'linen': '#faf0e6',
        'magenta': '#ff00ff',
        'maroon': '#800000',
        'mediumaquamarine': '#66cdaa',
        'mediumblue': '#0000cd',
        'mediumorchid': '#ba55d3',
        'mediumpurple': '#9370d8',
        'mediumseagreen': '#3cb371',
        'mediumslateblue': '#7b68ee',
        'mediumspringgreen': '#00fa9a',
        'mediumturquoise': '#48d1cc',
        'mediumvioletred': '#c71585',
        'midnightblue': '#191970',
        'mintcream': '#f5fffa',
        'mistyrose': '#ffe4e1',
        'moccasin': '#ffe4b5',
        'navajowhite': '#ffdead',
        'navy': '#000080',
        'oldlace': '#fdf5e6',
        'olive': '#808000',
        'olivedrab': '#6b8e23',
        'orange': '#ffa500',
        'orangered': '#ff4500',
        'orchid': '#da70d6',
        'palegoldenrod': '#eee8aa',
        'palegreen': '#98fb98',
        'paleturquoise': '#afeeee',
        'palevioletred': '#d87093',
        'papayawhip': '#ffefd5',
        'peachpuff': '#ffdab9',
        'peru': '#cd853f',
        'pink': '#ffc0cb',
        'plum': '#dda0dd',
        'powderblue': '#b0e0e6',
        'purple': '#800080',
        'rebeccapurple': '#663399',
        'red': '#ff0000',
        'rosybrown': '#bc8f8f',
        'royalblue': '#4169e1',
        'saddlebrown': '#8b4513',
        'salmon': '#fa8072',
        'sandybrown': '#f4a460',
        'seagreen': '#2e8b57',
        'seashell': '#fff5ee',
        'sienna': '#a0522d',
        'silver': '#c0c0c0',
        'skyblue': '#87ceeb',
        'slateblue': '#6a5acd',
        'slategray': '#708090',
        'slategrey': '#708090',
        'snow': '#fffafa',
        'springgreen': '#00ff7f',
        'steelblue': '#4682b4',
        'tan': '#d2b48c',
        'teal': '#008080',
        'thistle': '#d8bfd8',
        'tomato': '#ff6347',
        'turquoise': '#40e0d0',
        'violet': '#ee82ee',
        'wheat': '#f5deb3',
        'white': '#ffffff',
        'whitesmoke': '#f5f5f5',
        'yellow': '#ffff00',
        'yellowgreen': '#9acd32'
    };
}
,
/* less/lib/less/data/index */ function _(require, module, exports) {
    module.exports = {
        colors: require(174) /* ./colors */,
        unitConversions: require(176) /* ./unit-conversions */
    };
}
,
/* less/lib/less/data/unit-conversions */ function _(require, module, exports) {
    module.exports = {
        length: {
            'm': 1,
            'cm': 0.01,
            'mm': 0.001,
            'in': 0.0254,
            'px': 0.0254 / 96,
            'pt': 0.0254 / 72,
            'pc': 0.0254 / 72 * 12
        },
        duration: {
            's': 1,
            'ms': 0.001
        },
        angle: {
            'rad': 1 / (2 * Math.PI),
            'deg': 1 / 360,
            'grad': 1 / 400,
            'turn': 1
        }
    };
}
,
/* less/lib/less/default-options */ function _(require, module, exports) {
    // Export a new default each time
    module.exports = function () {
        return {
            /* Outputs a makefile import dependency list to stdout. */
            depends: false,
            /* Compress using less built-in compression.
             * This does an okay job but does not utilise all the tricks of
             * dedicated css compression. */
            compress: false,
            /* Runs the less parser and just reports errors without any output. */
            lint: false,
            /* Sets available include paths.
             * If the file in an @import rule does not exist at that exact location,
             * less will look for it at the location(s) passed to this option.
             * You might use this for instance to specify a path to a library which
             * you want to be referenced simply and relatively in the less files. */
            paths: [],
            /* color output in the terminal */
            color: true,
            /* The strictImports controls whether the compiler will allow an @import inside of either
             * @media blocks or (a later addition) other selector blocks.
             * See: https://github.com/less/less.js/issues/656 */
            strictImports: false,
            /* Allow Imports from Insecure HTTPS Hosts */
            insecure: false,
            /* Allows you to add a path to every generated import and url in your css.
             * This does not affect less import statements that are processed, just ones
             * that are left in the output css. */
            rootpath: '',
            /* By default URLs are kept as-is, so if you import a file in a sub-directory
             * that references an image, exactly the same URL will be output in the css.
             * This option allows you to re-write URL's in imported files so that the
             * URL is always relative to the base imported file */
            relativeUrls: false,
            /* Compatibility with IE8. Used for limiting data-uri length */
            ieCompat: false,
            /* Without this option on, Less will try and process all math in your css */
            strictMath: false,
            /* Without this option, less attempts to guess at the output unit when it does maths. */
            strictUnits: false,
            /* Effectively the declaration is put at the top of your base Less file,
             * meaning it can be used but it also can be overridden if this variable
             * is defined in the file. */
            globalVars: null,
            /* As opposed to the global variable option, this puts the declaration at the
             * end of your base file, meaning it will override anything defined in your Less file. */
            modifyVars: null,
            /* This option allows you to specify a argument to go on to every URL.  */
            urlArgs: ''
        };
    };
}
,
/* less/lib/less/environment/abstract-file-manager */ function _(require, module, exports) {
    var abstractFileManager = function () {
    };
    abstractFileManager.prototype.getPath = function (filename) {
        var j = filename.lastIndexOf('?');
        if (j > 0) {
            filename = filename.slice(0, j);
        }
        j = filename.lastIndexOf('/');
        if (j < 0) {
            j = filename.lastIndexOf('\\');
        }
        if (j < 0) {
            return "";
        }
        return filename.slice(0, j + 1);
    };
    abstractFileManager.prototype.tryAppendExtension = function (path, ext) {
        return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
    };
    abstractFileManager.prototype.tryAppendLessExtension = function (path) {
        return this.tryAppendExtension(path, '.less');
    };
    abstractFileManager.prototype.supportsSync = function () {
        return false;
    };
    abstractFileManager.prototype.alwaysMakePathsAbsolute = function () {
        return false;
    };
    abstractFileManager.prototype.isPathAbsolute = function (filename) {
        return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
    };
    // TODO: pull out / replace?
    abstractFileManager.prototype.join = function (basePath, laterPath) {
        if (!basePath) {
            return laterPath;
        }
        return basePath + laterPath;
    };
    abstractFileManager.prototype.pathDiff = function pathDiff(url, baseUrl) {
        // diff between two paths to create a relative path
        var urlParts = this.extractUrlParts(url), baseUrlParts = this.extractUrlParts(baseUrl), i, max, urlDirectories, baseUrlDirectories, diff = "";
        if (urlParts.hostPart !== baseUrlParts.hostPart) {
            return "";
        }
        max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
        for (i = 0; i < max; i++) {
            if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
                break;
            }
        }
        baseUrlDirectories = baseUrlParts.directories.slice(i);
        urlDirectories = urlParts.directories.slice(i);
        for (i = 0; i < baseUrlDirectories.length - 1; i++) {
            diff += "../";
        }
        for (i = 0; i < urlDirectories.length - 1; i++) {
            diff += urlDirectories[i] + "/";
        }
        return diff;
    };
    // helper function, not part of API
    abstractFileManager.prototype.extractUrlParts = function extractUrlParts(url, baseUrl) {
        // urlParts[1] = protocol://hostname/ OR /
        // urlParts[2] = / if path relative to host base
        // urlParts[3] = directories
        // urlParts[4] = filename
        // urlParts[5] = parameters
        var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i, urlParts = url.match(urlPartsRegex), returner = {}, rawDirectories = [], directories = [], i, baseUrlParts;
        if (!urlParts) {
            throw new Error("Could not parse sheet href - '" + url + "'");
        }
        // Stylesheets in IE don't always return the full path
        if (baseUrl && (!urlParts[1] || urlParts[2])) {
            baseUrlParts = baseUrl.match(urlPartsRegex);
            if (!baseUrlParts) {
                throw new Error("Could not parse page url - '" + baseUrl + "'");
            }
            urlParts[1] = urlParts[1] || baseUrlParts[1] || "";
            if (!urlParts[2]) {
                urlParts[3] = baseUrlParts[3] + urlParts[3];
            }
        }
        if (urlParts[3]) {
            rawDirectories = urlParts[3].replace(/\\/g, "/").split("/");
            // collapse '..' and skip '.'
            for (i = 0; i < rawDirectories.length; i++) {
                if (rawDirectories[i] === "..") {
                    directories.pop();
                }
                else if (rawDirectories[i] !== ".") {
                    directories.push(rawDirectories[i]);
                }
            }
        }
        returner.hostPart = urlParts[1];
        returner.directories = directories;
        returner.rawPath = (urlParts[1] || "") + rawDirectories.join("/");
        returner.path = (urlParts[1] || "") + directories.join("/");
        returner.filename = urlParts[4];
        returner.fileUrl = returner.path + (urlParts[4] || "");
        returner.url = returner.fileUrl + (urlParts[5] || "");
        return returner;
    };
    module.exports = abstractFileManager;
}
,
/* less/lib/less/environment/abstract-plugin-loader */ function _(require, module, exports) {
    var functionRegistry = require(187) /* ../functions/function-registry */, LessError = require(197) /* ../less-error */;
    var AbstractPluginLoader = function () {
    };
    function error(msg, type) {
        throw new LessError({
            type: type || 'Syntax',
            message: msg
        });
    }
    AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
        var loader, registry, pluginObj, localModule, pluginManager, filename;
        pluginManager = context.pluginManager;
        if (fileInfo) {
            if (typeof fileInfo === "string") {
                filename = fileInfo;
            }
            else {
                filename = fileInfo.filename;
            }
        }
        var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
        if (filename) {
            pluginObj = pluginManager.get(filename);
            if (pluginObj) {
                this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
                try {
                    if (pluginObj.use) {
                        pluginObj.use.call(this.context, pluginObj);
                    }
                }
                catch (e) {
                    e.message = 'Error during @plugin call';
                    return new this.less.LessError(e, imports, filename);
                }
                return pluginObj;
            }
        }
        localModule = {
            exports: {},
            pluginManager: pluginManager,
            fileInfo: fileInfo
        };
        registry = functionRegistry.create();
        var registerPlugin = function (obj) {
            pluginObj = obj;
        };
        try {
            loader = new Function("module", "require", "registerPlugin", "functions", "tree", "less", "fileInfo", contents);
            loader(localModule, this.require, registerPlugin, registry, this.less.tree, this.less, fileInfo);
        }
        catch (e) {
            return new this.less.LessError(e, imports, filename);
        }
        if (!pluginObj) {
            pluginObj = localModule.exports;
        }
        pluginObj = this.validatePlugin(pluginObj, filename, shortname);
        if (pluginObj) {
            // Run on first load
            pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
            pluginObj.functions = registry.getLocalFunctions();
            pluginObj.imports = imports;
            pluginObj.filename = filename;
            this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
            // Run every @plugin call
            try {
                if (pluginObj.use) {
                    pluginObj.use.call(this.context, pluginObj);
                }
            }
            catch (e) {
                e.message = 'Error during @plugin call';
                return new this.less.LessError(e, imports, filename);
            }
        }
        else {
            return new this.less.LessError({ message: "Not a valid plugin" });
        }
        return pluginObj;
    };
    AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
        if (options) {
            if (!plugin.setOptions) {
                error("Options have been provided but the plugin " + name + " does not support any options.");
                return null;
            }
            try {
                plugin.setOptions(options);
            }
            catch (e) {
                error("Error setting options on plugin " + name + '\n' + e.message);
                return null;
            }
        }
    };
    AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
        if (plugin) {
            // support plugins being a function
            // so that the plugin can be more usable programmatically
            if (typeof plugin === "function") {
                plugin = new plugin();
            }
            if (plugin.minVersion) {
                if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
                    error("Plugin " + name + " requires version " + this.versionToString(plugin.minVersion));
                    return null;
                }
            }
            return plugin;
        }
        return null;
    };
    AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
        if (typeof aVersion === "string") {
            aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
            aVersion.shift();
        }
        for (var i = 0; i < aVersion.length; i++) {
            if (aVersion[i] !== bVersion[i]) {
                return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
            }
        }
        return 0;
    };
    AbstractPluginLoader.prototype.versionToString = function (version) {
        var versionString = "";
        for (var i = 0; i < version.length; i++) {
            versionString += (versionString ? "." : "") + version[i];
        }
        return versionString;
    };
    AbstractPluginLoader.prototype.printUsage = function (plugins) {
        for (var i = 0; i < plugins.length; i++) {
            var plugin = plugins[i];
            if (plugin.printUsage) {
                plugin.printUsage();
            }
        }
    };
    module.exports = AbstractPluginLoader;
}
,
/* less/lib/less/environment/environment */ function _(require, module, exports) {
    /**
     * @todo Document why this abstraction exists, and the relationship between
     *       environment, file managers, and plugin manager
     */
    var logger = require(198) /* ../logger */;
    var environment = function (externalEnvironment, fileManagers) {
        this.fileManagers = fileManagers || [];
        externalEnvironment = externalEnvironment || {};
        var optionalFunctions = ["encodeBase64", "mimeLookup", "charsetLookup", "getSourceMapGenerator"], requiredFunctions = [], functions = requiredFunctions.concat(optionalFunctions);
        for (var i = 0; i < functions.length; i++) {
            var propName = functions[i], environmentFunc = externalEnvironment[propName];
            if (environmentFunc) {
                this[propName] = environmentFunc.bind(externalEnvironment);
            }
            else if (i < requiredFunctions.length) {
                this.warn("missing required function in environment - " + propName);
            }
        }
    };
    environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
        if (!filename) {
            logger.warn("getFileManager called with no filename.. Please report this issue. continuing.");
        }
        if (currentDirectory == null) {
            logger.warn("getFileManager called with null directory.. Please report this issue. continuing.");
        }
        var fileManagers = this.fileManagers;
        if (options.pluginManager) {
            fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
        }
        for (var i = fileManagers.length - 1; i >= 0; i--) {
            var fileManager = fileManagers[i];
            if (fileManager[isSync ? "supportsSync" : "supports"](filename, currentDirectory, options, environment)) {
                return fileManager;
            }
        }
        return null;
    };
    environment.prototype.addFileManager = function (fileManager) {
        this.fileManagers.push(fileManager);
    };
    environment.prototype.clearFileManagers = function () {
        this.fileManagers = [];
    };
    module.exports = environment;
}
,
/* less/lib/less/functions/boolean */ function _(require, module, exports) {
    var functionRegistry = require(187) /* ./function-registry */, Anonymous = require(209) /* ../tree/anonymous */, Keyword = require(229) /* ../tree/keyword */;
    functionRegistry.addMultiple({
        boolean: function (condition) {
            return condition ? Keyword.True : Keyword.False;
        },
        'if': function (condition, trueValue, falseValue) {
            return condition ? trueValue
                : (falseValue || new Anonymous);
        }
    });
}
,
/* less/lib/less/functions/color-blending */ function _(require, module, exports) {
    var Color = require(214) /* ../tree/color */, functionRegistry = require(187) /* ./function-registry */;
    // Color Blending
    // ref: http://www.w3.org/TR/compositing-1
    function colorBlend(mode, color1, color2) {
        var ab = color1.alpha, cb, // backdrop
        as = color2.alpha, cs, // source
        ar, cr, r = []; // result
        ar = as + ab * (1 - as);
        for (var i = 0; i < 3; i++) {
            cb = color1.rgb[i] / 255;
            cs = color2.rgb[i] / 255;
            cr = mode(cb, cs);
            if (ar) {
                cr = (as * cs + ab * (cb -
                    as * (cb + cs - cr))) / ar;
            }
            r[i] = cr * 255;
        }
        return new Color(r, ar);
    }
    var colorBlendModeFunctions = {
        multiply: function (cb, cs) {
            return cb * cs;
        },
        screen: function (cb, cs) {
            return cb + cs - cb * cs;
        },
        overlay: function (cb, cs) {
            cb *= 2;
            return (cb <= 1) ?
                colorBlendModeFunctions.multiply(cb, cs) :
                colorBlendModeFunctions.screen(cb - 1, cs);
        },
        softlight: function (cb, cs) {
            var d = 1, e = cb;
            if (cs > 0.5) {
                e = 1;
                d = (cb > 0.25) ? Math.sqrt(cb)
                    : ((16 * cb - 12) * cb + 4) * cb;
            }
            return cb - (1 - 2 * cs) * e * (d - cb);
        },
        hardlight: function (cb, cs) {
            return colorBlendModeFunctions.overlay(cs, cb);
        },
        difference: function (cb, cs) {
            return Math.abs(cb - cs);
        },
        exclusion: function (cb, cs) {
            return cb + cs - 2 * cb * cs;
        },
        // non-w3c functions:
        average: function (cb, cs) {
            return (cb + cs) / 2;
        },
        negation: function (cb, cs) {
            return 1 - Math.abs(cb + cs - 1);
        }
    };
    for (var f in colorBlendModeFunctions) {
        if (colorBlendModeFunctions.hasOwnProperty(f)) {
            colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
        }
    }
    functionRegistry.addMultiple(colorBlend);
}
,
/* less/lib/less/functions/color */ function _(require, module, exports) {
    var Dimension = require(221) /* ../tree/dimension */, Color = require(214) /* ../tree/color */, Quoted = require(238) /* ../tree/quoted */, Anonymous = require(209) /* ../tree/anonymous */, functionRegistry = require(187) /* ./function-registry */, colorFunctions;
    function clamp(val) {
        return Math.min(1, Math.max(0, val));
    }
    function hsla(color) {
        return colorFunctions.hsla(color.h, color.s, color.l, color.a);
    }
    function number(n) {
        if (n instanceof Dimension) {
            return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
        }
        else if (typeof n === 'number') {
            return n;
        }
        else {
            throw {
                type: "Argument",
                message: "color functions take numbers as parameters"
            };
        }
    }
    function scaled(n, size) {
        if (n instanceof Dimension && n.unit.is('%')) {
            return parseFloat(n.value * size / 100);
        }
        else {
            return number(n);
        }
    }
    colorFunctions = {
        rgb: function (r, g, b) {
            return colorFunctions.rgba(r, g, b, 1.0);
        },
        rgba: function (r, g, b, a) {
            var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
            a = number(a);
            return new Color(rgb, a);
        },
        hsl: function (h, s, l) {
            return colorFunctions.hsla(h, s, l, 1.0);
        },
        hsla: function (h, s, l, a) {
            var m1, m2;
            function hue(h) {
                h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
                if (h * 6 < 1) {
                    return m1 + (m2 - m1) * h * 6;
                }
                else if (h * 2 < 1) {
                    return m2;
                }
                else if (h * 3 < 2) {
                    return m1 + (m2 - m1) * (2 / 3 - h) * 6;
                }
                else {
                    return m1;
                }
            }
            h = (number(h) % 360) / 360;
            s = clamp(number(s));
            l = clamp(number(l));
            a = clamp(number(a));
            m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
            m1 = l * 2 - m2;
            return colorFunctions.rgba(hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255, a);
        },
        hsv: function (h, s, v) {
            return colorFunctions.hsva(h, s, v, 1.0);
        },
        hsva: function (h, s, v, a) {
            h = ((number(h) % 360) / 360) * 360;
            s = number(s);
            v = number(v);
            a = number(a);
            var i, f;
            i = Math.floor((h / 60) % 6);
            f = (h / 60) - i;
            var vs = [v,
                v * (1 - s),
                v * (1 - f * s),
                v * (1 - (1 - f) * s)];
            var perm = [[0, 3, 1],
                [2, 0, 1],
                [1, 0, 3],
                [1, 2, 0],
                [3, 1, 0],
                [0, 1, 2]];
            return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
        },
        hue: function (color) {
            return new Dimension(color.toHSL().h);
        },
        saturation: function (color) {
            return new Dimension(color.toHSL().s * 100, '%');
        },
        lightness: function (color) {
            return new Dimension(color.toHSL().l * 100, '%');
        },
        hsvhue: function (color) {
            return new Dimension(color.toHSV().h);
        },
        hsvsaturation: function (color) {
            return new Dimension(color.toHSV().s * 100, '%');
        },
        hsvvalue: function (color) {
            return new Dimension(color.toHSV().v * 100, '%');
        },
        red: function (color) {
            return new Dimension(color.rgb[0]);
        },
        green: function (color) {
            return new Dimension(color.rgb[1]);
        },
        blue: function (color) {
            return new Dimension(color.rgb[2]);
        },
        alpha: function (color) {
            return new Dimension(color.toHSL().a);
        },
        luma: function (color) {
            return new Dimension(color.luma() * color.alpha * 100, '%');
        },
        luminance: function (color) {
            var luminance = (0.2126 * color.rgb[0] / 255) +
                (0.7152 * color.rgb[1] / 255) +
                (0.0722 * color.rgb[2] / 255);
            return new Dimension(luminance * color.alpha * 100, '%');
        },
        saturate: function (color, amount, method) {
            // filter: saturate(3.2);
            // should be kept as is, so check for color
            if (!color.rgb) {
                return null;
            }
            var hsl = color.toHSL();
            if (typeof method !== "undefined" && method.value === "relative") {
                hsl.s += hsl.s * amount.value / 100;
            }
            else {
                hsl.s += amount.value / 100;
            }
            hsl.s = clamp(hsl.s);
            return hsla(hsl);
        },
        desaturate: function (color, amount, method) {
            var hsl = color.toHSL();
            if (typeof method !== "undefined" && method.value === "relative") {
                hsl.s -= hsl.s * amount.value / 100;
            }
            else {
                hsl.s -= amount.value / 100;
            }
            hsl.s = clamp(hsl.s);
            return hsla(hsl);
        },
        lighten: function (color, amount, method) {
            var hsl = color.toHSL();
            if (typeof method !== "undefined" && method.value === "relative") {
                hsl.l += hsl.l * amount.value / 100;
            }
            else {
                hsl.l += amount.value / 100;
            }
            hsl.l = clamp(hsl.l);
            return hsla(hsl);
        },
        darken: function (color, amount, method) {
            var hsl = color.toHSL();
            if (typeof method !== "undefined" && method.value === "relative") {
                hsl.l -= hsl.l * amount.value / 100;
            }
            else {
                hsl.l -= amount.value / 100;
            }
            hsl.l = clamp(hsl.l);
            return hsla(hsl);
        },
        fadein: function (color, amount, method) {
            var hsl = color.toHSL();
            if (typeof method !== "undefined" && method.value === "relative") {
                hsl.a += hsl.a * amount.value / 100;
            }
            else {
                hsl.a += amount.value / 100;
            }
            hsl.a = clamp(hsl.a);
            return hsla(hsl);
        },
        fadeout: function (color, amount, method) {
            var hsl = color.toHSL();
            if (typeof method !== "undefined" && method.value === "relative") {
                hsl.a -= hsl.a * amount.value / 100;
            }
            else {
                hsl.a -= amount.value / 100;
            }
            hsl.a = clamp(hsl.a);
            return hsla(hsl);
        },
        fade: function (color, amount) {
            var hsl = color.toHSL();
            hsl.a = amount.value / 100;
            hsl.a = clamp(hsl.a);
            return hsla(hsl);
        },
        spin: function (color, amount) {
            var hsl = color.toHSL();
            var hue = (hsl.h + amount.value) % 360;
            hsl.h = hue < 0 ? 360 + hue : hue;
            return hsla(hsl);
        },
        //
        // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
        // http://sass-lang.com
        //
        mix: function (color1, color2, weight) {
            if (!color1.toHSL || !color2.toHSL) {
                console.log(color2.type);
                console.dir(color2);
            }
            if (!weight) {
                weight = new Dimension(50);
            }
            var p = weight.value / 100.0;
            var w = p * 2 - 1;
            var a = color1.toHSL().a - color2.toHSL().a;
            var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
            var w2 = 1 - w1;
            var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
                color1.rgb[1] * w1 + color2.rgb[1] * w2,
                color1.rgb[2] * w1 + color2.rgb[2] * w2];
            var alpha = color1.alpha * p + color2.alpha * (1 - p);
            return new Color(rgb, alpha);
        },
        greyscale: function (color) {
            return colorFunctions.desaturate(color, new Dimension(100));
        },
        contrast: function (color, dark, light, threshold) {
            // filter: contrast(3.2);
            // should be kept as is, so check for color
            if (!color.rgb) {
                return null;
            }
            if (typeof light === 'undefined') {
                light = colorFunctions.rgba(255, 255, 255, 1.0);
            }
            if (typeof dark === 'undefined') {
                dark = colorFunctions.rgba(0, 0, 0, 1.0);
            }
            // Figure out which is actually light and dark:
            if (dark.luma() > light.luma()) {
                var t = light;
                light = dark;
                dark = t;
            }
            if (typeof threshold === 'undefined') {
                threshold = 0.43;
            }
            else {
                threshold = number(threshold);
            }
            if (color.luma() < threshold) {
                return light;
            }
            else {
                return dark;
            }
        },
        // Changes made in 2.7.0 - Reverted in 3.0.0
        // contrast: function (color, color1, color2, threshold) {
        //     // Return which of `color1` and `color2` has the greatest contrast with `color`
        //     // according to the standard WCAG contrast ratio calculation.
        //     // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
        //     // The threshold param is no longer used, in line with SASS.
        //     // filter: contrast(3.2);
        //     // should be kept as is, so check for color
        //     if (!color.rgb) {
        //         return null;
        //     }
        //     if (typeof color1 === 'undefined') {
        //         color1 = colorFunctions.rgba(0, 0, 0, 1.0);
        //     }
        //     if (typeof color2 === 'undefined') {
        //         color2 = colorFunctions.rgba(255, 255, 255, 1.0);
        //     }
        //     var contrast1, contrast2;
        //     var luma = color.luma();
        //     var luma1 = color1.luma();
        //     var luma2 = color2.luma();
        //     // Calculate contrast ratios for each color
        //     if (luma > luma1) {
        //         contrast1 = (luma + 0.05) / (luma1 + 0.05);
        //     } else {
        //         contrast1 = (luma1 + 0.05) / (luma + 0.05);
        //     }
        //     if (luma > luma2) {
        //         contrast2 = (luma + 0.05) / (luma2 + 0.05);
        //     } else {
        //         contrast2 = (luma2 + 0.05) / (luma + 0.05);
        //     }
        //     if (contrast1 > contrast2) {
        //         return color1;
        //     } else {
        //         return color2;
        //     }
        // },
        argb: function (color) {
            return new Anonymous(color.toARGB());
        },
        color: function (c) {
            if ((c instanceof Quoted) &&
                (/^#([a-f0-9]{6}|[a-f0-9]{3})$/i.test(c.value))) {
                return new Color(c.value.slice(1));
            }
            if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
                c.value = undefined;
                return c;
            }
            throw {
                type: "Argument",
                message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF"
            };
        },
        tint: function (color, amount) {
            return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
        },
        shade: function (color, amount) {
            return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
        }
    };
    functionRegistry.addMultiple(colorFunctions);
}
,
/* less/lib/less/functions/data-uri */ function _(require, module, exports) {
    module.exports = function (environment) {
        var Quoted = require(238) /* ../tree/quoted */, URL = require(243) /* ../tree/url */, utils = require(247) /* ../utils */, functionRegistry = require(187) /* ./function-registry */, fallback = function (functionThis, node) {
            return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
        }, logger = require(198) /* ../logger */;
        functionRegistry.add("data-uri", function (mimetypeNode, filePathNode) {
            if (!filePathNode) {
                filePathNode = mimetypeNode;
                mimetypeNode = null;
            }
            var mimetype = mimetypeNode && mimetypeNode.value;
            var filePath = filePathNode.value;
            var currentFileInfo = this.currentFileInfo;
            var currentDirectory = currentFileInfo.relativeUrls ?
                currentFileInfo.currentDirectory : currentFileInfo.entryPath;
            var fragmentStart = filePath.indexOf('#');
            var fragment = '';
            if (fragmentStart !== -1) {
                fragment = filePath.slice(fragmentStart);
                filePath = filePath.slice(0, fragmentStart);
            }
            var context = utils.clone(this.context);
            context.rawBuffer = true;
            var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
            if (!fileManager) {
                return fallback(this, filePathNode);
            }
            var useBase64 = false;
            // detect the mimetype if not given
            if (!mimetypeNode) {
                mimetype = environment.mimeLookup(filePath);
                if (mimetype === "image/svg+xml") {
                    useBase64 = false;
                }
                else {
                    // use base 64 unless it's an ASCII or UTF-8 format
                    var charset = environment.charsetLookup(mimetype);
                    useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
                }
                if (useBase64) {
                    mimetype += ';base64';
                }
            }
            else {
                useBase64 = /;base64$/.test(mimetype);
            }
            var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
            if (!fileSync.contents) {
                logger.warn("Skipped data-uri embedding of " + filePath + " because file not found");
                return fallback(this, filePathNode || mimetypeNode);
            }
            var buf = fileSync.contents;
            if (useBase64 && !environment.encodeBase64) {
                return fallback(this, filePathNode);
            }
            buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
            var uri = "data:" + mimetype + ',' + buf + fragment;
            // IE8 cannot handle a data-uri larger than 32,768 characters. If this is exceeded
            // and the --ieCompat flag is enabled, return a normal url() instead.
            var DATA_URI_MAX = 32768;
            if (uri.length >= DATA_URI_MAX) {
                if (this.context.ieCompat !== false) {
                    logger.warn("Skipped data-uri embedding of " + filePath + " because its size (" + uri.length +
                        " characters) exceeds IE8-safe " + DATA_URI_MAX + " characters!");
                    return fallback(this, filePathNode || mimetypeNode);
                }
            }
            return new URL(new Quoted('"' + uri + '"', uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
        });
    };
}
,
/* less/lib/less/functions/default */ function _(require, module, exports) {
    var Keyword = require(229) /* ../tree/keyword */, functionRegistry = require(187) /* ./function-registry */;
    var defaultFunc = {
        eval: function () {
            var v = this.value_, e = this.error_;
            if (e) {
                throw e;
            }
            if (v != null) {
                return v ? Keyword.True : Keyword.False;
            }
        },
        value: function (v) {
            this.value_ = v;
        },
        error: function (e) {
            this.error_ = e;
        },
        reset: function () {
            this.value_ = this.error_ = null;
        }
    };
    functionRegistry.add("default", defaultFunc.eval.bind(defaultFunc));
    module.exports = defaultFunc;
}
,
/* less/lib/less/functions/function-caller */ function _(require, module, exports) {
    var Expression = require(223) /* ../tree/expression */;
    var functionCaller = function (name, context, index, currentFileInfo) {
        this.name = name.toLowerCase();
        this.index = index;
        this.context = context;
        this.currentFileInfo = currentFileInfo;
        this.func = context.frames[0].functionRegistry.get(this.name);
    };
    functionCaller.prototype.isValid = function () {
        return Boolean(this.func);
    };
    functionCaller.prototype.call = function (args) {
        // This code is terrible and should be replaced as per this issue...
        // https://github.com/less/less.js/issues/2477
        if (Array.isArray(args)) {
            args = args.filter(function (item) {
                if (item.type === "Comment") {
                    return false;
                }
                return true;
            })
                .map(function (item) {
                if (item.type === "Expression") {
                    var subNodes = item.value.filter(function (item) {
                        if (item.type === "Comment") {
                            return false;
                        }
                        return true;
                    });
                    if (subNodes.length === 1) {
                        return subNodes[0];
                    }
                    else {
                        return new Expression(subNodes);
                    }
                }
                return item;
            });
        }
        return this.func.apply(this, args);
    };
    module.exports = functionCaller;
}
,
/* less/lib/less/functions/function-registry */ function _(require, module, exports) {
    function makeRegistry(base) {
        return {
            _data: {},
            add: function (name, func) {
                // precautionary case conversion, as later querying of
                // the registry by function-caller uses lower case as well.
                name = name.toLowerCase();
                if (this._data.hasOwnProperty(name)) {
                    // TODO warn
                }
                this._data[name] = func;
            },
            addMultiple: function (functions) {
                Object.keys(functions).forEach(function (name) {
                    this.add(name, functions[name]);
                }.bind(this));
            },
            get: function (name) {
                return this._data[name] || (base && base.get(name));
            },
            getLocalFunctions: function () {
                return this._data;
            },
            inherit: function () {
                return makeRegistry(this);
            },
            create: function (base) {
                return makeRegistry(base);
            }
        };
    }
    module.exports = makeRegistry(null);
}
,
/* less/lib/less/functions/index */ function _(require, module, exports) {
    module.exports = function (environment) {
        var functions = {
            functionRegistry: require(187) /* ./function-registry */,
            functionCaller: require(186) /* ./function-caller */
        };
        // register functions
        require(181) /* ./boolean */;
        require(185) /* ./default */;
        require(183) /* ./color */;
        require(182) /* ./color-blending */;
        require(184) /* ./data-uri */(environment);
        require(190) /* ./math */;
        require(191) /* ./number */;
        require(192) /* ./string */;
        require(193) /* ./svg */(environment);
        require(194) /* ./types */;
        return functions;
    };
}
,
/* less/lib/less/functions/math-helper */ function _(require, module, exports) {
    var Dimension = require(221) /* ../tree/dimension */;
    var MathHelper = function () {
    };
    MathHelper._math = function (fn, unit, n) {
        if (!(n instanceof Dimension)) {
            throw { type: "Argument", message: "argument must be a number" };
        }
        if (unit == null) {
            unit = n.unit;
        }
        else {
            n = n.unify();
        }
        return new Dimension(fn(parseFloat(n.value)), unit);
    };
    module.exports = MathHelper;
}
,
/* less/lib/less/functions/math */ function _(require, module, exports) {
    var functionRegistry = require(187) /* ./function-registry */, mathHelper = require(189) /* ./math-helper.js */;
    var mathFunctions = {
        // name,  unit
        ceil: null,
        floor: null,
        sqrt: null,
        abs: null,
        tan: "",
        sin: "",
        cos: "",
        atan: "rad",
        asin: "rad",
        acos: "rad"
    };
    for (var f in mathFunctions) {
        if (mathFunctions.hasOwnProperty(f)) {
            mathFunctions[f] = mathHelper._math.bind(null, Math[f], mathFunctions[f]);
        }
    }
    mathFunctions.round = function (n, f) {
        var fraction = typeof f === "undefined" ? 0 : f.value;
        return mathHelper._math(function (num) { return num.toFixed(fraction); }, null, n);
    };
    functionRegistry.addMultiple(mathFunctions);
}
,
/* less/lib/less/functions/number */ function _(require, module, exports) {
    var Dimension = require(221) /* ../tree/dimension */, Anonymous = require(209) /* ../tree/anonymous */, functionRegistry = require(187) /* ./function-registry */, mathHelper = require(189) /* ./math-helper.js */;
    var minMax = function (isMin, args) {
        args = Array.prototype.slice.call(args);
        switch (args.length) {
            case 0: throw { type: "Argument", message: "one or more arguments required" };
        }
        var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone, order = [], // elems only contains original argument values.
        values = {}; // key is the unit.toString() for unified Dimension values,
        // value is the index into the order array.
        for (i = 0; i < args.length; i++) {
            current = args[i];
            if (!(current instanceof Dimension)) {
                if (Array.isArray(args[i].value)) {
                    Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
                }
                continue;
            }
            currentUnified = current.unit.toString() === "" && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
            unit = currentUnified.unit.toString() === "" && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
            unitStatic = unit !== "" && unitStatic === undefined || unit !== "" && order[0].unify().unit.toString() === "" ? unit : unitStatic;
            unitClone = unit !== "" && unitClone === undefined ? current.unit.toString() : unitClone;
            j = values[""] !== undefined && unit !== "" && unit === unitStatic ? values[""] : values[unit];
            if (j === undefined) {
                if (unitStatic !== undefined && unit !== unitStatic) {
                    throw { type: "Argument", message: "incompatible types" };
                }
                values[unit] = order.length;
                order.push(current);
                continue;
            }
            referenceUnified = order[j].unit.toString() === "" && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
            if (isMin && currentUnified.value < referenceUnified.value ||
                !isMin && currentUnified.value > referenceUnified.value) {
                order[j] = current;
            }
        }
        if (order.length == 1) {
            return order[0];
        }
        args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? "," : ", ");
        return new Anonymous((isMin ? "min" : "max") + "(" + args + ")");
    };
    functionRegistry.addMultiple({
        min: function () {
            return minMax(true, arguments);
        },
        max: function () {
            return minMax(false, arguments);
        },
        convert: function (val, unit) {
            return val.convertTo(unit.value);
        },
        pi: function () {
            return new Dimension(Math.PI);
        },
        mod: function (a, b) {
            return new Dimension(a.value % b.value, a.unit);
        },
        pow: function (x, y) {
            if (typeof x === "number" && typeof y === "number") {
                x = new Dimension(x);
                y = new Dimension(y);
            }
            else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
                throw { type: "Argument", message: "arguments must be numbers" };
            }
            return new Dimension(Math.pow(x.value, y.value), x.unit);
        },
        percentage: function (n) {
            var result = mathHelper._math(function (num) {
                return num * 100;
            }, '%', n);
            return result;
        }
    });
}
,
/* less/lib/less/functions/string */ function _(require, module, exports) {
    var Quoted = require(238) /* ../tree/quoted */, Anonymous = require(209) /* ../tree/anonymous */, JavaScript = require(227) /* ../tree/javascript */, functionRegistry = require(187) /* ./function-registry */;
    functionRegistry.addMultiple({
        e: function (str) {
            return new Anonymous(str instanceof JavaScript ? str.evaluated : str.value);
        },
        escape: function (str) {
            return new Anonymous(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B")
                .replace(/\(/g, "%28").replace(/\)/g, "%29"));
        },
        replace: function (string, pattern, replacement, flags) {
            var result = string.value;
            replacement = (replacement.type === "Quoted") ?
                replacement.value : replacement.toCSS();
            result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
            return new Quoted(string.quote || '', result, string.escaped);
        },
        '%': function (string /* arg, arg, ... */) {
            var args = Array.prototype.slice.call(arguments, 1), result = string.value;
            for (var i = 0; i < args.length; i++) {
                /* jshint loopfunc:true */
                result = result.replace(/%[sda]/i, function (token) {
                    var value = ((args[i].type === "Quoted") &&
                        token.match(/s/i)) ? args[i].value : args[i].toCSS();
                    return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
                });
            }
            result = result.replace(/%%/g, '%');
            return new Quoted(string.quote || '', result, string.escaped);
        }
    });
}
,
/* less/lib/less/functions/svg */ function _(require, module, exports) {
    module.exports = function (environment) {
        var Dimension = require(221) /* ../tree/dimension */, Color = require(214) /* ../tree/color */, Expression = require(223) /* ../tree/expression */, Quoted = require(238) /* ../tree/quoted */, URL = require(243) /* ../tree/url */, functionRegistry = require(187) /* ./function-registry */;
        functionRegistry.add("svg-gradient", function (direction) {
            var stops, gradientDirectionSvg, gradientType = "linear", rectangleDimension = 'x="0" y="0" width="1" height="1"', renderEnv = { compress: false }, returner, directionValue = direction.toCSS(renderEnv), i, color, position, positionValue, alpha;
            function throwArgumentDescriptor() {
                throw { type: "Argument",
                    message: "svg-gradient expects direction, start_color [start_position], [color position,]...," +
                        " end_color [end_position] or direction, color list" };
            }
            if (arguments.length == 2) {
                if (arguments[1].value.length < 2) {
                    throwArgumentDescriptor();
                }
                stops = arguments[1].value;
            }
            else if (arguments.length < 3) {
                throwArgumentDescriptor();
            }
            else {
                stops = Array.prototype.slice.call(arguments, 1);
            }
            switch (directionValue) {
                case "to bottom":
                    gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
                    break;
                case "to right":
                    gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
                    break;
                case "to bottom right":
                    gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
                    break;
                case "to top right":
                    gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
                    break;
                case "ellipse":
                case "ellipse at center":
                    gradientType = "radial";
                    gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
                    rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
                    break;
                default:
                    throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right'," +
                            " 'to bottom right', 'to top right' or 'ellipse at center'" };
            }
            returner = '<?xml version="1.0" ?>' +
                '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' +
                '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>';
            for (i = 0; i < stops.length; i += 1) {
                if (stops[i] instanceof Expression) {
                    color = stops[i].value[0];
                    position = stops[i].value[1];
                }
                else {
                    color = stops[i];
                    position = undefined;
                }
                if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
                    throwArgumentDescriptor();
                }
                positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%";
                alpha = color.alpha;
                returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>';
            }
            returner += '</' + gradientType + 'Gradient>' +
                '<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>';
            returner = encodeURIComponent(returner);
            returner = "data:image/svg+xml," + returner;
            return new URL(new Quoted("'" + returner + "'", returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
        });
    };
}
,
/* less/lib/less/functions/types */ function _(require, module, exports) {
    var Keyword = require(229) /* ../tree/keyword */, DetachedRuleset = require(220) /* ../tree/detached-ruleset */, Dimension = require(221) /* ../tree/dimension */, Color = require(214) /* ../tree/color */, Quoted = require(238) /* ../tree/quoted */, Anonymous = require(209) /* ../tree/anonymous */, URL = require(243) /* ../tree/url */, Operation = require(235) /* ../tree/operation */, functionRegistry = require(187) /* ./function-registry */;
    var isa = function (n, Type) {
        return (n instanceof Type) ? Keyword.True : Keyword.False;
    }, isunit = function (n, unit) {
        if (unit === undefined) {
            throw { type: "Argument", message: "missing the required second argument to isunit." };
        }
        unit = typeof unit.value === "string" ? unit.value : unit;
        if (typeof unit !== "string") {
            throw { type: "Argument", message: "Second argument to isunit should be a unit or a string." };
        }
        return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
    }, getItemsFromNode = function (node) {
        // handle non-array values as an array of length 1
        // return 'undefined' if index is invalid
        var items = Array.isArray(node.value) ?
            node.value : Array(node);
        return items;
    };
    functionRegistry.addMultiple({
        isruleset: function (n) {
            return isa(n, DetachedRuleset);
        },
        iscolor: function (n) {
            return isa(n, Color);
        },
        isnumber: function (n) {
            return isa(n, Dimension);
        },
        isstring: function (n) {
            return isa(n, Quoted);
        },
        iskeyword: function (n) {
            return isa(n, Keyword);
        },
        isurl: function (n) {
            return isa(n, URL);
        },
        ispixel: function (n) {
            return isunit(n, 'px');
        },
        ispercentage: function (n) {
            return isunit(n, '%');
        },
        isem: function (n) {
            return isunit(n, 'em');
        },
        isunit: isunit,
        unit: function (val, unit) {
            if (!(val instanceof Dimension)) {
                throw { type: "Argument",
                    message: "the first argument to unit must be a number" +
                        (val instanceof Operation ? ". Have you forgotten parenthesis?" : "") };
            }
            if (unit) {
                if (unit instanceof Keyword) {
                    unit = unit.value;
                }
                else {
                    unit = unit.toCSS();
                }
            }
            else {
                unit = "";
            }
            return new Dimension(val.value, unit);
        },
        "get-unit": function (n) {
            return new Anonymous(n.unit);
        },
        extract: function (values, index) {
            index = index.value - 1; // (1-based index)
            return getItemsFromNode(values)[index];
        },
        length: function (values) {
            return new Dimension(getItemsFromNode(values).length);
        }
    });
}
,
/* less/lib/less/import-manager */ function _(require, module, exports) {
    var contexts = require(173) /* ./contexts */, Parser = require(203) /* ./parser/parser */, LessError = require(197) /* ./less-error */, utils = require(247) /* ./utils */, PromiseConstructor = typeof Promise === 'undefined' ? require(279) /* promise */ : Promise;
    module.exports = function (environment) {
        // FileInfo = {
        //  'relativeUrls' - option - whether to adjust URL's to be relative
        //  'filename' - full resolved filename of current file
        //  'rootpath' - path to append to normal URLs for this node
        //  'currentDirectory' - path to the current file, absolute
        //  'rootFilename' - filename of the base file
        //  'entryPath' - absolute path to the entry file
        //  'reference' - whether the file should not be output and only output parts that are referenced
        var ImportManager = function (less, context, rootFileInfo) {
            this.less = less;
            this.rootFilename = rootFileInfo.filename;
            this.paths = context.paths || []; // Search paths, when importing
            this.contents = {}; // map - filename to contents of all the files
            this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
            this.mime = context.mime;
            this.error = null;
            this.context = context;
            // Deprecated? Unused outside of here, could be useful.
            this.queue = []; // Files which haven't been imported yet
            this.files = {}; // Holds the imported parse trees.
        };
        /**
         * Add an import to be imported
         * @param path - the raw path
         * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
         * @param currentFileInfo - the current file info (used for instance to work out relative paths)
         * @param importOptions - import options
         * @param callback - callback for when it is imported
         */
        ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
            var importManager = this, pluginLoader = this.context.pluginManager.Loader;
            this.queue.push(path);
            var fileParsedFunc = function (e, root, fullPath) {
                importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
                var importedEqualsRoot = fullPath === importManager.rootFilename;
                if (importOptions.optional && e) {
                    callback(null, { rules: [] }, false, null);
                }
                else {
                    // Inline imports aren't cached here.
                    // If we start to cache them, please make sure they won't conflict with non-inline imports of the
                    // same name as they used to do before this comment and the condition below have been added.
                    if (!importManager.files[fullPath] && !importOptions.inline) {
                        importManager.files[fullPath] = { root: root, options: importOptions };
                    }
                    if (e && !importManager.error) {
                        importManager.error = e;
                    }
                    callback(e, root, importedEqualsRoot, fullPath);
                }
            };
            var newFileInfo = {
                relativeUrls: this.context.relativeUrls,
                entryPath: currentFileInfo.entryPath,
                rootpath: currentFileInfo.rootpath,
                rootFilename: currentFileInfo.rootFilename
            };
            var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
            if (!fileManager) {
                fileParsedFunc({ message: "Could not find a file-manager for " + path });
                return;
            }
            var loadFileCallback = function (loadedFile) {
                var plugin, resolvedFilename = loadedFile.filename, contents = loadedFile.contents.replace(/^\uFEFF/, '');
                // Pass on an updated rootpath if path of imported file is relative and file
                // is in a (sub|sup) directory
                //
                // Examples:
                // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
                //   then rootpath should become 'less/module/nav/'
                // - If path of imported file is '../mixins.less' and rootpath is 'less/',
                //   then rootpath should become 'less/../'
                newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
                if (newFileInfo.relativeUrls) {
                    newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ""), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
                    if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
                        newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
                    }
                }
                newFileInfo.filename = resolvedFilename;
                var newEnv = new contexts.Parse(importManager.context);
                newEnv.processImports = false;
                importManager.contents[resolvedFilename] = contents;
                if (currentFileInfo.reference || importOptions.reference) {
                    newFileInfo.reference = true;
                }
                if (importOptions.isPlugin) {
                    plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
                    if (plugin instanceof LessError) {
                        fileParsedFunc(plugin, null, resolvedFilename);
                    }
                    else {
                        fileParsedFunc(null, plugin, resolvedFilename);
                    }
                }
                else if (importOptions.inline) {
                    fileParsedFunc(null, contents, resolvedFilename);
                }
                else {
                    // import (multiple) parse trees apparently get altered and can't be cached.
                    // TODO: investigate why this is
                    if (importManager.files[resolvedFilename]
                        && !importManager.files[resolvedFilename].options.multiple
                        && !importOptions.multiple) {
                        fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
                    }
                    else {
                        new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
                            fileParsedFunc(e, root, resolvedFilename);
                        });
                    }
                }
            };
            var promise, context = utils.clone(this.context);
            if (tryAppendExtension) {
                context.ext = importOptions.isPlugin ? ".js" : ".less";
            }
            if (importOptions.isPlugin) {
                promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
            }
            else {
                promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
                    if (err) {
                        fileParsedFunc(err);
                    }
                    else {
                        loadFileCallback(loadedFile);
                    }
                });
            }
            if (promise) {
                promise.then(loadFileCallback, fileParsedFunc);
            }
        };
        return ImportManager;
    };
}
,
/* less/lib/less/index */ function _(require, module, exports) {
    module.exports = function (environment, fileManagers) {
        var SourceMapOutput, SourceMapBuilder, ParseTree, ImportManager, Environment;
        var initial = {
            version: [3, 0, 4],
            data: require(175) /* ./data */,
            tree: require(226) /* ./tree */,
            Environment: (Environment = require(180) /* ./environment/environment */),
            AbstractFileManager: require(178) /* ./environment/abstract-file-manager */,
            AbstractPluginLoader: require(179) /* ./environment/abstract-plugin-loader */,
            environment: (environment = new Environment(environment, fileManagers)),
            visitors: require(251) /* ./visitors */,
            Parser: require(203) /* ./parser/parser */,
            functions: require(188) /* ./functions */(environment),
            contexts: require(173) /* ./contexts */,
            SourceMapOutput: (SourceMapOutput = require(207) /* ./source-map-output */(environment)),
            SourceMapBuilder: (SourceMapBuilder = require(206) /* ./source-map-builder */(SourceMapOutput, environment)),
            ParseTree: (ParseTree = require(199) /* ./parse-tree */(SourceMapBuilder)),
            ImportManager: (ImportManager = require(195) /* ./import-manager */(environment)),
            render: require(205) /* ./render */(environment, ParseTree, ImportManager),
            parse: require(200) /* ./parse */(environment, ParseTree, ImportManager),
            LessError: require(197) /* ./less-error */,
            transformTree: require(208) /* ./transform-tree */,
            utils: require(247) /* ./utils */,
            PluginManager: require(204) /* ./plugin-manager */,
            logger: require(198) /* ./logger */
        };
        // Create a public API
        var ctor = function (t) {
            return function () {
                var obj = Object.create(t.prototype);
                t.apply(obj, Array.prototype.slice.call(arguments, 0));
                return obj;
            };
        };
        var t, api = Object.create(initial);
        for (var n in initial.tree) {
            /* eslint guard-for-in: 0 */
            t = initial.tree[n];
            if (typeof t === "function") {
                api[n.toLowerCase()] = ctor(t);
            }
            else {
                api[n] = Object.create(null);
                for (var o in t) {
                    /* eslint guard-for-in: 0 */
                    api[n][o.toLowerCase()] = ctor(t[o]);
                }
            }
        }
        return api;
    };
}
,
/* less/lib/less/less-error */ function _(require, module, exports) {
    var utils = require(247) /* ./utils */;
    /**
     * This is a centralized class of any error that could be thrown internally (mostly by the parser).
     * Besides standard .message it keeps some additional data like a path to the file where the error
     * occurred along with line and column numbers.
     *
     * @class
     * @extends Error
     * @type {module.LessError}
     *
     * @prop {string} type
     * @prop {string} filename
     * @prop {number} index
     * @prop {number} line
     * @prop {number} column
     * @prop {number} callLine
     * @prop {number} callExtract
     * @prop {string[]} extract
     *
     * @param {Object} e              - An error object to wrap around or just a descriptive object
     * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
     * @param {string} [currentFilename]
     */
    var LessError = module.exports = function LessError(e, fileContentMap, currentFilename) {
        Error.call(this);
        var filename = e.filename || currentFilename;
        this.message = e.message;
        this.stack = e.stack;
        if (fileContentMap && filename) {
            var input = fileContentMap.contents[filename], loc = utils.getLocation(e.index, input), line = loc.line, col = loc.column, callLine = e.call && utils.getLocation(e.call, input).line, lines = input ? input.split('\n') : '';
            this.type = e.type || 'Syntax';
            this.filename = filename;
            this.index = e.index;
            this.line = typeof line === 'number' ? line + 1 : null;
            this.column = col;
            if (!this.line && this.stack) {
                var found = this.stack.match(/(<anonymous>|Function):(\d+):(\d+)/);
                if (found) {
                    if (found[2]) {
                        this.line = parseInt(found[2]) - 2;
                    }
                    if (found[3]) {
                        this.column = parseInt(found[3]);
                    }
                }
            }
            this.callLine = callLine + 1;
            this.callExtract = lines[callLine];
            this.extract = [
                lines[this.line - 2],
                lines[this.line - 1],
                lines[this.line]
            ];
        }
    };
    if (typeof Object.create === 'undefined') {
        var F = function () { };
        F.prototype = Error.prototype;
        LessError.prototype = new F();
    }
    else {
        LessError.prototype = Object.create(Error.prototype);
    }
    LessError.prototype.constructor = LessError;
    /**
     * An overridden version of the default Object.prototype.toString
     * which uses additional information to create a helpful message.
     *
     * @param {Object} options
     * @returns {string}
     */
    LessError.prototype.toString = function (options) {
        options = options || {};
        var message = '';
        var extract = this.extract || [];
        var error = [];
        var stylize = function (str) { return str; };
        if (options.stylize) {
            var type = typeof options.stylize;
            if (type !== 'function') {
                throw Error('options.stylize should be a function, got a ' + type + '!');
            }
            stylize = options.stylize;
        }
        if (this.line !== null) {
            if (typeof extract[0] === 'string') {
                error.push(stylize((this.line - 1) + ' ' + extract[0], 'grey'));
            }
            if (typeof extract[1] === 'string') {
                var errorTxt = this.line + ' ';
                if (extract[1]) {
                    errorTxt += extract[1].slice(0, this.column) +
                        stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
                            extract[1].slice(this.column + 1), 'red'), 'inverse');
                }
                error.push(errorTxt);
            }
            if (typeof extract[2] === 'string') {
                error.push(stylize((this.line + 1) + ' ' + extract[2], 'grey'));
            }
            error = error.join('\n') + stylize('', 'reset') + '\n';
        }
        message += stylize(this.type + 'Error: ' + this.message, 'red');
        if (this.filename) {
            message += stylize(' in ', 'red') + this.filename;
        }
        if (this.line) {
            message += stylize(' on line ' + this.line + ', column ' + (this.column + 1) + ':', 'grey');
        }
        message += '\n' + error;
        if (this.callLine) {
            message += stylize('from ', 'red') + (this.filename || '') + '/n';
            message += stylize(this.callLine, 'grey') + ' ' + this.callExtract + '/n';
        }
        return message;
    };
}
,
/* less/lib/less/logger */ function _(require, module, exports) {
    module.exports = {
        error: function (msg) {
            this._fireEvent("error", msg);
        },
        warn: function (msg) {
            this._fireEvent("warn", msg);
        },
        info: function (msg) {
            this._fireEvent("info", msg);
        },
        debug: function (msg) {
            this._fireEvent("debug", msg);
        },
        addListener: function (listener) {
            this._listeners.push(listener);
        },
        removeListener: function (listener) {
            for (var i = 0; i < this._listeners.length; i++) {
                if (this._listeners[i] === listener) {
                    this._listeners.splice(i, 1);
                    return;
                }
            }
        },
        _fireEvent: function (type, msg) {
            for (var i = 0; i < this._listeners.length; i++) {
                var logFunction = this._listeners[i][type];
                if (logFunction) {
                    logFunction(msg);
                }
            }
        },
        _listeners: []
    };
}
,
/* less/lib/less/parse-tree */ function _(require, module, exports) {
    var LessError = require(197) /* ./less-error */, transformTree = require(208) /* ./transform-tree */, logger = require(198) /* ./logger */;
    module.exports = function (SourceMapBuilder) {
        var ParseTree = function (root, imports) {
            this.root = root;
            this.imports = imports;
        };
        ParseTree.prototype.toCSS = function (options) {
            var evaldRoot, result = {}, sourceMapBuilder;
            try {
                evaldRoot = transformTree(this.root, options);
            }
            catch (e) {
                throw new LessError(e, this.imports);
            }
            try {
                var compress = Boolean(options.compress);
                if (compress) {
                    logger.warn("The compress option has been deprecated. We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.");
                }
                var toCSSOptions = {
                    compress: compress,
                    dumpLineNumbers: options.dumpLineNumbers,
                    strictUnits: Boolean(options.strictUnits),
                    numPrecision: 8
                };
                if (options.sourceMap) {
                    sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
                    result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
                }
                else {
                    result.css = evaldRoot.toCSS(toCSSOptions);
                }
            }
            catch (e) {
                throw new LessError(e, this.imports);
            }
            if (options.pluginManager) {
                var postProcessors = options.pluginManager.getPostProcessors();
                for (var i = 0; i < postProcessors.length; i++) {
                    result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
                }
            }
            if (options.sourceMap) {
                result.map = sourceMapBuilder.getExternalSourceMap();
            }
            result.imports = [];
            for (var file in this.imports.files) {
                if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
                    result.imports.push(file);
                }
            }
            return result;
        };
        return ParseTree;
    };
}
,
/* less/lib/less/parse */ function _(require, module, exports) {
    var PromiseConstructor, contexts = require(173) /* ./contexts */, Parser = require(203) /* ./parser/parser */, PluginManager = require(204) /* ./plugin-manager */, LessError = require(197) /* ./less-error */, utils = require(247) /* ./utils */;
    module.exports = function (environment, ParseTree, ImportManager) {
        var parse = function (input, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = utils.defaults(this.options, {});
            }
            else {
                options = utils.defaults(this.options, options || {});
            }
            if (!callback) {
                if (!PromiseConstructor) {
                    PromiseConstructor = typeof Promise === 'undefined' ? require(279) /* promise */ : Promise;
                }
                var self = this;
                return new PromiseConstructor(function (resolve, reject) {
                    parse.call(self, input, options, function (err, output) {
                        if (err) {
                            reject(err);
                        }
                        else {
                            resolve(output);
                        }
                    });
                });
            }
            else {
                var context, rootFileInfo, pluginManager = new PluginManager(this, !options.reUsePluginManager);
                options.pluginManager = pluginManager;
                context = new contexts.Parse(options);
                if (options.rootFileInfo) {
                    rootFileInfo = options.rootFileInfo;
                }
                else {
                    var filename = options.filename || "input";
                    var entryPath = filename.replace(/[^\/\\]*$/, "");
                    rootFileInfo = {
                        filename: filename,
                        relativeUrls: context.relativeUrls,
                        rootpath: context.rootpath || "",
                        currentDirectory: entryPath,
                        entryPath: entryPath,
                        rootFilename: filename
                    };
                    // add in a missing trailing slash
                    if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== "/") {
                        rootFileInfo.rootpath += "/";
                    }
                }
                var imports = new ImportManager(this, context, rootFileInfo);
                this.importManager = imports;
                // TODO: allow the plugins to be just a list of paths or names
                // Do an async plugin queue like lessc
                if (options.plugins) {
                    options.plugins.forEach(function (plugin) {
                        var evalResult, contents;
                        if (plugin.fileContent) {
                            contents = plugin.fileContent.replace(/^\uFEFF/, '');
                            evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
                            if (evalResult instanceof LessError) {
                                return callback(evalResult);
                            }
                        }
                        else {
                            pluginManager.addPlugin(plugin);
                        }
                    });
                }
                new Parser(context, imports, rootFileInfo)
                    .parse(input, function (e, root) {
                    if (e) {
                        return callback(e);
                    }
                    callback(null, root, imports, options);
                }, options);
            }
        };
        return parse;
    };
}
,
/* less/lib/less/parser/chunker */ function _(require, module, exports) {
    // Split the input into chunks.
    module.exports = function (input, fail) {
        var len = input.length, level = 0, parenLevel = 0, lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace, chunks = [], emitFrom = 0, chunkerCurrentIndex, currentChunkStartIndex, cc, cc2, matched;
        function emitChunk(force) {
            var len = chunkerCurrentIndex - emitFrom;
            if (((len < 512) && !force) || !len) {
                return;
            }
            chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
            emitFrom = chunkerCurrentIndex + 1;
        }
        for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
            cc = input.charCodeAt(chunkerCurrentIndex);
            if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
                // a-z or whitespace
                continue;
            }
            switch (cc) {
                case 40: // (
                    parenLevel++;
                    lastOpeningParen = chunkerCurrentIndex;
                    continue;
                case 41: // )
                    if (--parenLevel < 0) {
                        return fail("missing opening `(`", chunkerCurrentIndex);
                    }
                    continue;
                case 59: // ;
                    if (!parenLevel) {
                        emitChunk();
                    }
                    continue;
                case 123: // {
                    level++;
                    lastOpening = chunkerCurrentIndex;
                    continue;
                case 125: // }
                    if (--level < 0) {
                        return fail("missing opening `{`", chunkerCurrentIndex);
                    }
                    if (!level && !parenLevel) {
                        emitChunk();
                    }
                    continue;
                case 92: // \
                    if (chunkerCurrentIndex < len - 1) {
                        chunkerCurrentIndex++;
                        continue;
                    }
                    return fail("unescaped `\\`", chunkerCurrentIndex);
                case 34:
                case 39:
                case 96: // ", ' and `
                    matched = 0;
                    currentChunkStartIndex = chunkerCurrentIndex;
                    for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
                        cc2 = input.charCodeAt(chunkerCurrentIndex);
                        if (cc2 > 96) {
                            continue;
                        }
                        if (cc2 == cc) {
                            matched = 1;
                            break;
                        }
                        if (cc2 == 92) { // \
                            if (chunkerCurrentIndex == len - 1) {
                                return fail("unescaped `\\`", chunkerCurrentIndex);
                            }
                            chunkerCurrentIndex++;
                        }
                    }
                    if (matched) {
                        continue;
                    }
                    return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
                case 47: // /, check for comment
                    if (parenLevel || (chunkerCurrentIndex == len - 1)) {
                        continue;
                    }
                    cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
                    if (cc2 == 47) {
                        // //, find lnfeed
                        for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
                            cc2 = input.charCodeAt(chunkerCurrentIndex);
                            if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
                                break;
                            }
                        }
                    }
                    else if (cc2 == 42) {
                        // /*, find */
                        lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
                        for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
                            cc2 = input.charCodeAt(chunkerCurrentIndex);
                            if (cc2 == 125) {
                                lastMultiCommentEndBrace = chunkerCurrentIndex;
                            }
                            if (cc2 != 42) {
                                continue;
                            }
                            if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
                                break;
                            }
                        }
                        if (chunkerCurrentIndex == len - 1) {
                            return fail("missing closing `*/`", currentChunkStartIndex);
                        }
                        chunkerCurrentIndex++;
                    }
                    continue;
                case 42: // *, check for unmatched */
                    if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
                        return fail("unmatched `/*`", chunkerCurrentIndex);
                    }
                    continue;
            }
        }
        if (level !== 0) {
            if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
                return fail("missing closing `}` or `*/`", lastOpening);
            }
            else {
                return fail("missing closing `}`", lastOpening);
            }
        }
        else if (parenLevel !== 0) {
            return fail("missing closing `)`", lastOpeningParen);
        }
        emitChunk(true);
        return chunks;
    };
}
,
/* less/lib/less/parser/parser-input */ function _(require, module, exports) {
    var chunker = require(201) /* ./chunker */;
    module.exports = function () {
        var input, // Less input string
        j, // current chunk
        saveStack = [], // holds state for backtracking
        furthest, // furthest index the parser has gone to
        furthestPossibleErrorMessage, // if this is furthest we got to, this is the probably cause
        chunks, // chunkified input
        current, // current chunk
        currentPos, // index of current chunk, in `input`
        parserInput = {};
        var CHARCODE_SPACE = 32, CHARCODE_TAB = 9, CHARCODE_LF = 10, CHARCODE_CR = 13, CHARCODE_PLUS = 43, CHARCODE_COMMA = 44, CHARCODE_FORWARD_SLASH = 47, CHARCODE_9 = 57;
        function skipWhitespace(length) {
            var oldi = parserInput.i, oldj = j, curr = parserInput.i - currentPos, endIndex = parserInput.i + current.length - curr, mem = (parserInput.i += length), inp = input, c, nextChar, comment;
            for (; parserInput.i < endIndex; parserInput.i++) {
                c = inp.charCodeAt(parserInput.i);
                if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
                    nextChar = inp.charAt(parserInput.i + 1);
                    if (nextChar === '/') {
                        comment = { index: parserInput.i, isLineComment: true };
                        var nextNewLine = inp.indexOf("\n", parserInput.i + 2);
                        if (nextNewLine < 0) {
                            nextNewLine = endIndex;
                        }
                        parserInput.i = nextNewLine;
                        comment.text = inp.substr(comment.index, parserInput.i - comment.index);
                        parserInput.commentStore.push(comment);
                        continue;
                    }
                    else if (nextChar === '*') {
                        var nextStarSlash = inp.indexOf("*/", parserInput.i + 2);
                        if (nextStarSlash >= 0) {
                            comment = {
                                index: parserInput.i,
                                text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
                                isLineComment: false
                            };
                            parserInput.i += comment.text.length - 1;
                            parserInput.commentStore.push(comment);
                            continue;
                        }
                    }
                    break;
                }
                if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
                    break;
                }
            }
            current = current.slice(length + parserInput.i - mem + curr);
            currentPos = parserInput.i;
            if (!current.length) {
                if (j < chunks.length - 1) {
                    current = chunks[++j];
                    skipWhitespace(0); // skip space at the beginning of a chunk
                    return true; // things changed
                }
                parserInput.finished = true;
            }
            return oldi !== parserInput.i || oldj !== j;
        }
        parserInput.save = function () {
            currentPos = parserInput.i;
            saveStack.push({ current: current, i: parserInput.i, j: j });
        };
        parserInput.restore = function (possibleErrorMessage) {
            if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
                furthest = parserInput.i;
                furthestPossibleErrorMessage = possibleErrorMessage;
            }
            var state = saveStack.pop();
            current = state.current;
            currentPos = parserInput.i = state.i;
            j = state.j;
        };
        parserInput.forget = function () {
            saveStack.pop();
        };
        parserInput.isWhitespace = function (offset) {
            var pos = parserInput.i + (offset || 0), code = input.charCodeAt(pos);
            return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
        };
        // Specialization of $(tok)
        parserInput.$re = function (tok) {
            if (parserInput.i > currentPos) {
                current = current.slice(parserInput.i - currentPos);
                currentPos = parserInput.i;
            }
            var m = tok.exec(current);
            if (!m) {
                return null;
            }
            skipWhitespace(m[0].length);
            if (typeof m === "string") {
                return m;
            }
            return m.length === 1 ? m[0] : m;
        };
        parserInput.$char = function (tok) {
            if (input.charAt(parserInput.i) !== tok) {
                return null;
            }
            skipWhitespace(1);
            return tok;
        };
        parserInput.$str = function (tok) {
            var tokLength = tok.length;
            // https://jsperf.com/string-startswith/21
            for (var i = 0; i < tokLength; i++) {
                if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
                    return null;
                }
            }
            skipWhitespace(tokLength);
            return tok;
        };
        parserInput.$quoted = function () {
            var startChar = input.charAt(parserInput.i);
            if (startChar !== "'" && startChar !== '"') {
                return;
            }
            var length = input.length, currentPosition = parserInput.i;
            for (var i = 1; i + currentPosition < length; i++) {
                var nextChar = input.charAt(i + currentPosition);
                switch (nextChar) {
                    case "\\":
                        i++;
                        continue;
                    case "\r":
                    case "\n":
                        break;
                    case startChar:
                        var str = input.substr(currentPosition, i + 1);
                        skipWhitespace(i + 1);
                        return str;
                    default:
                }
            }
            return null;
        };
        parserInput.autoCommentAbsorb = true;
        parserInput.commentStore = [];
        parserInput.finished = false;
        // Same as $(), but don't change the state of the parser,
        // just return the match.
        parserInput.peek = function (tok) {
            if (typeof tok === 'string') {
                // https://jsperf.com/string-startswith/21
                for (var i = 0; i < tok.length; i++) {
                    if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
                        return false;
                    }
                }
                return true;
            }
            else {
                return tok.test(current);
            }
        };
        // Specialization of peek()
        // TODO remove or change some currentChar calls to peekChar
        parserInput.peekChar = function (tok) {
            return input.charAt(parserInput.i) === tok;
        };
        parserInput.currentChar = function () {
            return input.charAt(parserInput.i);
        };
        parserInput.getInput = function () {
            return input;
        };
        parserInput.peekNotNumeric = function () {
            var c = input.charCodeAt(parserInput.i);
            // Is the first char of the dimension 0-9, '.', '+' or '-'
            return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
        };
        parserInput.start = function (str, chunkInput, failFunction) {
            input = str;
            parserInput.i = j = currentPos = furthest = 0;
            // chunking apparently makes things quicker (but my tests indicate
            // it might actually make things slower in node at least)
            // and it is a non-perfect parse - it can't recognise
            // unquoted urls, meaning it can't distinguish comments
            // meaning comments with quotes or {}() in them get 'counted'
            // and then lead to parse errors.
            // In addition if the chunking chunks in the wrong place we might
            // not be able to parse a parser statement in one go
            // this is officially deprecated but can be switched on via an option
            // in the case it causes too much performance issues.
            if (chunkInput) {
                chunks = chunker(str, failFunction);
            }
            else {
                chunks = [str];
            }
            current = chunks[0];
            skipWhitespace(0);
        };
        parserInput.end = function () {
            var message, isFinished = parserInput.i >= input.length;
            if (parserInput.i < furthest) {
                message = furthestPossibleErrorMessage;
                parserInput.i = furthest;
            }
            return {
                isFinished: isFinished,
                furthest: parserInput.i,
                furthestPossibleErrorMessage: message,
                furthestReachedEnd: parserInput.i >= input.length - 1,
                furthestChar: input[parserInput.i]
            };
        };
        return parserInput;
    };
}
,
/* less/lib/less/parser/parser */ function _(require, module, exports) {
    var LessError = require(197) /* ../less-error */, tree = require(226) /* ../tree */, visitors = require(251) /* ../visitors */, getParserInput = require(202) /* ./parser-input */, utils = require(247) /* ../utils */, functionRegistry = require(187) /* ../functions/function-registry */;
    //
    // less.js - parser
    //
    //    A relatively straight-forward predictive parser.
    //    There is no tokenization/lexing stage, the input is parsed
    //    in one sweep.
    //
    //    To make the parser fast enough to run in the browser, several
    //    optimization had to be made:
    //
    //    - Matching and slicing on a huge input is often cause of slowdowns.
    //      The solution is to chunkify the input into smaller strings.
    //      The chunks are stored in the `chunks` var,
    //      `j` holds the current chunk index, and `currentPos` holds
    //      the index of the current chunk in relation to `input`.
    //      This gives us an almost 4x speed-up.
    //
    //    - In many cases, we don't need to match individual tokens;
    //      for example, if a value doesn't hold any variables, operations
    //      or dynamic references, the parser can effectively 'skip' it,
    //      treating it as a literal.
    //      An example would be '1px solid #000' - which evaluates to itself,
    //      we don't need to know what the individual components are.
    //      The drawback, of course is that you don't get the benefits of
    //      syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
    //      and a smaller speed-up in the code-gen.
    //
    //
    //    Token matching is done with the `$` function, which either takes
    //    a terminal string or regexp, or a non-terminal function to call.
    //    It also takes care of moving all the indices forwards.
    //
    var Parser = function Parser(context, imports, fileInfo) {
        var parsers, parserInput = getParserInput();
        function error(msg, type) {
            throw new LessError({
                index: parserInput.i,
                filename: fileInfo.filename,
                type: type || 'Syntax',
                message: msg
            }, imports);
        }
        function expect(arg, msg, index) {
            // some older browsers return typeof 'function' for RegExp
            var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
            if (result) {
                return result;
            }
            error(msg || (typeof arg === 'string' ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'"
                : "unexpected token"));
        }
        // Specialization of expect()
        function expectChar(arg, msg) {
            if (parserInput.$char(arg)) {
                return arg;
            }
            error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'");
        }
        function getDebugInfo(index) {
            var filename = fileInfo.filename;
            return {
                lineNumber: utils.getLocation(index, parserInput.getInput()).line + 1,
                fileName: filename
            };
        }
        /**
         *  Used after initial parsing to create nodes on the fly
         *
         *  @param {String} str          - string to parse
         *  @param {Array}  parseList    - array of parsers to run input through e.g. ["value", "important"]
         *  @param {Number} currentIndex - start number to begin indexing
         *  @param {Object} fileInfo     - fileInfo to attach to created nodes
         */
        function parseNode(str, parseList, currentIndex, fileInfo, callback) {
            var result, returnNodes = [];
            var parser = parserInput;
            try {
                parser.start(str, false, function fail(msg, index) {
                    callback({
                        message: msg,
                        index: index + currentIndex
                    });
                });
                for (var x = 0, p, i; (p = parseList[x]); x++) {
                    i = parser.i;
                    result = parsers[p]();
                    if (result) {
                        result._index = i + currentIndex;
                        result._fileInfo = fileInfo;
                        returnNodes.push(result);
                    }
                    else {
                        returnNodes.push(null);
                    }
                }
                var endInfo = parser.end();
                if (endInfo.isFinished) {
                    callback(null, returnNodes);
                }
                else {
                    callback(true, null);
                }
            }
            catch (e) {
                throw new LessError({
                    index: e.index + currentIndex,
                    message: e.message
                }, imports, fileInfo.filename);
            }
        }
        //
        // The Parser
        //
        return {
            parserInput: parserInput,
            imports: imports,
            fileInfo: fileInfo,
            parseNode: parseNode,
            //
            // Parse an input string into an abstract syntax tree,
            // @param str A string containing 'less' markup
            // @param callback call `callback` when done.
            // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
            //
            parse: function (str, callback, additionalData) {
                var root, error = null, globalVars, modifyVars, ignored, preText = "";
                globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + '\n' : '';
                modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + Parser.serializeVars(additionalData.modifyVars) : '';
                if (context.pluginManager) {
                    var preProcessors = context.pluginManager.getPreProcessors();
                    for (var i = 0; i < preProcessors.length; i++) {
                        str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo });
                    }
                }
                if (globalVars || (additionalData && additionalData.banner)) {
                    preText = ((additionalData && additionalData.banner) ? additionalData.banner : "") + globalVars;
                    ignored = imports.contentsIgnoredChars;
                    ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
                    ignored[fileInfo.filename] += preText.length;
                }
                str = str.replace(/\r\n?/g, '\n');
                // Remove potential UTF Byte Order Mark
                str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
                imports.contents[fileInfo.filename] = str;
                // Start with the primary rule.
                // The whole syntax tree is held under a Ruleset node,
                // with the `root` property set to true, so no `{}` are
                // output. The callback is called when the input is parsed.
                try {
                    parserInput.start(str, context.chunkInput, function fail(msg, index) {
                        throw new LessError({
                            index: index,
                            type: 'Parse',
                            message: msg,
                            filename: fileInfo.filename
                        }, imports);
                    });
                    tree.Node.prototype.parse = this;
                    root = new tree.Ruleset(null, this.parsers.primary());
                    tree.Node.prototype.rootNode = root;
                    root.root = true;
                    root.firstRoot = true;
                    root.functionRegistry = functionRegistry.inherit();
                }
                catch (e) {
                    return callback(new LessError(e, imports, fileInfo.filename));
                }
                // If `i` is smaller than the `input.length - 1`,
                // it means the parser wasn't able to parse the whole
                // string, so we've got a parsing error.
                //
                // We try to extract a \n delimited string,
                // showing the line where the parse error occurred.
                // We split it up into two parts (the part which parsed,
                // and the part which didn't), so we can color them differently.
                var endInfo = parserInput.end();
                if (!endInfo.isFinished) {
                    var message = endInfo.furthestPossibleErrorMessage;
                    if (!message) {
                        message = "Unrecognised input";
                        if (endInfo.furthestChar === '}') {
                            message += ". Possibly missing opening '{'";
                        }
                        else if (endInfo.furthestChar === ')') {
                            message += ". Possibly missing opening '('";
                        }
                        else if (endInfo.furthestReachedEnd) {
                            message += ". Possibly missing something";
                        }
                    }
                    error = new LessError({
                        type: "Parse",
                        message: message,
                        index: endInfo.furthest,
                        filename: fileInfo.filename
                    }, imports);
                }
                var finish = function (e) {
                    e = error || e || imports.error;
                    if (e) {
                        if (!(e instanceof LessError)) {
                            e = new LessError(e, imports, fileInfo.filename);
                        }
                        return callback(e);
                    }
                    else {
                        return callback(null, root);
                    }
                };
                if (context.processImports !== false) {
                    new visitors.ImportVisitor(imports, finish)
                        .run(root);
                }
                else {
                    return finish();
                }
            },
            //
            // Here in, the parsing rules/functions
            //
            // The basic structure of the syntax tree generated is as follows:
            //
            //   Ruleset ->  Declaration -> Value -> Expression -> Entity
            //
            // Here's some Less code:
            //
            //    .class {
            //      color: #fff;
            //      border: 1px solid #000;
            //      width: @w + 4px;
            //      > .child {...}
            //    }
            //
            // And here's what the parse tree might look like:
            //
            //     Ruleset (Selector '.class', [
            //         Declaration ("color",  Value ([Expression [Color #fff]]))
            //         Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
            //         Declaration ("width",  Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
            //         Ruleset (Selector [Element '>', '.child'], [...])
            //     ])
            //
            //  In general, most rules will try to parse a token with the `$re()` function, and if the return
            //  value is truly, will return a new node, of the relevant type. Sometimes, we need to check
            //  first, before parsing, that's when we use `peek()`.
            //
            parsers: parsers = {
                //
                // The `primary` rule is the *entry* and *exit* point of the parser.
                // The rules here can appear at any level of the parse tree.
                //
                // The recursive nature of the grammar is an interplay between the `block`
                // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
                // as represented by this simplified grammar:
                //
                //     primary  →  (ruleset | declaration)+
                //     ruleset  →  selector+ block
                //     block    →  '{' primary '}'
                //
                // Only at one point is the primary rule not called from the
                // block rule: at the root level.
                //
                primary: function () {
                    var mixin = this.mixin, root = [], node;
                    while (true) {
                        while (true) {
                            node = this.comment();
                            if (!node) {
                                break;
                            }
                            root.push(node);
                        }
                        // always process comments before deciding if finished
                        if (parserInput.finished) {
                            break;
                        }
                        if (parserInput.peek('}')) {
                            break;
                        }
                        node = this.extendRule();
                        if (node) {
                            root = root.concat(node);
                            continue;
                        }
                        node = mixin.definition() || this.declaration() || this.ruleset() ||
                            mixin.call() || this.variableCall() || this.entities.call() || this.atrule();
                        if (node) {
                            root.push(node);
                        }
                        else {
                            var foundSemiColon = false;
                            while (parserInput.$char(";")) {
                                foundSemiColon = true;
                            }
                            if (!foundSemiColon) {
                                break;
                            }
                        }
                    }
                    return root;
                },
                // comments are collected by the main parsing mechanism and then assigned to nodes
                // where the current structure allows it
                comment: function () {
                    if (parserInput.commentStore.length) {
                        var comment = parserInput.commentStore.shift();
                        return new (tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo);
                    }
                },
                //
                // Entities are tokens which can be found inside an Expression
                //
                entities: {
                    //
                    // A string, which supports escaping " and '
                    //
                    //     "milky way" 'he\'s the one!'
                    //
                    quoted: function () {
                        var str, index = parserInput.i, isEscaped = false;
                        parserInput.save();
                        if (parserInput.$char("~")) {
                            isEscaped = true;
                        }
                        str = parserInput.$quoted();
                        if (!str) {
                            parserInput.restore();
                            return;
                        }
                        parserInput.forget();
                        return new (tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
                    },
                    //
                    // A catch-all word, such as:
                    //
                    //     black border-collapse
                    //
                    keyword: function () {
                        var k = parserInput.$char("%") || parserInput.$re(/^\[?[_A-Za-z-][_A-Za-z0-9-]*\]?/);
                        if (k) {
                            return tree.Color.fromKeyword(k) || new (tree.Keyword)(k);
                        }
                    },
                    //
                    // A function call
                    //
                    //     rgb(255, 0, 255)
                    //
                    // The arguments are parsed with the `entities.arguments` parser.
                    //
                    call: function () {
                        var name, args, func, index = parserInput.i;
                        // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
                        if (parserInput.peek(/^url\(/i)) {
                            return;
                        }
                        parserInput.save();
                        name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
                        if (!name) {
                            parserInput.forget();
                            return;
                        }
                        name = name[1];
                        func = this.customFuncCall(name);
                        if (func) {
                            args = func.parse();
                            if (args && func.stop) {
                                parserInput.forget();
                                return args;
                            }
                        }
                        args = this.arguments(args);
                        if (!parserInput.$char(')')) {
                            parserInput.restore("Could not parse call arguments or missing ')'");
                            return;
                        }
                        parserInput.forget();
                        return new (tree.Call)(name, args, index, fileInfo);
                    },
                    //
                    // Parsing rules for functions with non-standard args, e.g.:
                    //
                    //     boolean(not(2 > 1))
                    //
                    //     This is a quick prototype, to be modified/improved when
                    //     more custom-parsed funcs come (e.g. `selector(...)`)
                    //
                    customFuncCall: function (name) {
                        /* Ideally the table is to be moved out of here for faster perf.,
                           but it's quite tricky since it relies on all these `parsers`
                           and `expect` available only here */
                        return {
                            alpha: f(parsers.ieAlpha, true),
                            boolean: f(condition),
                            'if': f(condition)
                        }[name.toLowerCase()];
                        function f(parse, stop) {
                            return {
                                parse: parse,
                                stop: stop // when true - stop after parse() and return its result, 
                                // otherwise continue for plain args
                            };
                        }
                        function condition() {
                            return [expect(parsers.condition, 'expected condition')];
                        }
                    },
                    arguments: function (prevArgs) {
                        var argsComma = prevArgs || [], argsSemiColon = [], isSemiColonSeparated, value;
                        parserInput.save();
                        while (true) {
                            if (prevArgs) {
                                prevArgs = false;
                            }
                            else {
                                value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
                                if (!value) {
                                    break;
                                }
                                if (value.value && value.value.length == 1) {
                                    value = value.value[0];
                                }
                                argsComma.push(value);
                            }
                            if (parserInput.$char(',')) {
                                continue;
                            }
                            if (parserInput.$char(';') || isSemiColonSeparated) {
                                isSemiColonSeparated = true;
                                value = (argsComma.length < 1) ? argsComma[0]
                                    : new tree.Value(argsComma);
                                argsSemiColon.push(value);
                                argsComma = [];
                            }
                        }
                        parserInput.forget();
                        return isSemiColonSeparated ? argsSemiColon : argsComma;
                    },
                    literal: function () {
                        return this.dimension() ||
                            this.color() ||
                            this.quoted() ||
                            this.unicodeDescriptor();
                    },
                    // Assignments are argument entities for calls.
                    // They are present in ie filter properties as shown below.
                    //
                    //     filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
                    //
                    assignment: function () {
                        var key, value;
                        parserInput.save();
                        key = parserInput.$re(/^\w+(?=\s?=)/i);
                        if (!key) {
                            parserInput.restore();
                            return;
                        }
                        if (!parserInput.$char('=')) {
                            parserInput.restore();
                            return;
                        }
                        value = parsers.entity();
                        if (value) {
                            parserInput.forget();
                            return new (tree.Assignment)(key, value);
                        }
                        else {
                            parserInput.restore();
                        }
                    },
                    //
                    // Parse url() tokens
                    //
                    // We use a specific rule for urls, because they don't really behave like
                    // standard function calls. The difference is that the argument doesn't have
                    // to be enclosed within a string, so it can't be parsed as an Expression.
                    //
                    url: function () {
                        var value, index = parserInput.i;
                        parserInput.autoCommentAbsorb = false;
                        if (!parserInput.$str("url(")) {
                            parserInput.autoCommentAbsorb = true;
                            return;
                        }
                        value = this.quoted() || this.variable() || this.property() ||
                            parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || "";
                        parserInput.autoCommentAbsorb = true;
                        expectChar(')');
                        return new (tree.URL)((value.value != null ||
                            value instanceof tree.Variable ||
                            value instanceof tree.Property) ?
                            value : new (tree.Anonymous)(value, index), index, fileInfo);
                    },
                    //
                    // A Variable entity, such as `@fink`, in
                    //
                    //     width: @fink + 2px
                    //
                    // We use a different parser for variable definitions,
                    // see `parsers.variable`.
                    //
                    variable: function () {
                        var name, index = parserInput.i;
                        if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
                            return new (tree.Variable)(name, index, fileInfo);
                        }
                    },
                    // A variable entity using the protective {} e.g. @{var}
                    variableCurly: function () {
                        var curly, index = parserInput.i;
                        if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
                            return new (tree.Variable)("@" + curly[1], index, fileInfo);
                        }
                    },
                    //
                    // A Property accessor, such as `$color`, in
                    //
                    //     background-color: $color
                    //
                    property: function () {
                        var name, index = parserInput.i;
                        if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
                            return new (tree.Property)(name, index, fileInfo);
                        }
                    },
                    // A property entity useing the protective {} e.g. ${prop}
                    propertyCurly: function () {
                        var curly, index = parserInput.i;
                        if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
                            return new (tree.Property)("$" + curly[1], index, fileInfo);
                        }
                    },
                    //
                    // A Hexadecimal color
                    //
                    //     #4F3C2F
                    //
                    // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
                    //
                    color: function () {
                        var rgb;
                        if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) {
                            // strip colons, brackets, whitespaces and other characters that should not
                            // definitely be part of color string
                            var colorCandidateString = rgb.input.match(/^#([\w]+).*/);
                            colorCandidateString = colorCandidateString[1];
                            if (!colorCandidateString.match(/^[A-Fa-f0-9]+$/)) { // verify if candidate consists only of allowed HEX characters
                                error("Invalid HEX color code");
                            }
                            return new (tree.Color)(rgb[1], undefined, '#' + colorCandidateString);
                        }
                    },
                    colorKeyword: function () {
                        parserInput.save();
                        var autoCommentAbsorb = parserInput.autoCommentAbsorb;
                        parserInput.autoCommentAbsorb = false;
                        var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
                        parserInput.autoCommentAbsorb = autoCommentAbsorb;
                        if (!k) {
                            parserInput.forget();
                            return;
                        }
                        parserInput.restore();
                        var color = tree.Color.fromKeyword(k);
                        if (color) {
                            parserInput.$str(k);
                            return color;
                        }
                    },
                    //
                    // A Dimension, that is, a number and a unit
                    //
                    //     0.5em 95%
                    //
                    dimension: function () {
                        if (parserInput.peekNotNumeric()) {
                            return;
                        }
                        var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
                        if (value) {
                            return new (tree.Dimension)(value[1], value[2]);
                        }
                    },
                    //
                    // A unicode descriptor, as is used in unicode-range
                    //
                    // U+0??  or U+00A1-00A9
                    //
                    unicodeDescriptor: function () {
                        var ud;
                        ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
                        if (ud) {
                            return new (tree.UnicodeDescriptor)(ud[0]);
                        }
                    },
                    //
                    // JavaScript code to be evaluated
                    //
                    //     `window.location.href`
                    //
                    javascript: function () {
                        var js, index = parserInput.i;
                        parserInput.save();
                        var escape = parserInput.$char("~");
                        var jsQuote = parserInput.$char("`");
                        if (!jsQuote) {
                            parserInput.restore();
                            return;
                        }
                        js = parserInput.$re(/^[^`]*`/);
                        if (js) {
                            parserInput.forget();
                            return new (tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
                        }
                        parserInput.restore("invalid javascript definition");
                    }
                },
                //
                // The variable part of a variable definition. Used in the `rule` parser
                //
                //     @fink:
                //
                variable: function () {
                    var name;
                    if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
                        return name[1];
                    }
                },
                //
                // Call a variable value
                //
                //     @fink()
                //
                variableCall: function () {
                    var name;
                    if (parserInput.currentChar() === '@'
                        && (name = parserInput.$re(/^(@[\w-]+)\(\s*\)/))
                        && parsers.end()) {
                        return new tree.VariableCall(name[1]);
                    }
                },
                //
                // extend syntax - used to extend selectors
                //
                extend: function (isRule) {
                    var elements, e, index = parserInput.i, option, extendList, extend;
                    if (!parserInput.$str(isRule ? "&:extend(" : ":extend(")) {
                        return;
                    }
                    do {
                        option = null;
                        elements = null;
                        while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
                            e = this.element();
                            if (!e) {
                                break;
                            }
                            if (elements) {
                                elements.push(e);
                            }
                            else {
                                elements = [e];
                            }
                        }
                        option = option && option[1];
                        if (!elements) {
                            error("Missing target selector for :extend().");
                        }
                        extend = new (tree.Extend)(new (tree.Selector)(elements), option, index, fileInfo);
                        if (extendList) {
                            extendList.push(extend);
                        }
                        else {
                            extendList = [extend];
                        }
                    } while (parserInput.$char(","));
                    expect(/^\)/);
                    if (isRule) {
                        expect(/^;/);
                    }
                    return extendList;
                },
                //
                // extendRule - used in a rule to extend all the parent selectors
                //
                extendRule: function () {
                    return this.extend(true);
                },
                //
                // Mixins
                //
                mixin: {
                    //
                    // A Mixin call, with an optional argument list
                    //
                    //     #mixins > .square(#fff);
                    //     .rounded(4px, black);
                    //     .button;
                    //
                    // The `while` loop is there because mixins can be
                    // namespaced, but we only support the child and descendant
                    // selector for now.
                    //
                    call: function () {
                        var s = parserInput.currentChar(), important = false, index = parserInput.i, elemIndex, elements, elem, e, c, args;
                        if (s !== '.' && s !== '#') {
                            return;
                        }
                        parserInput.save(); // stop us absorbing part of an invalid selector
                        while (true) {
                            elemIndex = parserInput.i;
                            e = parserInput.$re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/);
                            if (!e) {
                                break;
                            }
                            elem = new (tree.Element)(c, e, elemIndex, fileInfo);
                            if (elements) {
                                elements.push(elem);
                            }
                            else {
                                elements = [elem];
                            }
                            c = parserInput.$char('>');
                        }
                        if (elements) {
                            if (parserInput.$char('(')) {
                                args = this.args(true).args;
                                expectChar(')');
                            }
                            if (parsers.important()) {
                                important = true;
                            }
                            if (parsers.end()) {
                                parserInput.forget();
                                return new (tree.mixin.Call)(elements, args, index, fileInfo, important);
                            }
                        }
                        parserInput.restore();
                    },
                    args: function (isCall) {
                        var entities = parsers.entities, returner = { args: null, variadic: false }, expressions = [], argsSemiColon = [], argsComma = [], isSemiColonSeparated, expressionContainsNamed, name, nameLoop, value, arg, expand;
                        parserInput.save();
                        while (true) {
                            if (isCall) {
                                arg = parsers.detachedRuleset() || parsers.expression();
                            }
                            else {
                                parserInput.commentStore.length = 0;
                                if (parserInput.$str("...")) {
                                    returner.variadic = true;
                                    if (parserInput.$char(";") && !isSemiColonSeparated) {
                                        isSemiColonSeparated = true;
                                    }
                                    (isSemiColonSeparated ? argsSemiColon : argsComma)
                                        .push({ variadic: true });
                                    break;
                                }
                                arg = entities.variable() || entities.property() || entities.literal() || entities.keyword();
                            }
                            if (!arg) {
                                break;
                            }
                            nameLoop = null;
                            if (arg.throwAwayComments) {
                                arg.throwAwayComments();
                            }
                            value = arg;
                            var val = null;
                            if (isCall) {
                                // Variable
                                if (arg.value && arg.value.length == 1) {
                                    val = arg.value[0];
                                }
                            }
                            else {
                                val = arg;
                            }
                            if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
                                if (parserInput.$char(':')) {
                                    if (expressions.length > 0) {
                                        if (isSemiColonSeparated) {
                                            error("Cannot mix ; and , as delimiter types");
                                        }
                                        expressionContainsNamed = true;
                                    }
                                    value = parsers.detachedRuleset() || parsers.expression();
                                    if (!value) {
                                        if (isCall) {
                                            error("could not understand value for named argument");
                                        }
                                        else {
                                            parserInput.restore();
                                            returner.args = [];
                                            return returner;
                                        }
                                    }
                                    nameLoop = (name = val.name);
                                }
                                else if (parserInput.$str("...")) {
                                    if (!isCall) {
                                        returner.variadic = true;
                                        if (parserInput.$char(";") && !isSemiColonSeparated) {
                                            isSemiColonSeparated = true;
                                        }
                                        (isSemiColonSeparated ? argsSemiColon : argsComma)
                                            .push({ name: arg.name, variadic: true });
                                        break;
                                    }
                                    else {
                                        expand = true;
                                    }
                                }
                                else if (!isCall) {
                                    name = nameLoop = val.name;
                                    value = null;
                                }
                            }
                            if (value) {
                                expressions.push(value);
                            }
                            argsComma.push({ name: nameLoop, value: value, expand: expand });
                            if (parserInput.$char(',')) {
                                continue;
                            }
                            if (parserInput.$char(';') || isSemiColonSeparated) {
                                if (expressionContainsNamed) {
                                    error("Cannot mix ; and , as delimiter types");
                                }
                                isSemiColonSeparated = true;
                                if (expressions.length > 1) {
                                    value = new (tree.Value)(expressions);
                                }
                                argsSemiColon.push({ name: name, value: value, expand: expand });
                                name = null;
                                expressions = [];
                                expressionContainsNamed = false;
                            }
                        }
                        parserInput.forget();
                        returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
                        return returner;
                    },
                    //
                    // A Mixin definition, with a list of parameters
                    //
                    //     .rounded (@radius: 2px, @color) {
                    //        ...
                    //     }
                    //
                    // Until we have a finer grained state-machine, we have to
                    // do a look-ahead, to make sure we don't have a mixin call.
                    // See the `rule` function for more information.
                    //
                    // We start by matching `.rounded (`, and then proceed on to
                    // the argument list, which has optional default values.
                    // We store the parameters in `params`, with a `value` key,
                    // if there is a value, such as in the case of `@radius`.
                    //
                    // Once we've got our params list, and a closing `)`, we parse
                    // the `{...}` block.
                    //
                    definition: function () {
                        var name, params = [], match, ruleset, cond, variadic = false;
                        if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
                            parserInput.peek(/^[^{]*\}/)) {
                            return;
                        }
                        parserInput.save();
                        match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
                        if (match) {
                            name = match[1];
                            var argInfo = this.args(false);
                            params = argInfo.args;
                            variadic = argInfo.variadic;
                            // .mixincall("@{a}");
                            // looks a bit like a mixin definition..
                            // also
                            // .mixincall(@a: {rule: set;});
                            // so we have to be nice and restore
                            if (!parserInput.$char(')')) {
                                parserInput.restore("Missing closing ')'");
                                return;
                            }
                            parserInput.commentStore.length = 0;
                            if (parserInput.$str("when")) { // Guard
                                cond = expect(parsers.conditions, 'expected condition');
                            }
                            ruleset = parsers.block();
                            if (ruleset) {
                                parserInput.forget();
                                return new (tree.mixin.Definition)(name, params, ruleset, cond, variadic);
                            }
                            else {
                                parserInput.restore();
                            }
                        }
                        else {
                            parserInput.forget();
                        }
                    }
                },
                //
                // Entities are the smallest recognized token,
                // and can be found inside a rule's value.
                //
                entity: function () {
                    var entities = this.entities;
                    return this.comment() || entities.literal() || entities.variable() || entities.url() ||
                        entities.property() || entities.call() || entities.keyword() || entities.javascript();
                },
                //
                // A Declaration terminator. Note that we use `peek()` to check for '}',
                // because the `block` rule will be expecting it, but we still need to make sure
                // it's there, if ';' was omitted.
                //
                end: function () {
                    return parserInput.$char(';') || parserInput.peek('}');
                },
                //
                // IE's alpha function
                //
                //     alpha(opacity=88)
                //
                ieAlpha: function () {
                    var value;
                    // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
                    if (!parserInput.$re(/^opacity=/i)) {
                        return;
                    }
                    value = parserInput.$re(/^\d+/);
                    if (!value) {
                        value = expect(parsers.entities.variable, "Could not parse alpha");
                        value = '@{' + value.name.slice(1) + '}';
                    }
                    expectChar(')');
                    return new tree.Quoted('', 'alpha(opacity=' + value + ')');
                },
                //
                // A Selector Element
                //
                //     div
                //     + h1
                //     #socks
                //     input[type="text"]
                //
                // Elements are the building blocks for Selectors,
                // they are made out of a `Combinator` (see combinator rule),
                // and an element name, such as a tag a class, or `*`.
                //
                element: function () {
                    var e, c, v, index = parserInput.i;
                    c = this.combinator();
                    e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
                        parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
                        parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
                        parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) ||
                        this.entities.variableCurly();
                    if (!e) {
                        parserInput.save();
                        if (parserInput.$char('(')) {
                            if ((v = this.selector(false)) && parserInput.$char(')')) {
                                e = new (tree.Paren)(v);
                                parserInput.forget();
                            }
                            else {
                                parserInput.restore("Missing closing ')'");
                            }
                        }
                        else {
                            parserInput.forget();
                        }
                    }
                    if (e) {
                        return new (tree.Element)(c, e, index, fileInfo);
                    }
                },
                //
                // Combinators combine elements together, in a Selector.
                //
                // Because our parser isn't white-space sensitive, special care
                // has to be taken, when parsing the descendant combinator, ` `,
                // as it's an empty space. We have to check the previous character
                // in the input, to see if it's a ` ` character. More info on how
                // we deal with this in *combinator.js*.
                //
                combinator: function () {
                    var c = parserInput.currentChar();
                    if (c === '/') {
                        parserInput.save();
                        var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
                        if (slashedCombinator) {
                            parserInput.forget();
                            return new (tree.Combinator)(slashedCombinator);
                        }
                        parserInput.restore();
                    }
                    if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
                        parserInput.i++;
                        if (c === '^' && parserInput.currentChar() === '^') {
                            c = '^^';
                            parserInput.i++;
                        }
                        while (parserInput.isWhitespace()) {
                            parserInput.i++;
                        }
                        return new (tree.Combinator)(c);
                    }
                    else if (parserInput.isWhitespace(-1)) {
                        return new (tree.Combinator)(" ");
                    }
                    else {
                        return new (tree.Combinator)(null);
                    }
                },
                //
                // A CSS Selector
                // with less extensions e.g. the ability to extend and guard
                //
                //     .class > div + h1
                //     li a:hover
                //
                // Selectors are made out of one or more Elements, see above.
                //
                selector: function (isLess) {
                    var index = parserInput.i, elements, extendList, c, e, allExtends, when, condition;
                    isLess = isLess !== false;
                    while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str("when"))) || (e = this.element())) {
                        if (when) {
                            condition = expect(this.conditions, 'expected condition');
                        }
                        else if (condition) {
                            error("CSS guard can only be used at the end of selector");
                        }
                        else if (extendList) {
                            if (allExtends) {
                                allExtends = allExtends.concat(extendList);
                            }
                            else {
                                allExtends = extendList;
                            }
                        }
                        else {
                            if (allExtends) {
                                error("Extend can only be used at the end of selector");
                            }
                            c = parserInput.currentChar();
                            if (elements) {
                                elements.push(e);
                            }
                            else {
                                elements = [e];
                            }
                            e = null;
                        }
                        if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
                            break;
                        }
                    }
                    if (elements) {
                        return new (tree.Selector)(elements, allExtends, condition, index, fileInfo);
                    }
                    if (allExtends) {
                        error("Extend must be used to extend a selector, it cannot be used on its own");
                    }
                },
                attribute: function () {
                    if (!parserInput.$char('[')) {
                        return;
                    }
                    var entities = this.entities, key, val, op;
                    if (!(key = entities.variableCurly())) {
                        key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
                    }
                    op = parserInput.$re(/^[|~*$^]?=/);
                    if (op) {
                        val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
                    }
                    expectChar(']');
                    return new (tree.Attribute)(key, op, val);
                },
                //
                // The `block` rule is used by `ruleset` and `mixin.definition`.
                // It's a wrapper around the `primary` rule, with added `{}`.
                //
                block: function () {
                    var content;
                    if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
                        return content;
                    }
                },
                blockRuleset: function () {
                    var block = this.block();
                    if (block) {
                        block = new tree.Ruleset(null, block);
                    }
                    return block;
                },
                detachedRuleset: function () {
                    var blockRuleset = this.blockRuleset();
                    if (blockRuleset) {
                        return new tree.DetachedRuleset(blockRuleset);
                    }
                },
                //
                // div, .class, body > p {...}
                //
                ruleset: function () {
                    var selectors, s, rules, debugInfo;
                    parserInput.save();
                    if (context.dumpLineNumbers) {
                        debugInfo = getDebugInfo(parserInput.i);
                    }
                    while (true) {
                        s = this.selector();
                        if (!s) {
                            break;
                        }
                        if (selectors) {
                            selectors.push(s);
                        }
                        else {
                            selectors = [s];
                        }
                        parserInput.commentStore.length = 0;
                        if (s.condition && selectors.length > 1) {
                            error("Guards are only currently allowed on a single selector.");
                        }
                        if (!parserInput.$char(',')) {
                            break;
                        }
                        if (s.condition) {
                            error("Guards are only currently allowed on a single selector.");
                        }
                        parserInput.commentStore.length = 0;
                    }
                    if (selectors && (rules = this.block())) {
                        parserInput.forget();
                        var ruleset = new (tree.Ruleset)(selectors, rules, context.strictImports);
                        if (context.dumpLineNumbers) {
                            ruleset.debugInfo = debugInfo;
                        }
                        return ruleset;
                    }
                    else {
                        parserInput.restore();
                    }
                },
                declaration: function () {
                    var name, value, startOfRule = parserInput.i, c = parserInput.currentChar(), important, merge, isVariable;
                    if (c === '.' || c === '#' || c === '&' || c === ':') {
                        return;
                    }
                    parserInput.save();
                    name = this.variable() || this.ruleProperty();
                    if (name) {
                        isVariable = typeof name === "string";
                        if (isVariable) {
                            value = this.detachedRuleset();
                        }
                        parserInput.commentStore.length = 0;
                        if (!value) {
                            // a name returned by this.ruleProperty() is always an array of the form:
                            // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
                            // where each item is a tree.Keyword or tree.Variable
                            merge = !isVariable && name.length > 1 && name.pop().value;
                            // Try to store values as anonymous
                            // If we need the value later we'll re-parse it in ruleset.parseValue
                            value = this.anonymousValue();
                            if (value) {
                                parserInput.forget();
                                // anonymous values absorb the end ';' which is required for them to work
                                return new (tree.Declaration)(name, value, false, merge, startOfRule, fileInfo);
                            }
                            if (!value) {
                                value = this.value();
                            }
                            important = this.important();
                        }
                        if (value && this.end()) {
                            parserInput.forget();
                            return new (tree.Declaration)(name, value, important, merge, startOfRule, fileInfo);
                        }
                        else {
                            parserInput.restore();
                        }
                    }
                    else {
                        parserInput.restore();
                    }
                },
                anonymousValue: function () {
                    var index = parserInput.i;
                    var match = parserInput.$re(/^([^@\$+\/'"*`(;{}-]*);/);
                    if (match) {
                        return new (tree.Anonymous)(match[1], index);
                    }
                },
                //
                // An @import atrule
                //
                //     @import "lib";
                //
                // Depending on our environment, importing is done differently:
                // In the browser, it's an XHR request, in Node, it would be a
                // file-system operation. The function used for importing is
                // stored in `import`, which we pass to the Import constructor.
                //
                "import": function () {
                    var path, features, index = parserInput.i;
                    var dir = parserInput.$re(/^@import?\s+/);
                    if (dir) {
                        var options = (dir ? this.importOptions() : null) || {};
                        if ((path = this.entities.quoted() || this.entities.url())) {
                            features = this.mediaFeatures();
                            if (!parserInput.$char(';')) {
                                parserInput.i = index;
                                error("missing semi-colon or unrecognised media features on import");
                            }
                            features = features && new (tree.Value)(features);
                            return new (tree.Import)(path, features, options, index, fileInfo);
                        }
                        else {
                            parserInput.i = index;
                            error("malformed import statement");
                        }
                    }
                },
                importOptions: function () {
                    var o, options = {}, optionName, value;
                    // list of options, surrounded by parens
                    if (!parserInput.$char('(')) {
                        return null;
                    }
                    do {
                        o = this.importOption();
                        if (o) {
                            optionName = o;
                            value = true;
                            switch (optionName) {
                                case "css":
                                    optionName = "less";
                                    value = false;
                                    break;
                                case "once":
                                    optionName = "multiple";
                                    value = false;
                                    break;
                            }
                            options[optionName] = value;
                            if (!parserInput.$char(',')) {
                                break;
                            }
                        }
                    } while (o);
                    expectChar(')');
                    return options;
                },
                importOption: function () {
                    var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
                    if (opt) {
                        return opt[1];
                    }
                },
                mediaFeature: function () {
                    var entities = this.entities, nodes = [], e, p;
                    parserInput.save();
                    do {
                        e = entities.keyword() || entities.variable();
                        if (e) {
                            nodes.push(e);
                        }
                        else if (parserInput.$char('(')) {
                            p = this.property();
                            e = this.value();
                            if (parserInput.$char(')')) {
                                if (p && e) {
                                    nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true)));
                                }
                                else if (e) {
                                    nodes.push(new (tree.Paren)(e));
                                }
                                else {
                                    error("badly formed media feature definition");
                                }
                            }
                            else {
                                error("Missing closing ')'", "Parse");
                            }
                        }
                    } while (e);
                    parserInput.forget();
                    if (nodes.length > 0) {
                        return new (tree.Expression)(nodes);
                    }
                },
                mediaFeatures: function () {
                    var entities = this.entities, features = [], e;
                    do {
                        e = this.mediaFeature();
                        if (e) {
                            features.push(e);
                            if (!parserInput.$char(',')) {
                                break;
                            }
                        }
                        else {
                            e = entities.variable();
                            if (e) {
                                features.push(e);
                                if (!parserInput.$char(',')) {
                                    break;
                                }
                            }
                        }
                    } while (e);
                    return features.length > 0 ? features : null;
                },
                media: function () {
                    var features, rules, media, debugInfo, index = parserInput.i;
                    if (context.dumpLineNumbers) {
                        debugInfo = getDebugInfo(index);
                    }
                    parserInput.save();
                    if (parserInput.$str("@media")) {
                        features = this.mediaFeatures();
                        rules = this.block();
                        if (!rules) {
                            error("media definitions require block statements after any features");
                        }
                        parserInput.forget();
                        media = new (tree.Media)(rules, features, index, fileInfo);
                        if (context.dumpLineNumbers) {
                            media.debugInfo = debugInfo;
                        }
                        return media;
                    }
                    parserInput.restore();
                },
                //
                // A @plugin directive, used to import plugins dynamically.
                //
                //     @plugin (args) "lib";
                //
                plugin: function () {
                    var path, args, options, index = parserInput.i, dir = parserInput.$re(/^@plugin?\s+/);
                    if (dir) {
                        args = this.pluginArgs();
                        if (args) {
                            options = {
                                pluginArgs: args,
                                isPlugin: true
                            };
                        }
                        else {
                            options = { isPlugin: true };
                        }
                        if ((path = this.entities.quoted() || this.entities.url())) {
                            if (!parserInput.$char(';')) {
                                parserInput.i = index;
                                error("missing semi-colon on @plugin");
                            }
                            return new (tree.Import)(path, null, options, index, fileInfo);
                        }
                        else {
                            parserInput.i = index;
                            error("malformed @plugin statement");
                        }
                    }
                },
                pluginArgs: function () {
                    // list of options, surrounded by parens
                    parserInput.save();
                    if (!parserInput.$char('(')) {
                        parserInput.restore();
                        return null;
                    }
                    var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
                    if (args[1]) {
                        parserInput.forget();
                        return args[1].trim();
                    }
                    else {
                        parserInput.restore();
                        return null;
                    }
                },
                //
                // A CSS AtRule
                //
                //     @charset "utf-8";
                //
                atrule: function () {
                    var index = parserInput.i, name, value, rules, nonVendorSpecificName, hasIdentifier, hasExpression, hasUnknown, hasBlock = true, isRooted = true;
                    if (parserInput.currentChar() !== '@') {
                        return;
                    }
                    value = this['import']() || this.plugin() || this.media();
                    if (value) {
                        return value;
                    }
                    parserInput.save();
                    name = parserInput.$re(/^@[a-z-]+/);
                    if (!name) {
                        return;
                    }
                    nonVendorSpecificName = name;
                    if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
                        nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
                    }
                    switch (nonVendorSpecificName) {
                        case "@charset":
                            hasIdentifier = true;
                            hasBlock = false;
                            break;
                        case "@namespace":
                            hasExpression = true;
                            hasBlock = false;
                            break;
                        case "@keyframes":
                        case "@counter-style":
                            hasIdentifier = true;
                            break;
                        case "@document":
                        case "@supports":
                            hasUnknown = true;
                            isRooted = false;
                            break;
                        default:
                            hasUnknown = true;
                            break;
                    }
                    parserInput.commentStore.length = 0;
                    if (hasIdentifier) {
                        value = this.entity();
                        if (!value) {
                            error("expected " + name + " identifier");
                        }
                    }
                    else if (hasExpression) {
                        value = this.expression();
                        if (!value) {
                            error("expected " + name + " expression");
                        }
                    }
                    else if (hasUnknown) {
                        value = (parserInput.$re(/^[^{;]+/) || '').trim();
                        hasBlock = (parserInput.currentChar() == '{');
                        if (value) {
                            value = new (tree.Anonymous)(value);
                        }
                    }
                    if (hasBlock) {
                        rules = this.blockRuleset();
                    }
                    if (rules || (!hasBlock && value && parserInput.$char(';'))) {
                        parserInput.forget();
                        return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
                    }
                    parserInput.restore("at-rule options not recognised");
                },
                //
                // A Value is a comma-delimited list of Expressions
                //
                //     font-family: Baskerville, Georgia, serif;
                //
                // In a Rule, a Value represents everything after the `:`,
                // and before the `;`.
                //
                value: function () {
                    var e, expressions = [], index = parserInput.i;
                    do {
                        e = this.expression();
                        if (e) {
                            expressions.push(e);
                            if (!parserInput.$char(',')) {
                                break;
                            }
                        }
                    } while (e);
                    if (expressions.length > 0) {
                        return new (tree.Value)(expressions, index);
                    }
                },
                important: function () {
                    if (parserInput.currentChar() === '!') {
                        return parserInput.$re(/^! *important/);
                    }
                },
                sub: function () {
                    var a, e;
                    parserInput.save();
                    if (parserInput.$char('(')) {
                        a = this.addition();
                        if (a && parserInput.$char(')')) {
                            parserInput.forget();
                            e = new (tree.Expression)([a]);
                            e.parens = true;
                            return e;
                        }
                        parserInput.restore("Expected ')'");
                        return;
                    }
                    parserInput.restore();
                },
                multiplication: function () {
                    var m, a, op, operation, isSpaced;
                    m = this.operand();
                    if (m) {
                        isSpaced = parserInput.isWhitespace(-1);
                        while (true) {
                            if (parserInput.peek(/^\/[*\/]/)) {
                                break;
                            }
                            parserInput.save();
                            op = parserInput.$char('/') || parserInput.$char('*');
                            if (!op) {
                                parserInput.forget();
                                break;
                            }
                            a = this.operand();
                            if (!a) {
                                parserInput.restore();
                                break;
                            }
                            parserInput.forget();
                            m.parensInOp = true;
                            a.parensInOp = true;
                            operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
                            isSpaced = parserInput.isWhitespace(-1);
                        }
                        return operation || m;
                    }
                },
                addition: function () {
                    var m, a, op, operation, isSpaced;
                    m = this.multiplication();
                    if (m) {
                        isSpaced = parserInput.isWhitespace(-1);
                        while (true) {
                            op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
                            if (!op) {
                                break;
                            }
                            a = this.multiplication();
                            if (!a) {
                                break;
                            }
                            m.parensInOp = true;
                            a.parensInOp = true;
                            operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
                            isSpaced = parserInput.isWhitespace(-1);
                        }
                        return operation || m;
                    }
                },
                conditions: function () {
                    var a, b, index = parserInput.i, condition;
                    a = this.condition();
                    if (a) {
                        while (true) {
                            if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
                                break;
                            }
                            b = this.condition();
                            if (!b) {
                                break;
                            }
                            condition = new (tree.Condition)('or', condition || a, b, index);
                        }
                        return condition || a;
                    }
                },
                condition: function () {
                    var result, logical, next;
                    function or() {
                        return parserInput.$str("or");
                    }
                    result = this.conditionAnd(this);
                    if (!result) {
                        return;
                    }
                    logical = or();
                    if (logical) {
                        next = this.condition();
                        if (next) {
                            result = new (tree.Condition)(logical, result, next);
                        }
                        else {
                            return;
                        }
                    }
                    return result;
                },
                conditionAnd: function () {
                    var result, logical, next;
                    function insideCondition(me) {
                        return me.negatedCondition() || me.parenthesisCondition();
                    }
                    function and() {
                        return parserInput.$str("and");
                    }
                    result = insideCondition(this);
                    if (!result) {
                        return;
                    }
                    logical = and();
                    if (logical) {
                        next = this.conditionAnd();
                        if (next) {
                            result = new (tree.Condition)(logical, result, next);
                        }
                        else {
                            return;
                        }
                    }
                    return result;
                },
                negatedCondition: function () {
                    if (parserInput.$str("not")) {
                        var result = this.parenthesisCondition();
                        if (result) {
                            result.negate = !result.negate;
                        }
                        return result;
                    }
                },
                parenthesisCondition: function () {
                    function tryConditionFollowedByParenthesis(me) {
                        var body;
                        parserInput.save();
                        body = me.condition();
                        if (!body) {
                            parserInput.restore();
                            return;
                        }
                        if (!parserInput.$char(')')) {
                            parserInput.restore();
                            return;
                        }
                        parserInput.forget();
                        return body;
                    }
                    var body;
                    parserInput.save();
                    if (!parserInput.$str("(")) {
                        parserInput.restore();
                        return;
                    }
                    body = tryConditionFollowedByParenthesis(this);
                    if (body) {
                        parserInput.forget();
                        return body;
                    }
                    body = this.atomicCondition();
                    if (!body) {
                        parserInput.restore();
                        return;
                    }
                    if (!parserInput.$char(')')) {
                        parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'");
                        return;
                    }
                    parserInput.forget();
                    return body;
                },
                atomicCondition: function () {
                    var entities = this.entities, index = parserInput.i, a, b, c, op;
                    a = this.addition() || entities.keyword() || entities.quoted();
                    if (a) {
                        if (parserInput.$char('>')) {
                            if (parserInput.$char('=')) {
                                op = ">=";
                            }
                            else {
                                op = '>';
                            }
                        }
                        else if (parserInput.$char('<')) {
                            if (parserInput.$char('=')) {
                                op = "<=";
                            }
                            else {
                                op = '<';
                            }
                        }
                        else if (parserInput.$char('=')) {
                            if (parserInput.$char('>')) {
                                op = "=>";
                            }
                            else if (parserInput.$char('<')) {
                                op = '=<';
                            }
                            else {
                                op = '=';
                            }
                        }
                        if (op) {
                            b = this.addition() || entities.keyword() || entities.quoted();
                            if (b) {
                                c = new (tree.Condition)(op, a, b, index, false);
                            }
                            else {
                                error('expected expression');
                            }
                        }
                        else {
                            c = new (tree.Condition)('=', a, new (tree.Keyword)('true'), index, false);
                        }
                        return c;
                    }
                },
                //
                // An operand is anything that can be part of an operation,
                // such as a Color, or a Variable
                //
                operand: function () {
                    var entities = this.entities, negate;
                    if (parserInput.peek(/^-[@\$\(]/)) {
                        negate = parserInput.$char('-');
                    }
                    var o = this.sub() || entities.dimension() ||
                        entities.color() || entities.variable() ||
                        entities.property() || entities.call() ||
                        entities.colorKeyword();
                    if (negate) {
                        o.parensInOp = true;
                        o = new (tree.Negative)(o);
                    }
                    return o;
                },
                //
                // Expressions either represent mathematical operations,
                // or white-space delimited Entities.
                //
                //     1px solid black
                //     @var * 2
                //
                expression: function () {
                    var entities = [], e, delim, index = parserInput.i;
                    do {
                        e = this.comment();
                        if (e) {
                            entities.push(e);
                            continue;
                        }
                        e = this.addition() || this.entity();
                        if (e) {
                            entities.push(e);
                            // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
                            if (!parserInput.peek(/^\/[\/*]/)) {
                                delim = parserInput.$char('/');
                                if (delim) {
                                    entities.push(new (tree.Anonymous)(delim, index));
                                }
                            }
                        }
                    } while (e);
                    if (entities.length > 0) {
                        return new (tree.Expression)(entities);
                    }
                },
                property: function () {
                    var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
                    if (name) {
                        return name[1];
                    }
                },
                ruleProperty: function () {
                    var name = [], index = [], s, k;
                    parserInput.save();
                    var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
                    if (simpleProperty) {
                        name = [new (tree.Keyword)(simpleProperty[1])];
                        parserInput.forget();
                        return name;
                    }
                    function match(re) {
                        var i = parserInput.i, chunk = parserInput.$re(re);
                        if (chunk) {
                            index.push(i);
                            return name.push(chunk[1]);
                        }
                    }
                    match(/^(\*?)/);
                    while (true) {
                        if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
                            break;
                        }
                    }
                    if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
                        parserInput.forget();
                        // at last, we have the complete match now. move forward,
                        // convert name particles to tree objects and return:
                        if (name[0] === '') {
                            name.shift();
                            index.shift();
                        }
                        for (k = 0; k < name.length; k++) {
                            s = name[k];
                            name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
                                new (tree.Keyword)(s) :
                                (s.charAt(0) === '@' ?
                                    new (tree.Variable)('@' + s.slice(2, -1), index[k], fileInfo) :
                                    new (tree.Property)('$' + s.slice(2, -1), index[k], fileInfo));
                        }
                        return name;
                    }
                    parserInput.restore();
                }
            }
        };
    };
    Parser.serializeVars = function (vars) {
        var s = '';
        for (var name in vars) {
            if (Object.hasOwnProperty.call(vars, name)) {
                var value = vars[name];
                s += ((name[0] === '@') ? '' : '@') + name + ': ' + value +
                    ((String(value).slice(-1) === ';') ? '' : ';');
            }
        }
        return s;
    };
    module.exports = Parser;
}
,
/* less/lib/less/plugin-manager */ function _(require, module, exports) {
    /**
     * Plugin Manager
     */
    var PluginManager = function (less) {
        this.less = less;
        this.visitors = [];
        this.preProcessors = [];
        this.postProcessors = [];
        this.installedPlugins = [];
        this.fileManagers = [];
        this.iterator = -1;
        this.pluginCache = {};
        this.Loader = new less.PluginLoader(less);
    };
    var pm, PluginManagerFactory = function (less, newFactory) {
        if (newFactory || !pm) {
            pm = new PluginManager(less);
        }
        return pm;
    };
    /**
     * Adds all the plugins in the array
     * @param {Array} plugins
     */
    PluginManager.prototype.addPlugins = function (plugins) {
        if (plugins) {
            for (var i = 0; i < plugins.length; i++) {
                this.addPlugin(plugins[i]);
            }
        }
    };
    /**
     *
     * @param plugin
     * @param {String} filename
     */
    PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
        this.installedPlugins.push(plugin);
        if (filename) {
            this.pluginCache[filename] = plugin;
        }
        if (plugin.install) {
            plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
        }
    };
    /**
     *
     * @param filename
     */
    PluginManager.prototype.get = function (filename) {
        return this.pluginCache[filename];
    };
    /**
     * Adds a visitor. The visitor object has options on itself to determine
     * when it should run.
     * @param visitor
     */
    PluginManager.prototype.addVisitor = function (visitor) {
        this.visitors.push(visitor);
    };
    /**
     * Adds a pre processor object
     * @param {object} preProcessor
     * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
     */
    PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
        var indexToInsertAt;
        for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
            if (this.preProcessors[indexToInsertAt].priority >= priority) {
                break;
            }
        }
        this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
    };
    /**
     * Adds a post processor object
     * @param {object} postProcessor
     * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
     */
    PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
        var indexToInsertAt;
        for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
            if (this.postProcessors[indexToInsertAt].priority >= priority) {
                break;
            }
        }
        this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
    };
    /**
     *
     * @param manager
     */
    PluginManager.prototype.addFileManager = function (manager) {
        this.fileManagers.push(manager);
    };
    /**
     *
     * @returns {Array}
     * @private
     */
    PluginManager.prototype.getPreProcessors = function () {
        var preProcessors = [];
        for (var i = 0; i < this.preProcessors.length; i++) {
            preProcessors.push(this.preProcessors[i].preProcessor);
        }
        return preProcessors;
    };
    /**
     *
     * @returns {Array}
     * @private
     */
    PluginManager.prototype.getPostProcessors = function () {
        var postProcessors = [];
        for (var i = 0; i < this.postProcessors.length; i++) {
            postProcessors.push(this.postProcessors[i].postProcessor);
        }
        return postProcessors;
    };
    /**
     *
     * @returns {Array}
     * @private
     */
    PluginManager.prototype.getVisitors = function () {
        return this.visitors;
    };
    PluginManager.prototype.visitor = function () {
        var self = this;
        return {
            first: function () {
                self.iterator = -1;
                return self.visitors[self.iterator];
            },
            get: function () {
                self.iterator += 1;
                return self.visitors[self.iterator];
            }
        };
    };
    /**
     *
     * @returns {Array}
     * @private
     */
    PluginManager.prototype.getFileManagers = function () {
        return this.fileManagers;
    };
    //
    module.exports = PluginManagerFactory;
}
,
/* less/lib/less/render */ function _(require, module, exports) {
    var PromiseConstructor, utils = require(247) /* ./utils */;
    module.exports = function (environment, ParseTree, ImportManager) {
        var render = function (input, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = utils.defaults(this.options, {});
            }
            else {
                options = utils.defaults(this.options, options || {});
            }
            if (!callback) {
                if (!PromiseConstructor) {
                    PromiseConstructor = typeof Promise === 'undefined' ? require(279) /* promise */ : Promise;
                }
                var self = this;
                return new PromiseConstructor(function (resolve, reject) {
                    render.call(self, input, options, function (err, output) {
                        if (err) {
                            reject(err);
                        }
                        else {
                            resolve(output);
                        }
                    });
                });
            }
            else {
                this.parse(input, options, function (err, root, imports, options) {
                    if (err) {
                        return callback(err);
                    }
                    var result;
                    try {
                        var parseTree = new ParseTree(root, imports);
                        result = parseTree.toCSS(options);
                    }
                    catch (err) {
                        return callback(err);
                    }
                    callback(null, result);
                });
            }
        };
        return render;
    };
}
,
/* less/lib/less/source-map-builder */ function _(require, module, exports) {
    module.exports = function (SourceMapOutput, environment) {
        var SourceMapBuilder = function (options) {
            this.options = options;
        };
        SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
            var sourceMapOutput = new SourceMapOutput({
                contentsIgnoredCharsMap: imports.contentsIgnoredChars,
                rootNode: rootNode,
                contentsMap: imports.contents,
                sourceMapFilename: this.options.sourceMapFilename,
                sourceMapURL: this.options.sourceMapURL,
                outputFilename: this.options.sourceMapOutputFilename,
                sourceMapBasepath: this.options.sourceMapBasepath,
                sourceMapRootpath: this.options.sourceMapRootpath,
                outputSourceFiles: this.options.outputSourceFiles,
                sourceMapGenerator: this.options.sourceMapGenerator,
                sourceMapFileInline: this.options.sourceMapFileInline
            });
            var css = sourceMapOutput.toCSS(options);
            this.sourceMap = sourceMapOutput.sourceMap;
            this.sourceMapURL = sourceMapOutput.sourceMapURL;
            if (this.options.sourceMapInputFilename) {
                this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
            }
            if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
                this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
            }
            return css + this.getCSSAppendage();
        };
        SourceMapBuilder.prototype.getCSSAppendage = function () {
            var sourceMapURL = this.sourceMapURL;
            if (this.options.sourceMapFileInline) {
                if (this.sourceMap === undefined) {
                    return "";
                }
                sourceMapURL = "data:application/json;base64," + environment.encodeBase64(this.sourceMap);
            }
            if (sourceMapURL) {
                return "/*# sourceMappingURL=" + sourceMapURL + " */";
            }
            return "";
        };
        SourceMapBuilder.prototype.getExternalSourceMap = function () {
            return this.sourceMap;
        };
        SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
            this.sourceMap = sourceMap;
        };
        SourceMapBuilder.prototype.isInline = function () {
            return this.options.sourceMapFileInline;
        };
        SourceMapBuilder.prototype.getSourceMapURL = function () {
            return this.sourceMapURL;
        };
        SourceMapBuilder.prototype.getOutputFilename = function () {
            return this.options.sourceMapOutputFilename;
        };
        SourceMapBuilder.prototype.getInputFilename = function () {
            return this.sourceMapInputFilename;
        };
        return SourceMapBuilder;
    };
}
,
/* less/lib/less/source-map-output */ function _(require, module, exports) {
    module.exports = function (environment) {
        var SourceMapOutput = function (options) {
            this._css = [];
            this._rootNode = options.rootNode;
            this._contentsMap = options.contentsMap;
            this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
            if (options.sourceMapFilename) {
                this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
            }
            this._outputFilename = options.outputFilename;
            this.sourceMapURL = options.sourceMapURL;
            if (options.sourceMapBasepath) {
                this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
            }
            if (options.sourceMapRootpath) {
                this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
                if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
                    this._sourceMapRootpath += '/';
                }
            }
            else {
                this._sourceMapRootpath = "";
            }
            this._outputSourceFiles = options.outputSourceFiles;
            this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
            this._lineNumber = 0;
            this._column = 0;
        };
        SourceMapOutput.prototype.removeBasepath = function (path) {
            if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
                path = path.substring(this._sourceMapBasepath.length);
                if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
                    path = path.substring(1);
                }
            }
            return path;
        };
        SourceMapOutput.prototype.normalizeFilename = function (filename) {
            filename = filename.replace(/\\/g, '/');
            filename = this.removeBasepath(filename);
            return (this._sourceMapRootpath || "") + filename;
        };
        SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
            // ignore adding empty strings
            if (!chunk) {
                return;
            }
            var lines, sourceLines, columns, sourceColumns, i;
            if (fileInfo) {
                var inputSource = this._contentsMap[fileInfo.filename];
                // remove vars/banner added to the top of the file
                if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
                    // adjust the index
                    index -= this._contentsIgnoredCharsMap[fileInfo.filename];
                    if (index < 0) {
                        index = 0;
                    }
                    // adjust the source
                    inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
                }
                inputSource = inputSource.substring(0, index);
                sourceLines = inputSource.split("\n");
                sourceColumns = sourceLines[sourceLines.length - 1];
            }
            lines = chunk.split("\n");
            columns = lines[lines.length - 1];
            if (fileInfo) {
                if (!mapLines) {
                    this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
                        original: { line: sourceLines.length, column: sourceColumns.length },
                        source: this.normalizeFilename(fileInfo.filename) });
                }
                else {
                    for (i = 0; i < lines.length; i++) {
                        this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
                            original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
                            source: this.normalizeFilename(fileInfo.filename) });
                    }
                }
            }
            if (lines.length === 1) {
                this._column += columns.length;
            }
            else {
                this._lineNumber += lines.length - 1;
                this._column = columns.length;
            }
            this._css.push(chunk);
        };
        SourceMapOutput.prototype.isEmpty = function () {
            return this._css.length === 0;
        };
        SourceMapOutput.prototype.toCSS = function (context) {
            this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
            if (this._outputSourceFiles) {
                for (var filename in this._contentsMap) {
                    if (this._contentsMap.hasOwnProperty(filename)) {
                        var source = this._contentsMap[filename];
                        if (this._contentsIgnoredCharsMap[filename]) {
                            source = source.slice(this._contentsIgnoredCharsMap[filename]);
                        }
                        this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
                    }
                }
            }
            this._rootNode.genCSS(context, this);
            if (this._css.length > 0) {
                var sourceMapURL, sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
                if (this.sourceMapURL) {
                    sourceMapURL = this.sourceMapURL;
                }
                else if (this._sourceMapFilename) {
                    sourceMapURL = this._sourceMapFilename;
                }
                this.sourceMapURL = sourceMapURL;
                this.sourceMap = sourceMapContent;
            }
            return this._css.join('');
        };
        return SourceMapOutput;
    };
}
,
/* less/lib/less/transform-tree */ function _(require, module, exports) {
    var contexts = require(173) /* ./contexts */, visitor = require(251) /* ./visitors */, tree = require(226) /* ./tree */;
    module.exports = function (root, options) {
        options = options || {};
        var evaldRoot, variables = options.variables, evalEnv = new contexts.Eval(options);
        //
        // Allows setting variables with a hash, so:
        //
        //   `{ color: new tree.Color('#f01') }` will become:
        //
        //   new tree.Declaration('@color',
        //     new tree.Value([
        //       new tree.Expression([
        //         new tree.Color('#f01')
        //       ])
        //     ])
        //   )
        //
        if (typeof variables === 'object' && !Array.isArray(variables)) {
            variables = Object.keys(variables).map(function (k) {
                var value = variables[k];
                if (!(value instanceof tree.Value)) {
                    if (!(value instanceof tree.Expression)) {
                        value = new tree.Expression([value]);
                    }
                    value = new tree.Value([value]);
                }
                return new tree.Declaration('@' + k, value, false, null, 0);
            });
            evalEnv.frames = [new tree.Ruleset(null, variables)];
        }
        var visitors = [
            new visitor.JoinSelectorVisitor(),
            new visitor.MarkVisibleSelectorsVisitor(true),
            new visitor.ExtendVisitor(),
            new visitor.ToCSSVisitor({ compress: Boolean(options.compress) })
        ], v, visitorIterator;
        // first() / get() allows visitors to be added while visiting
        if (options.pluginManager) {
            visitorIterator = options.pluginManager.visitor();
            visitorIterator.first();
            while ((v = visitorIterator.get())) {
                if (v.isPreEvalVisitor) {
                    v.run(root);
                }
            }
        }
        evaldRoot = root.eval(evalEnv);
        for (var i = 0; i < visitors.length; i++) {
            visitors[i].run(evaldRoot);
        }
        if (options.pluginManager) {
            visitorIterator.first();
            while ((v = visitorIterator.get())) {
                if (!v.isPreEvalVisitor) {
                    v.run(evaldRoot);
                }
            }
        }
        return evaldRoot;
    };
}
,
/* less/lib/less/tree/anonymous */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
        this.value = value;
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.mapLines = mapLines;
        this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
        this.allowRoot = true;
        this.copyVisibilityInfo(visibilityInfo);
    };
    Anonymous.prototype = new Node();
    Anonymous.prototype.type = "Anonymous";
    Anonymous.prototype.eval = function () {
        return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
    };
    Anonymous.prototype.compare = function (other) {
        return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
    };
    Anonymous.prototype.isRulesetLike = function () {
        return this.rulesetLike;
    };
    Anonymous.prototype.genCSS = function (context, output) {
        this.nodeVisible = Boolean(this.value);
        if (this.nodeVisible) {
            output.add(this.value, this._fileInfo, this._index, this.mapLines);
        }
    };
    module.exports = Anonymous;
}
,
/* less/lib/less/tree/assignment */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Assignment = function (key, val) {
        this.key = key;
        this.value = val;
    };
    Assignment.prototype = new Node();
    Assignment.prototype.type = "Assignment";
    Assignment.prototype.accept = function (visitor) {
        this.value = visitor.visit(this.value);
    };
    Assignment.prototype.eval = function (context) {
        if (this.value.eval) {
            return new Assignment(this.key, this.value.eval(context));
        }
        return this;
    };
    Assignment.prototype.genCSS = function (context, output) {
        output.add(this.key + '=');
        if (this.value.genCSS) {
            this.value.genCSS(context, output);
        }
        else {
            output.add(this.value);
        }
    };
    module.exports = Assignment;
}
,
/* less/lib/less/tree/atrule */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Selector = require(240) /* ./selector */, Ruleset = require(239) /* ./ruleset */, Anonymous = require(209) /* ./anonymous */;
    var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
        var i;
        this.name = name;
        this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
        if (rules) {
            if (Array.isArray(rules)) {
                this.rules = rules;
            }
            else {
                this.rules = [rules];
                this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
            }
            for (i = 0; i < this.rules.length; i++) {
                this.rules[i].allowImports = true;
            }
            this.setParent(this.rules, this);
        }
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.debugInfo = debugInfo;
        this.isRooted = isRooted || false;
        this.copyVisibilityInfo(visibilityInfo);
        this.allowRoot = true;
    };
    AtRule.prototype = new Node();
    AtRule.prototype.type = "AtRule";
    AtRule.prototype.accept = function (visitor) {
        var value = this.value, rules = this.rules;
        if (rules) {
            this.rules = visitor.visitArray(rules);
        }
        if (value) {
            this.value = visitor.visit(value);
        }
    };
    AtRule.prototype.isRulesetLike = function () {
        return this.rules || !this.isCharset();
    };
    AtRule.prototype.isCharset = function () {
        return "@charset" === this.name;
    };
    AtRule.prototype.genCSS = function (context, output) {
        var value = this.value, rules = this.rules;
        output.add(this.name, this.fileInfo(), this.getIndex());
        if (value) {
            output.add(' ');
            value.genCSS(context, output);
        }
        if (rules) {
            this.outputRuleset(context, output, rules);
        }
        else {
            output.add(';');
        }
    };
    AtRule.prototype.eval = function (context) {
        var mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules;
        // media stored inside other atrule should not bubble over it
        // backpup media bubbling information
        mediaPathBackup = context.mediaPath;
        mediaBlocksBackup = context.mediaBlocks;
        // deleted media bubbling information
        context.mediaPath = [];
        context.mediaBlocks = [];
        if (value) {
            value = value.eval(context);
        }
        if (rules) {
            // assuming that there is only one rule at this point - that is how parser constructs the rule
            rules = [rules[0].eval(context)];
            rules[0].root = true;
        }
        // restore media bubbling information
        context.mediaPath = mediaPathBackup;
        context.mediaBlocks = mediaBlocksBackup;
        return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
    };
    AtRule.prototype.variable = function (name) {
        if (this.rules) {
            // assuming that there is only one rule at this point - that is how parser constructs the rule
            return Ruleset.prototype.variable.call(this.rules[0], name);
        }
    };
    AtRule.prototype.find = function () {
        if (this.rules) {
            // assuming that there is only one rule at this point - that is how parser constructs the rule
            return Ruleset.prototype.find.apply(this.rules[0], arguments);
        }
    };
    AtRule.prototype.rulesets = function () {
        if (this.rules) {
            // assuming that there is only one rule at this point - that is how parser constructs the rule
            return Ruleset.prototype.rulesets.apply(this.rules[0]);
        }
    };
    AtRule.prototype.outputRuleset = function (context, output, rules) {
        var ruleCnt = rules.length, i;
        context.tabLevel = (context.tabLevel | 0) + 1;
        // Compressed
        if (context.compress) {
            output.add('{');
            for (i = 0; i < ruleCnt; i++) {
                rules[i].genCSS(context, output);
            }
            output.add('}');
            context.tabLevel--;
            return;
        }
        // Non-compressed
        var tabSetStr = '\n' + Array(context.tabLevel).join("  "), tabRuleStr = tabSetStr + "  ";
        if (!ruleCnt) {
            output.add(" {" + tabSetStr + '}');
        }
        else {
            output.add(" {" + tabRuleStr);
            rules[0].genCSS(context, output);
            for (i = 1; i < ruleCnt; i++) {
                output.add(tabRuleStr);
                rules[i].genCSS(context, output);
            }
            output.add(tabSetStr + '}');
        }
        context.tabLevel--;
    };
    module.exports = AtRule;
}
,
/* less/lib/less/tree/attribute */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Attribute = function (key, op, value) {
        this.key = key;
        this.op = op;
        this.value = value;
    };
    Attribute.prototype = new Node();
    Attribute.prototype.type = "Attribute";
    Attribute.prototype.eval = function (context) {
        return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(context) : this.value);
    };
    Attribute.prototype.genCSS = function (context, output) {
        output.add(this.toCSS(context));
    };
    Attribute.prototype.toCSS = function (context) {
        var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
        if (this.op) {
            value += this.op;
            value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
        }
        return '[' + value + ']';
    };
    module.exports = Attribute;
}
,
/* less/lib/less/tree/call */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Anonymous = require(209) /* ./anonymous */, FunctionCaller = require(186) /* ../functions/function-caller */;
    //
    // A function call node.
    //
    var Call = function (name, args, index, currentFileInfo) {
        this.name = name;
        this.args = args;
        this.mathOn = name === 'calc' ? false : true;
        this._index = index;
        this._fileInfo = currentFileInfo;
    };
    Call.prototype = new Node();
    Call.prototype.type = "Call";
    Call.prototype.accept = function (visitor) {
        if (this.args) {
            this.args = visitor.visitArray(this.args);
        }
    };
    //
    // When evaluating a function call,
    // we either find the function in the functionRegistry,
    // in which case we call it, passing the  evaluated arguments,
    // if this returns null or we cannot find the function, we
    // simply print it out as it appeared originally [2].
    //
    // The reason why we evaluate the arguments, is in the case where
    // we try to pass a variable to a function, like: `saturate(@color)`.
    // The function should receive the value, not the variable.
    //
    Call.prototype.eval = function (context) {
        /**
         * Turn off math for calc(), and switch back on for evaluating nested functions
         */
        var currentMathContext = context.mathOn;
        context.mathOn = this.mathOn;
        var args = this.args.map(function (a) { return a.eval(context); });
        context.mathOn = currentMathContext;
        var result, funcCaller = new FunctionCaller(this.name, context, this.getIndex(), this.fileInfo());
        if (funcCaller.isValid()) {
            try {
                result = funcCaller.call(args);
            }
            catch (e) {
                throw {
                    type: e.type || "Runtime",
                    message: "error evaluating function `" + this.name + "`" +
                        (e.message ? ': ' + e.message : ''),
                    index: this.getIndex(),
                    filename: this.fileInfo().filename,
                    line: e.lineNumber,
                    column: e.columnNumber
                };
            }
            if (result !== null && result !== undefined) {
                // Results that that are not nodes are cast as Anonymous nodes
                // Falsy values or booleans are returned as empty nodes
                if (!(result instanceof Node)) {
                    if (!result || result === true) {
                        result = new Anonymous(null);
                    }
                    else {
                        result = new Anonymous(result.toString());
                    }
                }
                result._index = this._index;
                result._fileInfo = this._fileInfo;
                return result;
            }
        }
        return new Call(this.name, args, this.getIndex(), this.fileInfo());
    };
    Call.prototype.genCSS = function (context, output) {
        output.add(this.name + "(", this.fileInfo(), this.getIndex());
        for (var i = 0; i < this.args.length; i++) {
            this.args[i].genCSS(context, output);
            if (i + 1 < this.args.length) {
                output.add(", ");
            }
        }
        output.add(")");
    };
    module.exports = Call;
}
,
/* less/lib/less/tree/color */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, colors = require(174) /* ../data/colors */;
    //
    // RGB Colors - #ff0014, #eee
    //
    var Color = function (rgb, a, originalForm) {
        //
        // The end goal here, is to parse the arguments
        // into an integer triplet, such as `128, 255, 0`
        //
        // This facilitates operations and conversions.
        //
        if (Array.isArray(rgb)) {
            this.rgb = rgb;
        }
        else if (rgb.length == 6) {
            this.rgb = rgb.match(/.{2}/g).map(function (c) {
                return parseInt(c, 16);
            });
        }
        else {
            this.rgb = rgb.split('').map(function (c) {
                return parseInt(c + c, 16);
            });
        }
        this.alpha = typeof a === 'number' ? a : 1;
        if (typeof originalForm !== 'undefined') {
            this.value = originalForm;
        }
    };
    Color.prototype = new Node();
    Color.prototype.type = "Color";
    function clamp(v, max) {
        return Math.min(Math.max(v, 0), max);
    }
    function toHex(v) {
        return '#' + v.map(function (c) {
            c = clamp(Math.round(c), 255);
            return (c < 16 ? '0' : '') + c.toString(16);
        }).join('');
    }
    Color.prototype.luma = function () {
        var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255;
        r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
        g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
        b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
        return 0.2126 * r + 0.7152 * g + 0.0722 * b;
    };
    Color.prototype.genCSS = function (context, output) {
        output.add(this.toCSS(context));
    };
    Color.prototype.toCSS = function (context, doNotCompress) {
        var compress = context && context.compress && !doNotCompress, color, alpha;
        // `value` is set if this color was originally
        // converted from a named color string so we need
        // to respect this and try to output named color too.
        if (this.value) {
            return this.value;
        }
        // If we have some transparency, the only way to represent it
        // is via `rgba`. Otherwise, we use the hex representation,
        // which has better compatibility with older browsers.
        // Values are capped between `0` and `255`, rounded and zero-padded.
        alpha = this.fround(context, this.alpha);
        if (alpha < 1) {
            return "rgba(" + this.rgb.map(function (c) {
                return clamp(Math.round(c), 255);
            }).concat(clamp(alpha, 1))
                .join(',' + (compress ? '' : ' ')) + ")";
        }
        color = this.toRGB();
        if (compress) {
            var splitcolor = color.split('');
            // Convert color to short format
            if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
                color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5];
            }
        }
        return color;
    };
    //
    // Operations have to be done per-channel, if not,
    // channels will spill onto each other. Once we have
    // our result, in the form of an integer triplet,
    // we create a new Color node to hold the result.
    //
    Color.prototype.operate = function (context, op, other) {
        var rgb = new Array(3);
        var alpha = this.alpha * (1 - other.alpha) + other.alpha;
        for (var c = 0; c < 3; c++) {
            rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
        }
        return new Color(rgb, alpha);
    };
    Color.prototype.toRGB = function () {
        return toHex(this.rgb);
    };
    Color.prototype.toHSL = function () {
        var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
        var max = Math.max(r, g, b), min = Math.min(r, g, b);
        var h, s, l = (max + min) / 2, d = max - min;
        if (max === min) {
            h = s = 0;
        }
        else {
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
                case r:
                    h = (g - b) / d + (g < b ? 6 : 0);
                    break;
                case g:
                    h = (b - r) / d + 2;
                    break;
                case b:
                    h = (r - g) / d + 4;
                    break;
            }
            h /= 6;
        }
        return { h: h * 360, s: s, l: l, a: a };
    };
    // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
    Color.prototype.toHSV = function () {
        var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
        var max = Math.max(r, g, b), min = Math.min(r, g, b);
        var h, s, v = max;
        var d = max - min;
        if (max === 0) {
            s = 0;
        }
        else {
            s = d / max;
        }
        if (max === min) {
            h = 0;
        }
        else {
            switch (max) {
                case r:
                    h = (g - b) / d + (g < b ? 6 : 0);
                    break;
                case g:
                    h = (b - r) / d + 2;
                    break;
                case b:
                    h = (r - g) / d + 4;
                    break;
            }
            h /= 6;
        }
        return { h: h * 360, s: s, v: v, a: a };
    };
    Color.prototype.toARGB = function () {
        return toHex([this.alpha * 255].concat(this.rgb));
    };
    Color.prototype.compare = function (x) {
        return (x.rgb &&
            x.rgb[0] === this.rgb[0] &&
            x.rgb[1] === this.rgb[1] &&
            x.rgb[2] === this.rgb[2] &&
            x.alpha === this.alpha) ? 0 : undefined;
    };
    Color.fromKeyword = function (keyword) {
        var c, key = keyword.toLowerCase();
        if (colors.hasOwnProperty(key)) {
            c = new Color(colors[key].slice(1));
        }
        else if (key === "transparent") {
            c = new Color([0, 0, 0], 0);
        }
        if (c) {
            c.value = keyword;
            return c;
        }
    };
    module.exports = Color;
}
,
/* less/lib/less/tree/combinator */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Combinator = function (value) {
        if (value === ' ') {
            this.value = ' ';
            this.emptyOrWhitespace = true;
        }
        else {
            this.value = value ? value.trim() : "";
            this.emptyOrWhitespace = this.value === "";
        }
    };
    Combinator.prototype = new Node();
    Combinator.prototype.type = "Combinator";
    var _noSpaceCombinators = {
        '': true,
        ' ': true,
        '|': true
    };
    Combinator.prototype.genCSS = function (context, output) {
        var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
        output.add(spaceOrEmpty + this.value + spaceOrEmpty);
    };
    module.exports = Combinator;
}
,
/* less/lib/less/tree/comment */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, getDebugInfo = require(218) /* ./debug-info */;
    var Comment = function (value, isLineComment, index, currentFileInfo) {
        this.value = value;
        this.isLineComment = isLineComment;
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.allowRoot = true;
    };
    Comment.prototype = new Node();
    Comment.prototype.type = "Comment";
    Comment.prototype.genCSS = function (context, output) {
        if (this.debugInfo) {
            output.add(getDebugInfo(context, this), this.fileInfo(), this.getIndex());
        }
        output.add(this.value);
    };
    Comment.prototype.isSilent = function (context) {
        var isCompressed = context.compress && this.value[2] !== "!";
        return this.isLineComment || isCompressed;
    };
    module.exports = Comment;
}
,
/* less/lib/less/tree/condition */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Condition = function (op, l, r, i, negate) {
        this.op = op.trim();
        this.lvalue = l;
        this.rvalue = r;
        this._index = i;
        this.negate = negate;
    };
    Condition.prototype = new Node();
    Condition.prototype.type = "Condition";
    Condition.prototype.accept = function (visitor) {
        this.lvalue = visitor.visit(this.lvalue);
        this.rvalue = visitor.visit(this.rvalue);
    };
    Condition.prototype.eval = function (context) {
        var result = (function (op, a, b) {
            switch (op) {
                case 'and': return a && b;
                case 'or': return a || b;
                default:
                    switch (Node.compare(a, b)) {
                        case -1:
                            return op === '<' || op === '=<' || op === '<=';
                        case 0:
                            return op === '=' || op === '>=' || op === '=<' || op === '<=';
                        case 1:
                            return op === '>' || op === '>=';
                        default:
                            return false;
                    }
            }
        })(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
        return this.negate ? !result : result;
    };
    module.exports = Condition;
}
,
/* less/lib/less/tree/debug-info */ function _(require, module, exports) {
    var debugInfo = function (context, ctx, lineSeparator) {
        var result = "";
        if (context.dumpLineNumbers && !context.compress) {
            switch (context.dumpLineNumbers) {
                case 'comments':
                    result = debugInfo.asComment(ctx);
                    break;
                case 'mediaquery':
                    result = debugInfo.asMediaQuery(ctx);
                    break;
                case 'all':
                    result = debugInfo.asComment(ctx) + (lineSeparator || "") + debugInfo.asMediaQuery(ctx);
                    break;
            }
        }
        return result;
    };
    debugInfo.asComment = function (ctx) {
        return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n';
    };
    debugInfo.asMediaQuery = function (ctx) {
        var filenameWithProtocol = ctx.debugInfo.fileName;
        if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
            filenameWithProtocol = 'file://' + filenameWithProtocol;
        }
        return '@media -sass-debug-info{filename{font-family:' +
            filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
                if (a == '\\') {
                    a = '\/';
                }
                return '\\' + a;
            }) +
            '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n';
    };
    module.exports = debugInfo;
}
,
/* less/lib/less/tree/declaration */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Value = require(244) /* ./value */, Keyword = require(229) /* ./keyword */, Anonymous = require(209) /* ./anonymous */;
    var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) {
        this.name = name;
        this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
        this.important = important ? ' ' + important.trim() : '';
        this.merge = merge;
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.inline = inline || false;
        this.variable = (variable !== undefined) ? variable
            : (name.charAt && (name.charAt(0) === '@'));
        this.allowRoot = true;
        this.setParent(this.value, this);
    };
    function evalName(context, name) {
        var value = "", i, n = name.length, output = { add: function (s) { value += s; } };
        for (i = 0; i < n; i++) {
            name[i].eval(context).genCSS(context, output);
        }
        return value;
    }
    Declaration.prototype = new Node();
    Declaration.prototype.type = "Declaration";
    Declaration.prototype.genCSS = function (context, output) {
        output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
        try {
            this.value.genCSS(context, output);
        }
        catch (e) {
            e.index = this._index;
            e.filename = this._fileInfo.filename;
            throw e;
        }
        output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? "" : ";"), this._fileInfo, this._index);
    };
    Declaration.prototype.eval = function (context) {
        var strictMathBypass = false, name = this.name, evaldValue, variable = this.variable;
        if (typeof name !== "string") {
            // expand 'primitive' name directly to get
            // things faster (~10% for benchmark.less):
            name = (name.length === 1) && (name[0] instanceof Keyword) ?
                name[0].value : evalName(context, name);
            variable = false; // never treat expanded interpolation as new variable name
        }
        if (name === "font" && !context.strictMath) {
            strictMathBypass = true;
            context.strictMath = true;
        }
        try {
            context.importantScope.push({});
            evaldValue = this.value.eval(context);
            if (!this.variable && evaldValue.type === "DetachedRuleset") {
                throw { message: "Rulesets cannot be evaluated on a property.",
                    index: this.getIndex(), filename: this.fileInfo().filename };
            }
            var important = this.important, importantResult = context.importantScope.pop();
            if (!important && importantResult.important) {
                important = importantResult.important;
            }
            return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
        }
        catch (e) {
            if (typeof e.index !== 'number') {
                e.index = this.getIndex();
                e.filename = this.fileInfo().filename;
            }
            throw e;
        }
        finally {
            if (strictMathBypass) {
                context.strictMath = false;
            }
        }
    };
    Declaration.prototype.makeImportant = function () {
        return new Declaration(this.name, this.value, "!important", this.merge, this.getIndex(), this.fileInfo(), this.inline);
    };
    module.exports = Declaration;
}
,
/* less/lib/less/tree/detached-ruleset */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, contexts = require(173) /* ../contexts */, utils = require(247) /* ../utils */;
    var DetachedRuleset = function (ruleset, frames) {
        this.ruleset = ruleset;
        this.frames = frames;
        this.setParent(this.ruleset, this);
    };
    DetachedRuleset.prototype = new Node();
    DetachedRuleset.prototype.type = "DetachedRuleset";
    DetachedRuleset.prototype.evalFirst = true;
    DetachedRuleset.prototype.accept = function (visitor) {
        this.ruleset = visitor.visit(this.ruleset);
    };
    DetachedRuleset.prototype.eval = function (context) {
        var frames = this.frames || utils.copyArray(context.frames);
        return new DetachedRuleset(this.ruleset, frames);
    };
    DetachedRuleset.prototype.callEval = function (context) {
        return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
    };
    module.exports = DetachedRuleset;
}
,
/* less/lib/less/tree/dimension */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, unitConversions = require(176) /* ../data/unit-conversions */, Unit = require(242) /* ./unit */, Color = require(214) /* ./color */;
    //
    // A number with a unit
    //
    var Dimension = function (value, unit) {
        this.value = parseFloat(value);
        if (isNaN(this.value)) {
            throw new Error("Dimension is not a number.");
        }
        this.unit = (unit && unit instanceof Unit) ? unit :
            new Unit(unit ? [unit] : undefined);
        this.setParent(this.unit, this);
    };
    Dimension.prototype = new Node();
    Dimension.prototype.type = "Dimension";
    Dimension.prototype.accept = function (visitor) {
        this.unit = visitor.visit(this.unit);
    };
    Dimension.prototype.eval = function (context) {
        return this;
    };
    Dimension.prototype.toColor = function () {
        return new Color([this.value, this.value, this.value]);
    };
    Dimension.prototype.genCSS = function (context, output) {
        if ((context && context.strictUnits) && !this.unit.isSingular()) {
            throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: " + this.unit.toString());
        }
        var value = this.fround(context, this.value), strValue = String(value);
        if (value !== 0 && value < 0.000001 && value > -0.000001) {
            // would be output 1e-6 etc.
            strValue = value.toFixed(20).replace(/0+$/, "");
        }
        if (context && context.compress) {
            // Zero values doesn't need a unit
            if (value === 0 && this.unit.isLength()) {
                output.add(strValue);
                return;
            }
            // Float values doesn't need a leading zero
            if (value > 0 && value < 1) {
                strValue = (strValue).substr(1);
            }
        }
        output.add(strValue);
        this.unit.genCSS(context, output);
    };
    // In an operation between two Dimensions,
    // we default to the first Dimension's unit,
    // so `1px + 2` will yield `3px`.
    Dimension.prototype.operate = function (context, op, other) {
        /* jshint noempty:false */
        var value = this._operate(context, op, this.value, other.value), unit = this.unit.clone();
        if (op === '+' || op === '-') {
            if (unit.numerator.length === 0 && unit.denominator.length === 0) {
                unit = other.unit.clone();
                if (this.unit.backupUnit) {
                    unit.backupUnit = this.unit.backupUnit;
                }
            }
            else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) {
                // do nothing
            }
            else {
                other = other.convertTo(this.unit.usedUnits());
                if (context.strictUnits && other.unit.toString() !== unit.toString()) {
                    throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() +
                        "' and '" + other.unit.toString() + "'.");
                }
                value = this._operate(context, op, this.value, other.value);
            }
        }
        else if (op === '*') {
            unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
            unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
            unit.cancel();
        }
        else if (op === '/') {
            unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
            unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
            unit.cancel();
        }
        return new Dimension(value, unit);
    };
    Dimension.prototype.compare = function (other) {
        var a, b;
        if (!(other instanceof Dimension)) {
            return undefined;
        }
        if (this.unit.isEmpty() || other.unit.isEmpty()) {
            a = this;
            b = other;
        }
        else {
            a = this.unify();
            b = other.unify();
            if (a.unit.compare(b.unit) !== 0) {
                return undefined;
            }
        }
        return Node.numericCompare(a.value, b.value);
    };
    Dimension.prototype.unify = function () {
        return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
    };
    Dimension.prototype.convertTo = function (conversions) {
        var value = this.value, unit = this.unit.clone(), i, groupName, group, targetUnit, derivedConversions = {}, applyUnit;
        if (typeof conversions === 'string') {
            for (i in unitConversions) {
                if (unitConversions[i].hasOwnProperty(conversions)) {
                    derivedConversions = {};
                    derivedConversions[i] = conversions;
                }
            }
            conversions = derivedConversions;
        }
        applyUnit = function (atomicUnit, denominator) {
            /* jshint loopfunc:true */
            if (group.hasOwnProperty(atomicUnit)) {
                if (denominator) {
                    value = value / (group[atomicUnit] / group[targetUnit]);
                }
                else {
                    value = value * (group[atomicUnit] / group[targetUnit]);
                }
                return targetUnit;
            }
            return atomicUnit;
        };
        for (groupName in conversions) {
            if (conversions.hasOwnProperty(groupName)) {
                targetUnit = conversions[groupName];
                group = unitConversions[groupName];
                unit.map(applyUnit);
            }
        }
        unit.cancel();
        return new Dimension(value, unit);
    };
    module.exports = Dimension;
}
,
/* less/lib/less/tree/element */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Paren = require(236) /* ./paren */, Combinator = require(215) /* ./combinator */;
    var Element = function (combinator, value, index, currentFileInfo, visibilityInfo) {
        this.combinator = combinator instanceof Combinator ?
            combinator : new Combinator(combinator);
        if (typeof value === 'string') {
            this.value = value.trim();
        }
        else if (value) {
            this.value = value;
        }
        else {
            this.value = "";
        }
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.copyVisibilityInfo(visibilityInfo);
        this.setParent(this.combinator, this);
    };
    Element.prototype = new Node();
    Element.prototype.type = "Element";
    Element.prototype.accept = function (visitor) {
        var value = this.value;
        this.combinator = visitor.visit(this.combinator);
        if (typeof value === "object") {
            this.value = visitor.visit(value);
        }
    };
    Element.prototype.eval = function (context) {
        return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.getIndex(), this.fileInfo(), this.visibilityInfo());
    };
    Element.prototype.clone = function () {
        return new Element(this.combinator, this.value, this.getIndex(), this.fileInfo(), this.visibilityInfo());
    };
    Element.prototype.genCSS = function (context, output) {
        output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
    };
    Element.prototype.toCSS = function (context) {
        context = context || {};
        var value = this.value, firstSelector = context.firstSelector;
        if (value instanceof Paren) {
            // selector in parens should not be affected by outer selector
            // flags (breaks only interpolated selectors - see #1973)
            context.firstSelector = true;
        }
        value = value.toCSS ? value.toCSS(context) : value;
        context.firstSelector = firstSelector;
        if (value === '' && this.combinator.value.charAt(0) === '&') {
            return '';
        }
        else {
            return this.combinator.toCSS(context) + value;
        }
    };
    module.exports = Element;
}
,
/* less/lib/less/tree/expression */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Paren = require(236) /* ./paren */, Comment = require(216) /* ./comment */;
    var Expression = function (value) {
        this.value = value;
        if (!value) {
            throw new Error("Expression requires an array parameter");
        }
    };
    Expression.prototype = new Node();
    Expression.prototype.type = "Expression";
    Expression.prototype.accept = function (visitor) {
        this.value = visitor.visitArray(this.value);
    };
    Expression.prototype.eval = function (context) {
        var returnValue, inParenthesis = this.parens && !this.parensInOp, doubleParen = false;
        if (inParenthesis) {
            context.inParenthesis();
        }
        if (this.value.length > 1) {
            returnValue = new Expression(this.value.map(function (e) {
                return e.eval(context);
            }));
        }
        else if (this.value.length === 1) {
            if (this.value[0].parens && !this.value[0].parensInOp) {
                doubleParen = true;
            }
            returnValue = this.value[0].eval(context);
        }
        else {
            returnValue = this;
        }
        if (inParenthesis) {
            context.outOfParenthesis();
        }
        if (this.parens && this.parensInOp && !(context.isMathOn()) && !doubleParen) {
            returnValue = new Paren(returnValue);
        }
        return returnValue;
    };
    Expression.prototype.genCSS = function (context, output) {
        for (var i = 0; i < this.value.length; i++) {
            this.value[i].genCSS(context, output);
            if (i + 1 < this.value.length) {
                output.add(" ");
            }
        }
    };
    Expression.prototype.throwAwayComments = function () {
        this.value = this.value.filter(function (v) {
            return !(v instanceof Comment);
        });
    };
    module.exports = Expression;
}
,
/* less/lib/less/tree/extend */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Selector = require(240) /* ./selector */;
    var Extend = function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
        this.selector = selector;
        this.option = option;
        this.object_id = Extend.next_id++;
        this.parent_ids = [this.object_id];
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.copyVisibilityInfo(visibilityInfo);
        this.allowRoot = true;
        switch (option) {
            case "all":
                this.allowBefore = true;
                this.allowAfter = true;
                break;
            default:
                this.allowBefore = false;
                this.allowAfter = false;
                break;
        }
        this.setParent(this.selector, this);
    };
    Extend.next_id = 0;
    Extend.prototype = new Node();
    Extend.prototype.type = "Extend";
    Extend.prototype.accept = function (visitor) {
        this.selector = visitor.visit(this.selector);
    };
    Extend.prototype.eval = function (context) {
        return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
    };
    Extend.prototype.clone = function (context) {
        return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
    };
    // it concatenates (joins) all selectors in selector array
    Extend.prototype.findSelfSelectors = function (selectors) {
        var selfElements = [], i, selectorElements;
        for (i = 0; i < selectors.length; i++) {
            selectorElements = selectors[i].elements;
            // duplicate the logic in genCSS function inside the selector node.
            // future TODO - move both logics into the selector joiner visitor
            if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") {
                selectorElements[0].combinator.value = ' ';
            }
            selfElements = selfElements.concat(selectors[i].elements);
        }
        this.selfSelectors = [new Selector(selfElements)];
        this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
    };
    module.exports = Extend;
}
,
/* less/lib/less/tree/import */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Media = require(230) /* ./media */, URL = require(243) /* ./url */, Quoted = require(238) /* ./quoted */, Ruleset = require(239) /* ./ruleset */, Anonymous = require(209) /* ./anonymous */, utils = require(247) /* ../utils */, LessError = require(197) /* ../less-error */;
    //
    // CSS @import node
    //
    // The general strategy here is that we don't want to wait
    // for the parsing to be completed, before we start importing
    // the file. That's because in the context of a browser,
    // most of the time will be spent waiting for the server to respond.
    //
    // On creation, we push the import path to our import queue, though
    // `import,push`, we also pass it a callback, which it'll call once
    // the file has been fetched, and parsed.
    //
    var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) {
        this.options = options;
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.path = path;
        this.features = features;
        this.allowRoot = true;
        if (this.options.less !== undefined || this.options.inline) {
            this.css = !this.options.less || this.options.inline;
        }
        else {
            var pathValue = this.getPath();
            if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
                this.css = true;
            }
        }
        this.copyVisibilityInfo(visibilityInfo);
        this.setParent(this.features, this);
        this.setParent(this.path, this);
    };
    //
    // The actual import node doesn't return anything, when converted to CSS.
    // The reason is that it's used at the evaluation stage, so that the rules
    // it imports can be treated like any other rules.
    //
    // In `eval`, we make sure all Import nodes get evaluated, recursively, so
    // we end up with a flat structure, which can easily be imported in the parent
    // ruleset.
    //
    Import.prototype = new Node();
    Import.prototype.type = "Import";
    Import.prototype.accept = function (visitor) {
        if (this.features) {
            this.features = visitor.visit(this.features);
        }
        this.path = visitor.visit(this.path);
        if (!this.options.isPlugin && !this.options.inline && this.root) {
            this.root = visitor.visit(this.root);
        }
    };
    Import.prototype.genCSS = function (context, output) {
        if (this.css && this.path._fileInfo.reference === undefined) {
            output.add("@import ", this._fileInfo, this._index);
            this.path.genCSS(context, output);
            if (this.features) {
                output.add(" ");
                this.features.genCSS(context, output);
            }
            output.add(';');
        }
    };
    Import.prototype.getPath = function () {
        return (this.path instanceof URL) ?
            this.path.value.value : this.path.value;
    };
    Import.prototype.isVariableImport = function () {
        var path = this.path;
        if (path instanceof URL) {
            path = path.value;
        }
        if (path instanceof Quoted) {
            return path.containsVariables();
        }
        return true;
    };
    Import.prototype.evalForImport = function (context) {
        var path = this.path;
        if (path instanceof URL) {
            path = path.value;
        }
        return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
    };
    Import.prototype.evalPath = function (context) {
        var path = this.path.eval(context);
        var rootpath = this._fileInfo && this._fileInfo.rootpath;
        if (!(path instanceof URL)) {
            if (rootpath) {
                var pathValue = path.value;
                // Add the base path if the import is relative
                if (pathValue && context.isPathRelative(pathValue)) {
                    path.value = rootpath + pathValue;
                }
            }
            path.value = context.normalizePath(path.value);
        }
        return path;
    };
    Import.prototype.eval = function (context) {
        var result = this.doEval(context);
        if (this.options.reference || this.blocksVisibility()) {
            if (result.length || result.length === 0) {
                result.forEach(function (node) {
                    node.addVisibilityBlock();
                });
            }
            else {
                result.addVisibilityBlock();
            }
        }
        return result;
    };
    Import.prototype.doEval = function (context) {
        var ruleset, registry, features = this.features && this.features.eval(context);
        if (this.options.isPlugin) {
            if (this.root && this.root.eval) {
                try {
                    this.root.eval(context);
                }
                catch (e) {
                    e.message = "Plugin error during evaluation";
                    throw new LessError(e, this.root.imports, this.root.filename);
                }
            }
            registry = context.frames[0] && context.frames[0].functionRegistry;
            if (registry && this.root && this.root.functions) {
                registry.addMultiple(this.root.functions);
            }
            return [];
        }
        if (this.skip) {
            if (typeof this.skip === "function") {
                this.skip = this.skip();
            }
            if (this.skip) {
                return [];
            }
        }
        if (this.options.inline) {
            var contents = new Anonymous(this.root, 0, {
                filename: this.importedFilename,
                reference: this.path._fileInfo && this.path._fileInfo.reference
            }, true, true);
            return this.features ? new Media([contents], this.features.value) : [contents];
        }
        else if (this.css) {
            var newImport = new Import(this.evalPath(context), features, this.options, this._index);
            if (!newImport.css && this.error) {
                throw this.error;
            }
            return newImport;
        }
        else {
            ruleset = new Ruleset(null, utils.copyArray(this.root.rules));
            ruleset.evalImports(context);
            return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
        }
    };
    module.exports = Import;
}
,
/* less/lib/less/tree/index */ function _(require, module, exports) {
    var tree = Object.create(null);
    tree.Node = require(234) /* ./node */;
    tree.Color = require(214) /* ./color */;
    tree.AtRule = require(211) /* ./atrule */;
    tree.DetachedRuleset = require(220) /* ./detached-ruleset */;
    tree.Operation = require(235) /* ./operation */;
    tree.Dimension = require(221) /* ./dimension */;
    tree.Unit = require(242) /* ./unit */;
    tree.Keyword = require(229) /* ./keyword */;
    tree.Variable = require(246) /* ./variable */;
    tree.Property = require(237) /* ./property */;
    tree.Ruleset = require(239) /* ./ruleset */;
    tree.Element = require(222) /* ./element */;
    tree.Attribute = require(212) /* ./attribute */;
    tree.Combinator = require(215) /* ./combinator */;
    tree.Selector = require(240) /* ./selector */;
    tree.Quoted = require(238) /* ./quoted */;
    tree.Expression = require(223) /* ./expression */;
    tree.Declaration = require(219) /* ./declaration */;
    tree.Call = require(213) /* ./call */;
    tree.URL = require(243) /* ./url */;
    tree.Import = require(225) /* ./import */;
    tree.mixin = {
        Call: require(231) /* ./mixin-call */,
        Definition: require(232) /* ./mixin-definition */
    };
    tree.Comment = require(216) /* ./comment */;
    tree.Anonymous = require(209) /* ./anonymous */;
    tree.Value = require(244) /* ./value */;
    tree.JavaScript = require(227) /* ./javascript */;
    tree.Assignment = require(210) /* ./assignment */;
    tree.Condition = require(217) /* ./condition */;
    tree.Paren = require(236) /* ./paren */;
    tree.Media = require(230) /* ./media */;
    tree.UnicodeDescriptor = require(241) /* ./unicode-descriptor */;
    tree.Negative = require(233) /* ./negative */;
    tree.Extend = require(224) /* ./extend */;
    tree.VariableCall = require(245) /* ./variable-call */;
    module.exports = tree;
}
,
/* less/lib/less/tree/javascript */ function _(require, module, exports) {
    var JsEvalNode = require(228) /* ./js-eval-node */, Dimension = require(221) /* ./dimension */, Quoted = require(238) /* ./quoted */, Anonymous = require(209) /* ./anonymous */;
    var JavaScript = function (string, escaped, index, currentFileInfo) {
        this.escaped = escaped;
        this.expression = string;
        this._index = index;
        this._fileInfo = currentFileInfo;
    };
    JavaScript.prototype = new JsEvalNode();
    JavaScript.prototype.type = "JavaScript";
    JavaScript.prototype.eval = function (context) {
        var result = this.evaluateJavaScript(this.expression, context);
        if (typeof result === 'number') {
            return new Dimension(result);
        }
        else if (typeof result === 'string') {
            return new Quoted('"' + result + '"', result, this.escaped, this._index);
        }
        else if (Array.isArray(result)) {
            return new Anonymous(result.join(', '));
        }
        else {
            return new Anonymous(result);
        }
    };
    module.exports = JavaScript;
}
,
/* less/lib/less/tree/js-eval-node */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Variable = require(246) /* ./variable */;
    var JsEvalNode = function () {
    };
    JsEvalNode.prototype = new Node();
    JsEvalNode.prototype.evaluateJavaScript = function (expression, context) {
        var result, that = this, evalContext = {};
        if (!context.javascriptEnabled) {
            throw { message: "Inline JavaScript is not enabled. Is it set in your options?",
                filename: this.fileInfo().filename,
                index: this.getIndex() };
        }
        expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
            return that.jsify(new Variable('@' + name, that.getIndex(), that.fileInfo()).eval(context));
        });
        try {
            expression = new Function('return (' + expression + ')');
        }
        catch (e) {
            throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`",
                filename: this.fileInfo().filename,
                index: this.getIndex() };
        }
        var variables = context.frames[0].variables();
        for (var k in variables) {
            if (variables.hasOwnProperty(k)) {
                /* jshint loopfunc:true */
                evalContext[k.slice(1)] = {
                    value: variables[k].value,
                    toJS: function () {
                        return this.value.eval(context).toCSS();
                    }
                };
            }
        }
        try {
            result = expression.call(evalContext);
        }
        catch (e) {
            throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'",
                filename: this.fileInfo().filename,
                index: this.getIndex() };
        }
        return result;
    };
    JsEvalNode.prototype.jsify = function (obj) {
        if (Array.isArray(obj.value) && (obj.value.length > 1)) {
            return '[' + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + ']';
        }
        else {
            return obj.toCSS();
        }
    };
    module.exports = JsEvalNode;
}
,
/* less/lib/less/tree/keyword */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Keyword = function (value) { this.value = value; };
    Keyword.prototype = new Node();
    Keyword.prototype.type = "Keyword";
    Keyword.prototype.genCSS = function (context, output) {
        if (this.value === '%') {
            throw { type: "Syntax", message: "Invalid % without number" };
        }
        output.add(this.value);
    };
    Keyword.True = new Keyword('true');
    Keyword.False = new Keyword('false');
    module.exports = Keyword;
}
,
/* less/lib/less/tree/media */ function _(require, module, exports) {
    var Ruleset = require(239) /* ./ruleset */, Value = require(244) /* ./value */, Selector = require(240) /* ./selector */, Anonymous = require(209) /* ./anonymous */, Expression = require(223) /* ./expression */, AtRule = require(211) /* ./atrule */, utils = require(247) /* ../utils */;
    var Media = function (value, features, index, currentFileInfo, visibilityInfo) {
        this._index = index;
        this._fileInfo = currentFileInfo;
        var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
        this.features = new Value(features);
        this.rules = [new Ruleset(selectors, value)];
        this.rules[0].allowImports = true;
        this.copyVisibilityInfo(visibilityInfo);
        this.allowRoot = true;
        this.setParent(selectors, this);
        this.setParent(this.features, this);
        this.setParent(this.rules, this);
    };
    Media.prototype = new AtRule();
    Media.prototype.type = "Media";
    Media.prototype.isRulesetLike = function () { return true; };
    Media.prototype.accept = function (visitor) {
        if (this.features) {
            this.features = visitor.visit(this.features);
        }
        if (this.rules) {
            this.rules = visitor.visitArray(this.rules);
        }
    };
    Media.prototype.genCSS = function (context, output) {
        output.add('@media ', this._fileInfo, this._index);
        this.features.genCSS(context, output);
        this.outputRuleset(context, output, this.rules);
    };
    Media.prototype.eval = function (context) {
        if (!context.mediaBlocks) {
            context.mediaBlocks = [];
            context.mediaPath = [];
        }
        var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
        if (this.debugInfo) {
            this.rules[0].debugInfo = this.debugInfo;
            media.debugInfo = this.debugInfo;
        }
        media.features = this.features.eval(context);
        context.mediaPath.push(media);
        context.mediaBlocks.push(media);
        this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
        context.frames.unshift(this.rules[0]);
        media.rules = [this.rules[0].eval(context)];
        context.frames.shift();
        context.mediaPath.pop();
        return context.mediaPath.length === 0 ? media.evalTop(context) :
            media.evalNested(context);
    };
    Media.prototype.evalTop = function (context) {
        var result = this;
        // Render all dependent Media blocks.
        if (context.mediaBlocks.length > 1) {
            var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
            result = new Ruleset(selectors, context.mediaBlocks);
            result.multiMedia = true;
            result.copyVisibilityInfo(this.visibilityInfo());
            this.setParent(result, this);
        }
        delete context.mediaBlocks;
        delete context.mediaPath;
        return result;
    };
    Media.prototype.evalNested = function (context) {
        var i, value, path = context.mediaPath.concat([this]);
        // Extract the media-query conditions separated with `,` (OR).
        for (i = 0; i < path.length; i++) {
            value = path[i].features instanceof Value ?
                path[i].features.value : path[i].features;
            path[i] = Array.isArray(value) ? value : [value];
        }
        // Trace all permutations to generate the resulting media-query.
        //
        // (a, b and c) with nested (d, e) ->
        //    a and d
        //    a and e
        //    b and c and d
        //    b and c and e
        this.features = new Value(this.permute(path).map(function (path) {
            path = path.map(function (fragment) {
                return fragment.toCSS ? fragment : new Anonymous(fragment);
            });
            for (i = path.length - 1; i > 0; i--) {
                path.splice(i, 0, new Anonymous("and"));
            }
            return new Expression(path);
        }));
        this.setParent(this.features, this);
        // Fake a tree-node that doesn't output anything.
        return new Ruleset([], []);
    };
    Media.prototype.permute = function (arr) {
        if (arr.length === 0) {
            return [];
        }
        else if (arr.length === 1) {
            return arr[0];
        }
        else {
            var result = [];
            var rest = this.permute(arr.slice(1));
            for (var i = 0; i < rest.length; i++) {
                for (var j = 0; j < arr[0].length; j++) {
                    result.push([arr[0][j]].concat(rest[i]));
                }
            }
            return result;
        }
    };
    Media.prototype.bubbleSelectors = function (selectors) {
        if (!selectors) {
            return;
        }
        this.rules = [new Ruleset(utils.copyArray(selectors), [this.rules[0]])];
        this.setParent(this.rules, this);
    };
    module.exports = Media;
}
,
/* less/lib/less/tree/mixin-call */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Selector = require(240) /* ./selector */, MixinDefinition = require(232) /* ./mixin-definition */, defaultFunc = require(185) /* ../functions/default */;
    var MixinCall = function (elements, args, index, currentFileInfo, important) {
        this.selector = new Selector(elements);
        this.arguments = args || [];
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.important = important;
        this.allowRoot = true;
        this.setParent(this.selector, this);
    };
    MixinCall.prototype = new Node();
    MixinCall.prototype.type = "MixinCall";
    MixinCall.prototype.accept = function (visitor) {
        if (this.selector) {
            this.selector = visitor.visit(this.selector);
        }
        if (this.arguments.length) {
            this.arguments = visitor.visitArray(this.arguments);
        }
    };
    MixinCall.prototype.eval = function (context) {
        var mixins, mixin, mixinPath, args = [], arg, argValue, rules = [], match = false, i, m, f, isRecursive, isOneFound, candidates = [], candidate, conditionResult = [], defaultResult, defFalseEitherCase = -1, defNone = 0, defTrue = 1, defFalse = 2, count, originalRuleset, noArgumentsFilter;
        function calcDefGroup(mixin, mixinPath) {
            var f, p, namespace;
            for (f = 0; f < 2; f++) {
                conditionResult[f] = true;
                defaultFunc.value(f);
                for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
                    namespace = mixinPath[p];
                    if (namespace.matchCondition) {
                        conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
                    }
                }
                if (mixin.matchCondition) {
                    conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
                }
            }
            if (conditionResult[0] || conditionResult[1]) {
                if (conditionResult[0] != conditionResult[1]) {
                    return conditionResult[1] ?
                        defTrue : defFalse;
                }
                return defNone;
            }
            return defFalseEitherCase;
        }
        for (i = 0; i < this.arguments.length; i++) {
            arg = this.arguments[i];
            argValue = arg.value.eval(context);
            if (arg.expand && Array.isArray(argValue.value)) {
                argValue = argValue.value;
                for (m = 0; m < argValue.length; m++) {
                    args.push({ value: argValue[m] });
                }
            }
            else {
                args.push({ name: arg.name, value: argValue });
            }
        }
        noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
        for (i = 0; i < context.frames.length; i++) {
            if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
                isOneFound = true;
                // To make `default()` function independent of definition order we have two "subpasses" here.
                // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
                // and build candidate list with corresponding flags. Then, when we know all possible matches,
                // we make a final decision.
                for (m = 0; m < mixins.length; m++) {
                    mixin = mixins[m].rule;
                    mixinPath = mixins[m].path;
                    isRecursive = false;
                    for (f = 0; f < context.frames.length; f++) {
                        if ((!(mixin instanceof MixinDefinition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
                            isRecursive = true;
                            break;
                        }
                    }
                    if (isRecursive) {
                        continue;
                    }
                    if (mixin.matchArgs(args, context)) {
                        candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
                        if (candidate.group !== defFalseEitherCase) {
                            candidates.push(candidate);
                        }
                        match = true;
                    }
                }
                defaultFunc.reset();
                count = [0, 0, 0];
                for (m = 0; m < candidates.length; m++) {
                    count[candidates[m].group]++;
                }
                if (count[defNone] > 0) {
                    defaultResult = defFalse;
                }
                else {
                    defaultResult = defTrue;
                    if ((count[defTrue] + count[defFalse]) > 1) {
                        throw { type: 'Runtime',
                            message: 'Ambiguous use of `default()` found when matching for `' + this.format(args) + '`',
                            index: this.getIndex(), filename: this.fileInfo().filename };
                    }
                }
                for (m = 0; m < candidates.length; m++) {
                    candidate = candidates[m].group;
                    if ((candidate === defNone) || (candidate === defaultResult)) {
                        try {
                            mixin = candidates[m].mixin;
                            if (!(mixin instanceof MixinDefinition)) {
                                originalRuleset = mixin.originalRuleset || mixin;
                                mixin = new MixinDefinition("", [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
                                mixin.originalRuleset = originalRuleset;
                            }
                            var newRules = mixin.evalCall(context, args, this.important).rules;
                            this._setVisibilityToReplacement(newRules);
                            Array.prototype.push.apply(rules, newRules);
                        }
                        catch (e) {
                            throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
                        }
                    }
                }
                if (match) {
                    return rules;
                }
            }
        }
        if (isOneFound) {
            throw { type: 'Runtime',
                message: 'No matching definition was found for `' + this.format(args) + '`',
                index: this.getIndex(), filename: this.fileInfo().filename };
        }
        else {
            throw { type: 'Name',
                message: this.selector.toCSS().trim() + " is undefined",
                index: this.getIndex(), filename: this.fileInfo().filename };
        }
    };
    MixinCall.prototype._setVisibilityToReplacement = function (replacement) {
        var i, rule;
        if (this.blocksVisibility()) {
            for (i = 0; i < replacement.length; i++) {
                rule = replacement[i];
                rule.addVisibilityBlock();
            }
        }
    };
    MixinCall.prototype.format = function (args) {
        return this.selector.toCSS().trim() + '(' +
            (args ? args.map(function (a) {
                var argValue = "";
                if (a.name) {
                    argValue += a.name + ":";
                }
                if (a.value.toCSS) {
                    argValue += a.value.toCSS();
                }
                else {
                    argValue += "???";
                }
                return argValue;
            }).join(', ') : "") + ")";
    };
    module.exports = MixinCall;
}
,
/* less/lib/less/tree/mixin-definition */ function _(require, module, exports) {
    var Selector = require(240) /* ./selector */, Element = require(222) /* ./element */, Ruleset = require(239) /* ./ruleset */, Declaration = require(219) /* ./declaration */, Expression = require(223) /* ./expression */, contexts = require(173) /* ../contexts */, utils = require(247) /* ../utils */;
    var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) {
        this.name = name;
        this.selectors = [new Selector([new Element(null, name, this._index, this._fileInfo)])];
        this.params = params;
        this.condition = condition;
        this.variadic = variadic;
        this.arity = params.length;
        this.rules = rules;
        this._lookups = {};
        var optionalParameters = [];
        this.required = params.reduce(function (count, p) {
            if (!p.name || (p.name && !p.value)) {
                return count + 1;
            }
            else {
                optionalParameters.push(p.name);
                return count;
            }
        }, 0);
        this.optionalParameters = optionalParameters;
        this.frames = frames;
        this.copyVisibilityInfo(visibilityInfo);
        this.allowRoot = true;
    };
    Definition.prototype = new Ruleset();
    Definition.prototype.type = "MixinDefinition";
    Definition.prototype.evalFirst = true;
    Definition.prototype.accept = function (visitor) {
        if (this.params && this.params.length) {
            this.params = visitor.visitArray(this.params);
        }
        this.rules = visitor.visitArray(this.rules);
        if (this.condition) {
            this.condition = visitor.visit(this.condition);
        }
    };
    Definition.prototype.evalParams = function (context, mixinEnv, args, evaldArguments) {
        /* jshint boss:true */
        var frame = new Ruleset(null, null), varargs, arg, params = utils.copyArray(this.params), i, j, val, name, isNamedFound, argIndex, argsLength = 0;
        if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
            frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
        }
        mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
        if (args) {
            args = utils.copyArray(args);
            argsLength = args.length;
            for (i = 0; i < argsLength; i++) {
                arg = args[i];
                if (name = (arg && arg.name)) {
                    isNamedFound = false;
                    for (j = 0; j < params.length; j++) {
                        if (!evaldArguments[j] && name === params[j].name) {
                            evaldArguments[j] = arg.value.eval(context);
                            frame.prependRule(new Declaration(name, arg.value.eval(context)));
                            isNamedFound = true;
                            break;
                        }
                    }
                    if (isNamedFound) {
                        args.splice(i, 1);
                        i--;
                        continue;
                    }
                    else {
                        throw { type: 'Runtime', message: "Named argument for " + this.name +
                                ' ' + args[i].name + ' not found' };
                    }
                }
            }
        }
        argIndex = 0;
        for (i = 0; i < params.length; i++) {
            if (evaldArguments[i]) {
                continue;
            }
            arg = args && args[argIndex];
            if (name = params[i].name) {
                if (params[i].variadic) {
                    varargs = [];
                    for (j = argIndex; j < argsLength; j++) {
                        varargs.push(args[j].value.eval(context));
                    }
                    frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
                }
                else {
                    val = arg && arg.value;
                    if (val) {
                        val = val.eval(context);
                    }
                    else if (params[i].value) {
                        val = params[i].value.eval(mixinEnv);
                        frame.resetCache();
                    }
                    else {
                        throw { type: 'Runtime', message: "wrong number of arguments for " + this.name +
                                ' (' + argsLength + ' for ' + this.arity + ')' };
                    }
                    frame.prependRule(new Declaration(name, val));
                    evaldArguments[i] = val;
                }
            }
            if (params[i].variadic && args) {
                for (j = argIndex; j < argsLength; j++) {
                    evaldArguments[j] = args[j].value.eval(context);
                }
            }
            argIndex++;
        }
        return frame;
    };
    Definition.prototype.makeImportant = function () {
        var rules = !this.rules ? this.rules : this.rules.map(function (r) {
            if (r.makeImportant) {
                return r.makeImportant(true);
            }
            else {
                return r;
            }
        });
        var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
        return result;
    };
    Definition.prototype.eval = function (context) {
        return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || utils.copyArray(context.frames));
    };
    Definition.prototype.evalCall = function (context, args, important) {
        var _arguments = [], mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames, frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments), rules, ruleset;
        frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
        rules = utils.copyArray(this.rules);
        ruleset = new Ruleset(null, rules);
        ruleset.originalRuleset = this;
        ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
        if (important) {
            ruleset = ruleset.makeImportant();
        }
        return ruleset;
    };
    Definition.prototype.matchCondition = function (args, context) {
        if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context, /* the parameter variables */ new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
            .concat(this.frames || []) // the parent namespace/mixin frames
            .concat(context.frames)))) { // the current environment frames
            return false;
        }
        return true;
    };
    Definition.prototype.matchArgs = function (args, context) {
        var allArgsCnt = (args && args.length) || 0, len, optionalParameters = this.optionalParameters;
        var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
            if (optionalParameters.indexOf(p.name) < 0) {
                return count + 1;
            }
            else {
                return count;
            }
        }, 0);
        if (!this.variadic) {
            if (requiredArgsCnt < this.required) {
                return false;
            }
            if (allArgsCnt > this.params.length) {
                return false;
            }
        }
        else {
            if (requiredArgsCnt < (this.required - 1)) {
                return false;
            }
        }
        // check patterns
        len = Math.min(requiredArgsCnt, this.arity);
        for (var i = 0; i < len; i++) {
            if (!this.params[i].name && !this.params[i].variadic) {
                if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
                    return false;
                }
            }
        }
        return true;
    };
    module.exports = Definition;
}
,
/* less/lib/less/tree/negative */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Operation = require(235) /* ./operation */, Dimension = require(221) /* ./dimension */;
    var Negative = function (node) {
        this.value = node;
    };
    Negative.prototype = new Node();
    Negative.prototype.type = "Negative";
    Negative.prototype.genCSS = function (context, output) {
        output.add('-');
        this.value.genCSS(context, output);
    };
    Negative.prototype.eval = function (context) {
        if (context.isMathOn()) {
            return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
        }
        return new Negative(this.value.eval(context));
    };
    module.exports = Negative;
}
,
/* less/lib/less/tree/node */ function _(require, module, exports) {
    var Node = function () {
        this.parent = null;
        this.visibilityBlocks = undefined;
        this.nodeVisible = undefined;
        this.rootNode = null;
        this.parsed = null;
        var self = this;
        Object.defineProperty(this, "currentFileInfo", {
            get: function () { return self.fileInfo(); }
        });
        Object.defineProperty(this, "index", {
            get: function () { return self.getIndex(); }
        });
    };
    Node.prototype.setParent = function (nodes, parent) {
        function set(node) {
            if (node && node instanceof Node) {
                node.parent = parent;
            }
        }
        if (Array.isArray(nodes)) {
            nodes.forEach(set);
        }
        else {
            set(nodes);
        }
    };
    Node.prototype.getIndex = function () {
        return this._index || (this.parent && this.parent.getIndex()) || 0;
    };
    Node.prototype.fileInfo = function () {
        return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
    };
    Node.prototype.isRulesetLike = function () { return false; };
    Node.prototype.toCSS = function (context) {
        var strs = [];
        this.genCSS(context, {
            add: function (chunk, fileInfo, index) {
                strs.push(chunk);
            },
            isEmpty: function () {
                return strs.length === 0;
            }
        });
        return strs.join('');
    };
    Node.prototype.genCSS = function (context, output) {
        output.add(this.value);
    };
    Node.prototype.accept = function (visitor) {
        this.value = visitor.visit(this.value);
    };
    Node.prototype.eval = function () { return this; };
    Node.prototype._operate = function (context, op, a, b) {
        switch (op) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            case '/': return a / b;
        }
    };
    Node.prototype.fround = function (context, value) {
        var precision = context && context.numPrecision;
        // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
        return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
    };
    Node.compare = function (a, b) {
        /* returns:
         -1: a < b
         0: a = b
         1: a > b
         and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
        if ((a.compare) &&
            // for "symmetric results" force toCSS-based comparison
            // of Quoted or Anonymous if either value is one of those
            !(b.type === "Quoted" || b.type === "Anonymous")) {
            return a.compare(b);
        }
        else if (b.compare) {
            return -b.compare(a);
        }
        else if (a.type !== b.type) {
            return undefined;
        }
        a = a.value;
        b = b.value;
        if (!Array.isArray(a)) {
            return a === b ? 0 : undefined;
        }
        if (a.length !== b.length) {
            return undefined;
        }
        for (var i = 0; i < a.length; i++) {
            if (Node.compare(a[i], b[i]) !== 0) {
                return undefined;
            }
        }
        return 0;
    };
    Node.numericCompare = function (a, b) {
        return a < b ? -1
            : a === b ? 0
                : a > b ? 1 : undefined;
    };
    // Returns true if this node represents root of ast imported by reference
    Node.prototype.blocksVisibility = function () {
        if (this.visibilityBlocks == null) {
            this.visibilityBlocks = 0;
        }
        return this.visibilityBlocks !== 0;
    };
    Node.prototype.addVisibilityBlock = function () {
        if (this.visibilityBlocks == null) {
            this.visibilityBlocks = 0;
        }
        this.visibilityBlocks = this.visibilityBlocks + 1;
    };
    Node.prototype.removeVisibilityBlock = function () {
        if (this.visibilityBlocks == null) {
            this.visibilityBlocks = 0;
        }
        this.visibilityBlocks = this.visibilityBlocks - 1;
    };
    // Turns on node visibility - if called node will be shown in output regardless
    // of whether it comes from import by reference or not
    Node.prototype.ensureVisibility = function () {
        this.nodeVisible = true;
    };
    // Turns off node visibility - if called node will NOT be shown in output regardless
    // of whether it comes from import by reference or not
    Node.prototype.ensureInvisibility = function () {
        this.nodeVisible = false;
    };
    // return values:
    // false - the node must not be visible
    // true - the node must be visible
    // undefined or null - the node has the same visibility as its parent
    Node.prototype.isVisible = function () {
        return this.nodeVisible;
    };
    Node.prototype.visibilityInfo = function () {
        return {
            visibilityBlocks: this.visibilityBlocks,
            nodeVisible: this.nodeVisible
        };
    };
    Node.prototype.copyVisibilityInfo = function (info) {
        if (!info) {
            return;
        }
        this.visibilityBlocks = info.visibilityBlocks;
        this.nodeVisible = info.nodeVisible;
    };
    module.exports = Node;
}
,
/* less/lib/less/tree/operation */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Color = require(214) /* ./color */, Dimension = require(221) /* ./dimension */;
    var Operation = function (op, operands, isSpaced) {
        this.op = op.trim();
        this.operands = operands;
        this.isSpaced = isSpaced;
    };
    Operation.prototype = new Node();
    Operation.prototype.type = "Operation";
    Operation.prototype.accept = function (visitor) {
        this.operands = visitor.visit(this.operands);
    };
    Operation.prototype.eval = function (context) {
        var a = this.operands[0].eval(context), b = this.operands[1].eval(context);
        if (context.isMathOn()) {
            if (a instanceof Dimension && b instanceof Color) {
                a = a.toColor();
            }
            if (b instanceof Dimension && a instanceof Color) {
                b = b.toColor();
            }
            if (!a.operate) {
                throw { type: "Operation",
                    message: "Operation on an invalid type" };
            }
            return a.operate(context, this.op, b);
        }
        else {
            return new Operation(this.op, [a, b], this.isSpaced);
        }
    };
    Operation.prototype.genCSS = function (context, output) {
        this.operands[0].genCSS(context, output);
        if (this.isSpaced) {
            output.add(" ");
        }
        output.add(this.op);
        if (this.isSpaced) {
            output.add(" ");
        }
        this.operands[1].genCSS(context, output);
    };
    module.exports = Operation;
}
,
/* less/lib/less/tree/paren */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Paren = function (node) {
        this.value = node;
    };
    Paren.prototype = new Node();
    Paren.prototype.type = "Paren";
    Paren.prototype.genCSS = function (context, output) {
        output.add('(');
        this.value.genCSS(context, output);
        output.add(')');
    };
    Paren.prototype.eval = function (context) {
        return new Paren(this.value.eval(context));
    };
    module.exports = Paren;
}
,
/* less/lib/less/tree/property */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Declaration = require(219) /* ./declaration */;
    var Property = function (name, index, currentFileInfo) {
        this.name = name;
        this._index = index;
        this._fileInfo = currentFileInfo;
    };
    Property.prototype = new Node();
    Property.prototype.type = "Property";
    Property.prototype.eval = function (context) {
        var property, name = this.name;
        // TODO: shorten this reference
        var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
        if (this.evaluating) {
            throw { type: 'Name',
                message: "Recursive property reference for " + name,
                filename: this.fileInfo().filename,
                index: this.getIndex() };
        }
        this.evaluating = true;
        property = this.find(context.frames, function (frame) {
            var v, vArr = frame.property(name);
            if (vArr) {
                for (var i = 0; i < vArr.length; i++) {
                    v = vArr[i];
                    vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
                }
                mergeRules(vArr);
                v = vArr[vArr.length - 1];
                if (v.important) {
                    var importantScope = context.importantScope[context.importantScope.length - 1];
                    importantScope.important = v.important;
                }
                v = v.value.eval(context);
                return v;
            }
        });
        if (property) {
            this.evaluating = false;
            return property;
        }
        else {
            throw { type: 'Name',
                message: "Property '" + name + "' is undefined",
                filename: this.currentFileInfo.filename,
                index: this.index };
        }
    };
    Property.prototype.find = function (obj, fun) {
        for (var i = 0, r; i < obj.length; i++) {
            r = fun.call(obj, obj[i]);
            if (r) {
                return r;
            }
        }
        return null;
    };
    module.exports = Property;
}
,
/* less/lib/less/tree/quoted */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Variable = require(246) /* ./variable */, Property = require(237) /* ./property */;
    var Quoted = function (str, content, escaped, index, currentFileInfo) {
        this.escaped = (escaped == null) ? true : escaped;
        this.value = content || '';
        this.quote = str.charAt(0);
        this._index = index;
        this._fileInfo = currentFileInfo;
    };
    Quoted.prototype = new Node();
    Quoted.prototype.type = "Quoted";
    Quoted.prototype.genCSS = function (context, output) {
        if (!this.escaped) {
            output.add(this.quote, this.fileInfo(), this.getIndex());
        }
        output.add(this.value);
        if (!this.escaped) {
            output.add(this.quote);
        }
    };
    Quoted.prototype.containsVariables = function () {
        return this.value.match(/@\{([\w-]+)\}/);
    };
    Quoted.prototype.eval = function (context) {
        var that = this, value = this.value;
        var variableReplacement = function (_, name) {
            var v = new Variable('@' + name, that.getIndex(), that.fileInfo()).eval(context, true);
            return (v instanceof Quoted) ? v.value : v.toCSS();
        };
        var propertyReplacement = function (_, name) {
            var v = new Property('$' + name, that.getIndex(), that.fileInfo()).eval(context, true);
            return (v instanceof Quoted) ? v.value : v.toCSS();
        };
        function iterativeReplace(value, regexp, replacementFnc) {
            var evaluatedValue = value;
            do {
                value = evaluatedValue;
                evaluatedValue = value.replace(regexp, replacementFnc);
            } while (value !== evaluatedValue);
            return evaluatedValue;
        }
        value = iterativeReplace(value, /@\{([\w-]+)\}/g, variableReplacement);
        value = iterativeReplace(value, /\$\{([\w-]+)\}/g, propertyReplacement);
        return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
    };
    Quoted.prototype.compare = function (other) {
        // when comparing quoted strings allow the quote to differ
        if (other.type === "Quoted" && !this.escaped && !other.escaped) {
            return Node.numericCompare(this.value, other.value);
        }
        else {
            return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
        }
    };
    module.exports = Quoted;
}
,
/* less/lib/less/tree/ruleset */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Declaration = require(219) /* ./declaration */, Keyword = require(229) /* ./keyword */, Comment = require(216) /* ./comment */, Paren = require(236) /* ./paren */, Selector = require(240) /* ./selector */, Element = require(222) /* ./element */, Anonymous = require(209) /* ./anonymous */, contexts = require(173) /* ../contexts */, globalFunctionRegistry = require(187) /* ../functions/function-registry */, defaultFunc = require(185) /* ../functions/default */, getDebugInfo = require(218) /* ./debug-info */, utils = require(247) /* ../utils */;
    var Ruleset = function (selectors, rules, strictImports, visibilityInfo) {
        this.selectors = selectors;
        this.rules = rules;
        this._lookups = {};
        this._variables = null;
        this._properties = null;
        this.strictImports = strictImports;
        this.copyVisibilityInfo(visibilityInfo);
        this.allowRoot = true;
        this.setParent(this.selectors, this);
        this.setParent(this.rules, this);
    };
    Ruleset.prototype = new Node();
    Ruleset.prototype.type = "Ruleset";
    Ruleset.prototype.isRuleset = true;
    Ruleset.prototype.isRulesetLike = function () { return true; };
    Ruleset.prototype.accept = function (visitor) {
        if (this.paths) {
            this.paths = visitor.visitArray(this.paths, true);
        }
        else if (this.selectors) {
            this.selectors = visitor.visitArray(this.selectors);
        }
        if (this.rules && this.rules.length) {
            this.rules = visitor.visitArray(this.rules);
        }
    };
    Ruleset.prototype.eval = function (context) {
        var thisSelectors = this.selectors, selectors, selCnt, selector, i, hasOnePassingSelector = false;
        if (thisSelectors && (selCnt = thisSelectors.length)) {
            selectors = new Array(selCnt);
            defaultFunc.error({
                type: "Syntax",
                message: "it is currently only allowed in parametric mixin guards,"
            });
            for (i = 0; i < selCnt; i++) {
                selector = thisSelectors[i].eval(context);
                selectors[i] = selector;
                if (selector.evaldCondition) {
                    hasOnePassingSelector = true;
                }
            }
            defaultFunc.reset();
        }
        else {
            hasOnePassingSelector = true;
        }
        var rules = this.rules ? utils.copyArray(this.rules) : null, ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo()), rule, subRule;
        ruleset.originalRuleset = this;
        ruleset.root = this.root;
        ruleset.firstRoot = this.firstRoot;
        ruleset.allowImports = this.allowImports;
        if (this.debugInfo) {
            ruleset.debugInfo = this.debugInfo;
        }
        if (!hasOnePassingSelector) {
            rules.length = 0;
        }
        // inherit a function registry from the frames stack when possible;
        // otherwise from the global registry
        ruleset.functionRegistry = (function (frames) {
            var i = 0, n = frames.length, found;
            for (; i !== n; ++i) {
                found = frames[i].functionRegistry;
                if (found) {
                    return found;
                }
            }
            return globalFunctionRegistry;
        }(context.frames)).inherit();
        // push the current ruleset to the frames stack
        var ctxFrames = context.frames;
        ctxFrames.unshift(ruleset);
        // currrent selectors
        var ctxSelectors = context.selectors;
        if (!ctxSelectors) {
            context.selectors = ctxSelectors = [];
        }
        ctxSelectors.unshift(this.selectors);
        // Evaluate imports
        if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
            ruleset.evalImports(context);
        }
        // Store the frames around mixin definitions,
        // so they can be evaluated like closures when the time comes.
        var rsRules = ruleset.rules;
        for (i = 0; (rule = rsRules[i]); i++) {
            if (rule.evalFirst) {
                rsRules[i] = rule.eval(context);
            }
        }
        var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
        // Evaluate mixin calls.
        for (i = 0; (rule = rsRules[i]); i++) {
            if (rule.type === "MixinCall") {
                /* jshint loopfunc:true */
                rules = rule.eval(context).filter(function (r) {
                    if ((r instanceof Declaration) && r.variable) {
                        // do not pollute the scope if the variable is
                        // already there. consider returning false here
                        // but we need a way to "return" variable from mixins
                        return !(ruleset.variable(r.name));
                    }
                    return true;
                });
                rsRules.splice.apply(rsRules, [i, 1].concat(rules));
                i += rules.length - 1;
                ruleset.resetCache();
            }
            else if (rule.type === "VariableCall") {
                /* jshint loopfunc:true */
                rules = rule.eval(context).rules.filter(function (r) {
                    if ((r instanceof Declaration) && r.variable) {
                        // do not pollute the scope at all
                        return false;
                    }
                    return true;
                });
                rsRules.splice.apply(rsRules, [i, 1].concat(rules));
                i += rules.length - 1;
                ruleset.resetCache();
            }
        }
        // Evaluate everything else
        for (i = 0; (rule = rsRules[i]); i++) {
            if (!rule.evalFirst) {
                rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
            }
        }
        // Evaluate everything else
        for (i = 0; (rule = rsRules[i]); i++) {
            // for rulesets, check if it is a css guard and can be removed
            if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
                // check if it can be folded in (e.g. & where)
                if (rule.selectors[0].isJustParentSelector()) {
                    rsRules.splice(i--, 1);
                    for (var j = 0; (subRule = rule.rules[j]); j++) {
                        if (subRule instanceof Node) {
                            subRule.copyVisibilityInfo(rule.visibilityInfo());
                            if (!(subRule instanceof Declaration) || !subRule.variable) {
                                rsRules.splice(++i, 0, subRule);
                            }
                        }
                    }
                }
            }
        }
        // Pop the stack
        ctxFrames.shift();
        ctxSelectors.shift();
        if (context.mediaBlocks) {
            for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
                context.mediaBlocks[i].bubbleSelectors(selectors);
            }
        }
        return ruleset;
    };
    Ruleset.prototype.evalImports = function (context) {
        var rules = this.rules, i, importRules;
        if (!rules) {
            return;
        }
        for (i = 0; i < rules.length; i++) {
            if (rules[i].type === "Import") {
                importRules = rules[i].eval(context);
                if (importRules && (importRules.length || importRules.length === 0)) {
                    rules.splice.apply(rules, [i, 1].concat(importRules));
                    i += importRules.length - 1;
                }
                else {
                    rules.splice(i, 1, importRules);
                }
                this.resetCache();
            }
        }
    };
    Ruleset.prototype.makeImportant = function () {
        var result = new Ruleset(this.selectors, this.rules.map(function (r) {
            if (r.makeImportant) {
                return r.makeImportant();
            }
            else {
                return r;
            }
        }), this.strictImports, this.visibilityInfo());
        return result;
    };
    Ruleset.prototype.matchArgs = function (args) {
        return !args || args.length === 0;
    };
    // lets you call a css selector with a guard
    Ruleset.prototype.matchCondition = function (args, context) {
        var lastSelector = this.selectors[this.selectors.length - 1];
        if (!lastSelector.evaldCondition) {
            return false;
        }
        if (lastSelector.condition &&
            !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
            return false;
        }
        return true;
    };
    Ruleset.prototype.resetCache = function () {
        this._rulesets = null;
        this._variables = null;
        this._properties = null;
        this._lookups = {};
    };
    Ruleset.prototype.variables = function () {
        if (!this._variables) {
            this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
                if (r instanceof Declaration && r.variable === true) {
                    hash[r.name] = r;
                }
                // when evaluating variables in an import statement, imports have not been eval'd
                // so we need to go inside import statements.
                // guard against root being a string (in the case of inlined less)
                if (r.type === "Import" && r.root && r.root.variables) {
                    var vars = r.root.variables();
                    for (var name in vars) {
                        if (vars.hasOwnProperty(name)) {
                            hash[name] = vars[name];
                        }
                    }
                }
                return hash;
            }, {});
        }
        return this._variables;
    };
    Ruleset.prototype.properties = function () {
        if (!this._properties) {
            this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
                if (r instanceof Declaration && r.variable !== true) {
                    var name = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
                        r.name[0].value : r.name;
                    // Properties don't overwrite as they can merge
                    if (!hash['$' + name]) {
                        hash['$' + name] = [r];
                    }
                    else {
                        hash['$' + name].push(r);
                    }
                }
                return hash;
            }, {});
        }
        return this._properties;
    };
    Ruleset.prototype.variable = function (name) {
        var decl = this.variables()[name];
        if (decl) {
            return this.parseValue(decl);
        }
    };
    Ruleset.prototype.property = function (name) {
        var decl = this.properties()[name];
        if (decl) {
            return this.parseValue(decl);
        }
    };
    Ruleset.prototype.parseValue = function (toParse) {
        var self = this;
        function transformDeclaration(decl) {
            if (decl.value instanceof Anonymous && !decl.parsed) {
                this.parse.parseNode(decl.value.value, ["value", "important"], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
                    if (err) {
                        decl.parsed = true;
                    }
                    if (result) {
                        decl.value = result[0];
                        decl.important = result[1] || '';
                        decl.parsed = true;
                    }
                });
                return decl;
            }
            else {
                return decl;
            }
        }
        if (!Array.isArray(toParse)) {
            return transformDeclaration.call(self, toParse);
        }
        else {
            var nodes = [];
            toParse.forEach(function (n) {
                nodes.push(transformDeclaration.call(self, n));
            });
            return nodes;
        }
    };
    Ruleset.prototype.rulesets = function () {
        if (!this.rules) {
            return [];
        }
        var filtRules = [], rules = this.rules, i, rule;
        for (i = 0; (rule = rules[i]); i++) {
            if (rule.isRuleset) {
                filtRules.push(rule);
            }
        }
        return filtRules;
    };
    Ruleset.prototype.prependRule = function (rule) {
        var rules = this.rules;
        if (rules) {
            rules.unshift(rule);
        }
        else {
            this.rules = [rule];
        }
        this.setParent(rule, this);
    };
    Ruleset.prototype.find = function (selector, self, filter) {
        self = self || this;
        var rules = [], match, foundMixins, key = selector.toCSS();
        if (key in this._lookups) {
            return this._lookups[key];
        }
        this.rulesets().forEach(function (rule) {
            if (rule !== self) {
                for (var j = 0; j < rule.selectors.length; j++) {
                    match = selector.match(rule.selectors[j]);
                    if (match) {
                        if (selector.elements.length > match) {
                            if (!filter || filter(rule)) {
                                foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
                                for (var i = 0; i < foundMixins.length; ++i) {
                                    foundMixins[i].path.push(rule);
                                }
                                Array.prototype.push.apply(rules, foundMixins);
                            }
                        }
                        else {
                            rules.push({ rule: rule, path: [] });
                        }
                        break;
                    }
                }
            }
        });
        this._lookups[key] = rules;
        return rules;
    };
    Ruleset.prototype.genCSS = function (context, output) {
        var i, j, charsetRuleNodes = [], ruleNodes = [], debugInfo, // Line number debugging
        rule, path;
        context.tabLevel = (context.tabLevel || 0);
        if (!this.root) {
            context.tabLevel++;
        }
        var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join("  "), tabSetStr = context.compress ? '' : Array(context.tabLevel).join("  "), sep;
        var charsetNodeIndex = 0;
        var importNodeIndex = 0;
        for (i = 0; (rule = this.rules[i]); i++) {
            if (rule instanceof Comment) {
                if (importNodeIndex === i) {
                    importNodeIndex++;
                }
                ruleNodes.push(rule);
            }
            else if (rule.isCharset && rule.isCharset()) {
                ruleNodes.splice(charsetNodeIndex, 0, rule);
                charsetNodeIndex++;
                importNodeIndex++;
            }
            else if (rule.type === "Import") {
                ruleNodes.splice(importNodeIndex, 0, rule);
                importNodeIndex++;
            }
            else {
                ruleNodes.push(rule);
            }
        }
        ruleNodes = charsetRuleNodes.concat(ruleNodes);
        // If this is the root node, we don't render
        // a selector, or {}.
        if (!this.root) {
            debugInfo = getDebugInfo(context, this, tabSetStr);
            if (debugInfo) {
                output.add(debugInfo);
                output.add(tabSetStr);
            }
            var paths = this.paths, pathCnt = paths.length, pathSubCnt;
            sep = context.compress ? ',' : (',\n' + tabSetStr);
            for (i = 0; i < pathCnt; i++) {
                path = paths[i];
                if (!(pathSubCnt = path.length)) {
                    continue;
                }
                if (i > 0) {
                    output.add(sep);
                }
                context.firstSelector = true;
                path[0].genCSS(context, output);
                context.firstSelector = false;
                for (j = 1; j < pathSubCnt; j++) {
                    path[j].genCSS(context, output);
                }
            }
            output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
        }
        // Compile rules and rulesets
        for (i = 0; (rule = ruleNodes[i]); i++) {
            if (i + 1 === ruleNodes.length) {
                context.lastRule = true;
            }
            var currentLastRule = context.lastRule;
            if (rule.isRulesetLike(rule)) {
                context.lastRule = false;
            }
            if (rule.genCSS) {
                rule.genCSS(context, output);
            }
            else if (rule.value) {
                output.add(rule.value.toString());
            }
            context.lastRule = currentLastRule;
            if (!context.lastRule && rule.isVisible()) {
                output.add(context.compress ? '' : ('\n' + tabRuleStr));
            }
            else {
                context.lastRule = false;
            }
        }
        if (!this.root) {
            output.add((context.compress ? '}' : '\n' + tabSetStr + '}'));
            context.tabLevel--;
        }
        if (!output.isEmpty() && !context.compress && this.firstRoot) {
            output.add('\n');
        }
    };
    Ruleset.prototype.joinSelectors = function (paths, context, selectors) {
        for (var s = 0; s < selectors.length; s++) {
            this.joinSelector(paths, context, selectors[s]);
        }
    };
    Ruleset.prototype.joinSelector = function (paths, context, selector) {
        function createParenthesis(elementsToPak, originalElement) {
            var replacementParen, j;
            if (elementsToPak.length === 0) {
                replacementParen = new Paren(elementsToPak[0]);
            }
            else {
                var insideParent = new Array(elementsToPak.length);
                for (j = 0; j < elementsToPak.length; j++) {
                    insideParent[j] = new Element(null, elementsToPak[j], originalElement._index, originalElement._fileInfo);
                }
                replacementParen = new Paren(new Selector(insideParent));
            }
            return replacementParen;
        }
        function createSelector(containedElement, originalElement) {
            var element, selector;
            element = new Element(null, containedElement, originalElement._index, originalElement._fileInfo);
            selector = new Selector([element]);
            return selector;
        }
        // joins selector path from `beginningPath` with selector path in `addPath`
        // `replacedElement` contains element that is being replaced by `addPath`
        // returns concatenated path
        function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
            var newSelectorPath, lastSelector, newJoinedSelector;
            // our new selector path
            newSelectorPath = [];
            // construct the joined selector - if & is the first thing this will be empty,
            // if not newJoinedSelector will be the last set of elements in the selector
            if (beginningPath.length > 0) {
                newSelectorPath = utils.copyArray(beginningPath);
                lastSelector = newSelectorPath.pop();
                newJoinedSelector = originalSelector.createDerived(utils.copyArray(lastSelector.elements));
            }
            else {
                newJoinedSelector = originalSelector.createDerived([]);
            }
            if (addPath.length > 0) {
                // /deep/ is a combinator that is valid without anything in front of it
                // so if the & does not have a combinator that is "" or " " then
                // and there is a combinator on the parent, then grab that.
                // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
                var combinator = replacedElement.combinator, parentEl = addPath[0].elements[0];
                if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
                    combinator = parentEl.combinator;
                }
                // join the elements so far with the first part of the parent
                newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement._index, replacedElement._fileInfo));
                newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
            }
            // now add the joined selector - but only if it is not empty
            if (newJoinedSelector.elements.length !== 0) {
                newSelectorPath.push(newJoinedSelector);
            }
            // put together the parent selectors after the join (e.g. the rest of the parent)
            if (addPath.length > 1) {
                var restOfPath = addPath.slice(1);
                restOfPath = restOfPath.map(function (selector) {
                    return selector.createDerived(selector.elements, []);
                });
                newSelectorPath = newSelectorPath.concat(restOfPath);
            }
            return newSelectorPath;
        }
        // joins selector path from `beginningPath` with every selector path in `addPaths` array
        // `replacedElement` contains element that is being replaced by `addPath`
        // returns array with all concatenated paths
        function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
            var j;
            for (j = 0; j < beginningPath.length; j++) {
                var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
                result.push(newSelectorPath);
            }
            return result;
        }
        function mergeElementsOnToSelectors(elements, selectors) {
            var i, sel;
            if (elements.length === 0) {
                return;
            }
            if (selectors.length === 0) {
                selectors.push([new Selector(elements)]);
                return;
            }
            for (i = 0; (sel = selectors[i]); i++) {
                // if the previous thing in sel is a parent this needs to join on to it
                if (sel.length > 0) {
                    sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
                }
                else {
                    sel.push(new Selector(elements));
                }
            }
        }
        // replace all parent selectors inside `inSelector` by content of `context` array
        // resulting selectors are returned inside `paths` array
        // returns true if `inSelector` contained at least one parent selector
        function replaceParentSelector(paths, context, inSelector) {
            // The paths are [[Selector]]
            // The first list is a list of comma separated selectors
            // The inner list is a list of inheritance separated selectors
            // e.g.
            // .a, .b {
            //   .c {
            //   }
            // }
            // == [[.a] [.c]] [[.b] [.c]]
            //
            var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;
            function findNestedSelector(element) {
                var maybeSelector;
                if (!(element.value instanceof Paren)) {
                    return null;
                }
                maybeSelector = element.value.value;
                if (!(maybeSelector instanceof Selector)) {
                    return null;
                }
                return maybeSelector;
            }
            // the elements from the current selector so far
            currentElements = [];
            // the current list of new selectors to add to the path.
            // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
            // by the parents
            newSelectors = [
                []
            ];
            for (i = 0; (el = inSelector.elements[i]); i++) {
                // non parent reference elements just get added
                if (el.value !== "&") {
                    var nestedSelector = findNestedSelector(el);
                    if (nestedSelector != null) {
                        // merge the current list of non parent selector elements
                        // on to the current list of selectors to add
                        mergeElementsOnToSelectors(currentElements, newSelectors);
                        var nestedPaths = [], replaced, replacedNewSelectors = [];
                        replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
                        hadParentSelector = hadParentSelector || replaced;
                        // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
                        for (k = 0; k < nestedPaths.length; k++) {
                            var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
                            addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
                        }
                        newSelectors = replacedNewSelectors;
                        currentElements = [];
                    }
                    else {
                        currentElements.push(el);
                    }
                }
                else {
                    hadParentSelector = true;
                    // the new list of selectors to add
                    selectorsMultiplied = [];
                    // merge the current list of non parent selector elements
                    // on to the current list of selectors to add
                    mergeElementsOnToSelectors(currentElements, newSelectors);
                    // loop through our current selectors
                    for (j = 0; j < newSelectors.length; j++) {
                        sel = newSelectors[j];
                        // if we don't have any parent paths, the & might be in a mixin so that it can be used
                        // whether there are parents or not
                        if (context.length === 0) {
                            // the combinator used on el should now be applied to the next element instead so that
                            // it is not lost
                            if (sel.length > 0) {
                                sel[0].elements.push(new Element(el.combinator, '', el._index, el._fileInfo));
                            }
                            selectorsMultiplied.push(sel);
                        }
                        else {
                            // and the parent selectors
                            for (k = 0; k < context.length; k++) {
                                // We need to put the current selectors
                                // then join the last selector's elements on to the parents selectors
                                var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
                                // add that to our new set of selectors
                                selectorsMultiplied.push(newSelectorPath);
                            }
                        }
                    }
                    // our new selectors has been multiplied, so reset the state
                    newSelectors = selectorsMultiplied;
                    currentElements = [];
                }
            }
            // if we have any elements left over (e.g. .a& .b == .b)
            // add them on to all the current selectors
            mergeElementsOnToSelectors(currentElements, newSelectors);
            for (i = 0; i < newSelectors.length; i++) {
                length = newSelectors[i].length;
                if (length > 0) {
                    paths.push(newSelectors[i]);
                    lastSelector = newSelectors[i][length - 1];
                    newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
                }
            }
            return hadParentSelector;
        }
        function deriveSelector(visibilityInfo, deriveFrom) {
            var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
            newSelector.copyVisibilityInfo(visibilityInfo);
            return newSelector;
        }
        // joinSelector code follows
        var i, newPaths, hadParentSelector;
        newPaths = [];
        hadParentSelector = replaceParentSelector(newPaths, context, selector);
        if (!hadParentSelector) {
            if (context.length > 0) {
                newPaths = [];
                for (i = 0; i < context.length; i++) {
                    var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
                    concatenated.push(selector);
                    newPaths.push(concatenated);
                }
            }
            else {
                newPaths = [[selector]];
            }
        }
        for (i = 0; i < newPaths.length; i++) {
            paths.push(newPaths[i]);
        }
    };
    module.exports = Ruleset;
}
,
/* less/lib/less/tree/selector */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Element = require(222) /* ./element */, LessError = require(197) /* ../less-error */;
    var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
        this.extendList = extendList;
        this.condition = condition;
        this.evaldCondition = !condition;
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.elements = this.getElements(elements);
        this.mixinElements_ = undefined;
        this.copyVisibilityInfo(visibilityInfo);
        this.setParent(this.elements, this);
    };
    Selector.prototype = new Node();
    Selector.prototype.type = "Selector";
    Selector.prototype.accept = function (visitor) {
        if (this.elements) {
            this.elements = visitor.visitArray(this.elements);
        }
        if (this.extendList) {
            this.extendList = visitor.visitArray(this.extendList);
        }
        if (this.condition) {
            this.condition = visitor.visit(this.condition);
        }
    };
    Selector.prototype.createDerived = function (elements, extendList, evaldCondition) {
        elements = this.getElements(elements);
        var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
        newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
        newSelector.mediaEmpty = this.mediaEmpty;
        return newSelector;
    };
    Selector.prototype.getElements = function (els) {
        if (typeof els === "string") {
            this.parse.parseNode(els, ["selector"], this._index, this._fileInfo, function (err, result) {
                if (err) {
                    throw new LessError({
                        index: err.index,
                        message: err.message
                    }, this.parse.imports, this._fileInfo.filename);
                }
                els = result[0].elements;
            });
        }
        return els;
    };
    Selector.prototype.createEmptySelectors = function () {
        var el = new Element('', '&', this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)];
        sels[0].mediaEmpty = true;
        return sels;
    };
    Selector.prototype.match = function (other) {
        var elements = this.elements, len = elements.length, olen, i;
        other = other.mixinElements();
        olen = other.length;
        if (olen === 0 || len < olen) {
            return 0;
        }
        else {
            for (i = 0; i < olen; i++) {
                if (elements[i].value !== other[i]) {
                    return 0;
                }
            }
        }
        return olen; // return number of matched elements
    };
    Selector.prototype.mixinElements = function () {
        if (this.mixinElements_) {
            return this.mixinElements_;
        }
        var elements = this.elements.map(function (v) {
            return v.combinator.value + (v.value.value || v.value);
        }).join("").match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
        if (elements) {
            if (elements[0] === "&") {
                elements.shift();
            }
        }
        else {
            elements = [];
        }
        return (this.mixinElements_ = elements);
    };
    Selector.prototype.isJustParentSelector = function () {
        return !this.mediaEmpty &&
            this.elements.length === 1 &&
            this.elements[0].value === '&' &&
            (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
    };
    Selector.prototype.eval = function (context) {
        var evaldCondition = this.condition && this.condition.eval(context), elements = this.elements, extendList = this.extendList;
        elements = elements && elements.map(function (e) { return e.eval(context); });
        extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
        return this.createDerived(elements, extendList, evaldCondition);
    };
    Selector.prototype.genCSS = function (context, output) {
        var i, element;
        if ((!context || !context.firstSelector) && this.elements[0].combinator.value === "") {
            output.add(' ', this.fileInfo(), this.getIndex());
        }
        for (i = 0; i < this.elements.length; i++) {
            element = this.elements[i];
            element.genCSS(context, output);
        }
    };
    Selector.prototype.getIsOutput = function () {
        return this.evaldCondition;
    };
    module.exports = Selector;
}
,
/* less/lib/less/tree/unicode-descriptor */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var UnicodeDescriptor = function (value) {
        this.value = value;
    };
    UnicodeDescriptor.prototype = new Node();
    UnicodeDescriptor.prototype.type = "UnicodeDescriptor";
    module.exports = UnicodeDescriptor;
}
,
/* less/lib/less/tree/unit */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, unitConversions = require(176) /* ../data/unit-conversions */, utils = require(247) /* ../utils */;
    var Unit = function (numerator, denominator, backupUnit) {
        this.numerator = numerator ? utils.copyArray(numerator).sort() : [];
        this.denominator = denominator ? utils.copyArray(denominator).sort() : [];
        if (backupUnit) {
            this.backupUnit = backupUnit;
        }
        else if (numerator && numerator.length) {
            this.backupUnit = numerator[0];
        }
    };
    Unit.prototype = new Node();
    Unit.prototype.type = "Unit";
    Unit.prototype.clone = function () {
        return new Unit(utils.copyArray(this.numerator), utils.copyArray(this.denominator), this.backupUnit);
    };
    Unit.prototype.genCSS = function (context, output) {
        // Dimension checks the unit is singular and throws an error if in strict math mode.
        var strictUnits = context && context.strictUnits;
        if (this.numerator.length === 1) {
            output.add(this.numerator[0]); // the ideal situation
        }
        else if (!strictUnits && this.backupUnit) {
            output.add(this.backupUnit);
        }
        else if (!strictUnits && this.denominator.length) {
            output.add(this.denominator[0]);
        }
    };
    Unit.prototype.toString = function () {
        var i, returnStr = this.numerator.join("*");
        for (i = 0; i < this.denominator.length; i++) {
            returnStr += "/" + this.denominator[i];
        }
        return returnStr;
    };
    Unit.prototype.compare = function (other) {
        return this.is(other.toString()) ? 0 : undefined;
    };
    Unit.prototype.is = function (unitString) {
        return this.toString().toUpperCase() === unitString.toUpperCase();
    };
    Unit.prototype.isLength = function () {
        return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
    };
    Unit.prototype.isEmpty = function () {
        return this.numerator.length === 0 && this.denominator.length === 0;
    };
    Unit.prototype.isSingular = function () {
        return this.numerator.length <= 1 && this.denominator.length === 0;
    };
    Unit.prototype.map = function (callback) {
        var i;
        for (i = 0; i < this.numerator.length; i++) {
            this.numerator[i] = callback(this.numerator[i], false);
        }
        for (i = 0; i < this.denominator.length; i++) {
            this.denominator[i] = callback(this.denominator[i], true);
        }
    };
    Unit.prototype.usedUnits = function () {
        var group, result = {}, mapUnit, groupName;
        mapUnit = function (atomicUnit) {
            /* jshint loopfunc:true */
            if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
                result[groupName] = atomicUnit;
            }
            return atomicUnit;
        };
        for (groupName in unitConversions) {
            if (unitConversions.hasOwnProperty(groupName)) {
                group = unitConversions[groupName];
                this.map(mapUnit);
            }
        }
        return result;
    };
    Unit.prototype.cancel = function () {
        var counter = {}, atomicUnit, i;
        for (i = 0; i < this.numerator.length; i++) {
            atomicUnit = this.numerator[i];
            counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
        }
        for (i = 0; i < this.denominator.length; i++) {
            atomicUnit = this.denominator[i];
            counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
        }
        this.numerator = [];
        this.denominator = [];
        for (atomicUnit in counter) {
            if (counter.hasOwnProperty(atomicUnit)) {
                var count = counter[atomicUnit];
                if (count > 0) {
                    for (i = 0; i < count; i++) {
                        this.numerator.push(atomicUnit);
                    }
                }
                else if (count < 0) {
                    for (i = 0; i < -count; i++) {
                        this.denominator.push(atomicUnit);
                    }
                }
            }
        }
        this.numerator.sort();
        this.denominator.sort();
    };
    module.exports = Unit;
}
,
/* less/lib/less/tree/url */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var URL = function (val, index, currentFileInfo, isEvald) {
        this.value = val;
        this._index = index;
        this._fileInfo = currentFileInfo;
        this.isEvald = isEvald;
    };
    URL.prototype = new Node();
    URL.prototype.type = "Url";
    URL.prototype.accept = function (visitor) {
        this.value = visitor.visit(this.value);
    };
    URL.prototype.genCSS = function (context, output) {
        output.add("url(");
        this.value.genCSS(context, output);
        output.add(")");
    };
    URL.prototype.eval = function (context) {
        var val = this.value.eval(context), rootpath;
        if (!this.isEvald) {
            // Add the base path if the URL is relative
            rootpath = this.fileInfo() && this.fileInfo().rootpath;
            if (rootpath &&
                typeof val.value === "string" &&
                context.isPathRelative(val.value)) {
                if (!val.quote) {
                    rootpath = rootpath.replace(/[\(\)'"\s]/g, function (match) { return "\\" + match; });
                }
                val.value = rootpath + val.value;
            }
            val.value = context.normalizePath(val.value);
            // Add url args if enabled
            if (context.urlArgs) {
                if (!val.value.match(/^\s*data:/)) {
                    var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
                    var urlArgs = delimiter + context.urlArgs;
                    if (val.value.indexOf('#') !== -1) {
                        val.value = val.value.replace('#', urlArgs + '#');
                    }
                    else {
                        val.value += urlArgs;
                    }
                }
            }
        }
        return new URL(val, this.getIndex(), this.fileInfo(), true);
    };
    module.exports = URL;
}
,
/* less/lib/less/tree/value */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Value = function (value) {
        if (!value) {
            throw new Error("Value requires an array argument");
        }
        if (!Array.isArray(value)) {
            this.value = [value];
        }
        else {
            this.value = value;
        }
    };
    Value.prototype = new Node();
    Value.prototype.type = "Value";
    Value.prototype.accept = function (visitor) {
        if (this.value) {
            this.value = visitor.visitArray(this.value);
        }
    };
    Value.prototype.eval = function (context) {
        if (this.value.length === 1) {
            return this.value[0].eval(context);
        }
        else {
            return new Value(this.value.map(function (v) {
                return v.eval(context);
            }));
        }
    };
    Value.prototype.genCSS = function (context, output) {
        var i;
        for (i = 0; i < this.value.length; i++) {
            this.value[i].genCSS(context, output);
            if (i + 1 < this.value.length) {
                output.add((context && context.compress) ? ',' : ', ');
            }
        }
    };
    module.exports = Value;
}
,
/* less/lib/less/tree/variable-call */ function _(require, module, exports) {
    var Node = require(234) /* ./node */, Variable = require(246) /* ./variable */;
    var VariableCall = function (variable) {
        this.variable = variable;
        this.allowRoot = true;
    };
    VariableCall.prototype = new Node();
    VariableCall.prototype.type = "VariableCall";
    VariableCall.prototype.eval = function (context) {
        var detachedRuleset = new Variable(this.variable).eval(context);
        return detachedRuleset.callEval(context);
    };
    module.exports = VariableCall;
}
,
/* less/lib/less/tree/variable */ function _(require, module, exports) {
    var Node = require(234) /* ./node */;
    var Variable = function (name, index, currentFileInfo) {
        this.name = name;
        this._index = index;
        this._fileInfo = currentFileInfo;
    };
    Variable.prototype = new Node();
    Variable.prototype.type = "Variable";
    Variable.prototype.eval = function (context) {
        var variable, name = this.name;
        if (name.indexOf('@@') === 0) {
            name = '@' + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
        }
        if (this.evaluating) {
            throw { type: 'Name',
                message: "Recursive variable definition for " + name,
                filename: this.fileInfo().filename,
                index: this.getIndex() };
        }
        this.evaluating = true;
        variable = this.find(context.frames, function (frame) {
            var v = frame.variable(name);
            if (v) {
                if (v.important) {
                    var importantScope = context.importantScope[context.importantScope.length - 1];
                    importantScope.important = v.important;
                }
                return v.value.eval(context);
            }
        });
        if (variable) {
            this.evaluating = false;
            return variable;
        }
        else {
            throw { type: 'Name',
                message: "variable " + name + " is undefined",
                filename: this.fileInfo().filename,
                index: this.getIndex() };
        }
    };
    Variable.prototype.find = function (obj, fun) {
        for (var i = 0, r; i < obj.length; i++) {
            r = fun.call(obj, obj[i]);
            if (r) {
                return r;
            }
        }
        return null;
    };
    module.exports = Variable;
}
,
/* less/lib/less/utils */ function _(require, module, exports) {
    /* jshint proto: true */
    module.exports = {
        getLocation: function (index, inputStream) {
            var n = index + 1, line = null, column = -1;
            while (--n >= 0 && inputStream.charAt(n) !== '\n') {
                column++;
            }
            if (typeof index === 'number') {
                line = (inputStream.slice(0, index).match(/\n/g) || "").length;
            }
            return {
                line: line,
                column: column
            };
        },
        copyArray: function (arr) {
            var i, length = arr.length, copy = new Array(length);
            for (i = 0; i < length; i++) {
                copy[i] = arr[i];
            }
            return copy;
        },
        clone: function (obj) {
            var cloned = {};
            for (var prop in obj) {
                if (obj.hasOwnProperty(prop)) {
                    cloned[prop] = obj[prop];
                }
            }
            return cloned;
        },
        defaults: function (obj1, obj2) {
            if (!obj2._defaults || obj2._defaults !== obj1) {
                for (var prop in obj1) {
                    if (obj1.hasOwnProperty(prop)) {
                        if (!obj2.hasOwnProperty(prop)) {
                            obj2[prop] = obj1[prop];
                        }
                        else if (Array.isArray(obj1[prop])
                            && Array.isArray(obj2[prop])) {
                            obj1[prop].forEach(function (p) {
                                if (obj2[prop].indexOf(p) === -1) {
                                    obj2[prop].push(p);
                                }
                            });
                        }
                    }
                }
            }
            obj2._defaults = obj1;
            return obj2;
        },
        merge: function (obj1, obj2) {
            for (var prop in obj2) {
                if (obj2.hasOwnProperty(prop)) {
                    obj1[prop] = obj2[prop];
                }
            }
            return obj1;
        }
    };
}
,
/* less/lib/less/visitors/extend-visitor */ function _(require, module, exports) {
    var tree = require(226) /* ../tree */, Visitor = require(255) /* ./visitor */, logger = require(198) /* ../logger */, utils = require(247) /* ../utils */;
    /* jshint loopfunc:true */
    var ExtendFinderVisitor = function () {
        this._visitor = new Visitor(this);
        this.contexts = [];
        this.allExtendsStack = [[]];
    };
    ExtendFinderVisitor.prototype = {
        run: function (root) {
            root = this._visitor.visit(root);
            root.allExtends = this.allExtendsStack[0];
            return root;
        },
        visitDeclaration: function (declNode, visitArgs) {
            visitArgs.visitDeeper = false;
        },
        visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
            visitArgs.visitDeeper = false;
        },
        visitRuleset: function (rulesetNode, visitArgs) {
            if (rulesetNode.root) {
                return;
            }
            var i, j, extend, allSelectorsExtendList = [], extendList;
            // get &:extend(.a); rules which apply to all selectors in this ruleset
            var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
            for (i = 0; i < ruleCnt; i++) {
                if (rulesetNode.rules[i] instanceof tree.Extend) {
                    allSelectorsExtendList.push(rules[i]);
                    rulesetNode.extendOnEveryPath = true;
                }
            }
            // now find every selector and apply the extends that apply to all extends
            // and the ones which apply to an individual extend
            var paths = rulesetNode.paths;
            for (i = 0; i < paths.length; i++) {
                var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList;
                extendList = selExtendList ? utils.copyArray(selExtendList).concat(allSelectorsExtendList)
                    : allSelectorsExtendList;
                if (extendList) {
                    extendList = extendList.map(function (allSelectorsExtend) {
                        return allSelectorsExtend.clone();
                    });
                }
                for (j = 0; j < extendList.length; j++) {
                    this.foundExtends = true;
                    extend = extendList[j];
                    extend.findSelfSelectors(selectorPath);
                    extend.ruleset = rulesetNode;
                    if (j === 0) {
                        extend.firstExtendOnThisSelectorPath = true;
                    }
                    this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
                }
            }
            this.contexts.push(rulesetNode.selectors);
        },
        visitRulesetOut: function (rulesetNode) {
            if (!rulesetNode.root) {
                this.contexts.length = this.contexts.length - 1;
            }
        },
        visitMedia: function (mediaNode, visitArgs) {
            mediaNode.allExtends = [];
            this.allExtendsStack.push(mediaNode.allExtends);
        },
        visitMediaOut: function (mediaNode) {
            this.allExtendsStack.length = this.allExtendsStack.length - 1;
        },
        visitAtRule: function (atRuleNode, visitArgs) {
            atRuleNode.allExtends = [];
            this.allExtendsStack.push(atRuleNode.allExtends);
        },
        visitAtRuleOut: function (atRuleNode) {
            this.allExtendsStack.length = this.allExtendsStack.length - 1;
        }
    };
    var ProcessExtendsVisitor = function () {
        this._visitor = new Visitor(this);
    };
    ProcessExtendsVisitor.prototype = {
        run: function (root) {
            var extendFinder = new ExtendFinderVisitor();
            this.extendIndices = {};
            extendFinder.run(root);
            if (!extendFinder.foundExtends) {
                return root;
            }
            root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
            this.allExtendsStack = [root.allExtends];
            var newRoot = this._visitor.visit(root);
            this.checkExtendsForNonMatched(root.allExtends);
            return newRoot;
        },
        checkExtendsForNonMatched: function (extendList) {
            var indices = this.extendIndices;
            extendList.filter(function (extend) {
                return !extend.hasFoundMatches && extend.parent_ids.length == 1;
            }).forEach(function (extend) {
                var selector = "_unknown_";
                try {
                    selector = extend.selector.toCSS({});
                }
                catch (_) { }
                if (!indices[extend.index + ' ' + selector]) {
                    indices[extend.index + ' ' + selector] = true;
                    logger.warn("extend '" + selector + "' has no matches");
                }
            });
        },
        doExtendChaining: function (extendsList, extendsListTarget, iterationCount) {
            //
            // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
            // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
            // this means this new extend can then go and alter other extends
            //
            // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
            // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
            // processed if we look at each selector at a time, as is done in visitRuleset
            var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend;
            iterationCount = iterationCount || 0;
            // loop through comparing every extend with every target extend.
            // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
            // e.g.  .a:extend(.b) {}  and .b:extend(.c) {} then the first extend extends the second one
            // and the second is the target.
            // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
            // case when processing media queries
            for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
                for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
                    extend = extendsList[extendIndex];
                    targetExtend = extendsListTarget[targetExtendIndex];
                    // look for circular references
                    if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
                        continue;
                    }
                    // find a match in the target extends self selector (the bit before :extend)
                    selectorPath = [targetExtend.selfSelectors[0]];
                    matches = extendVisitor.findMatch(extend, selectorPath);
                    if (matches.length) {
                        extend.hasFoundMatches = true;
                        // we found a match, so for each self selector..
                        extend.selfSelectors.forEach(function (selfSelector) {
                            var info = targetExtend.visibilityInfo();
                            // process the extend as usual
                            newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
                            // but now we create a new extend from it
                            newExtend = new (tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
                            newExtend.selfSelectors = newSelector;
                            // add the extend onto the list of extends for that selector
                            newSelector[newSelector.length - 1].extendList = [newExtend];
                            // record that we need to add it.
                            extendsToAdd.push(newExtend);
                            newExtend.ruleset = targetExtend.ruleset;
                            //remember its parents for circular references
                            newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
                            // only process the selector once.. if we have :extend(.a,.b) then multiple
                            // extends will look at the same selector path, so when extending
                            // we know that any others will be duplicates in terms of what is added to the css
                            if (targetExtend.firstExtendOnThisSelectorPath) {
                                newExtend.firstExtendOnThisSelectorPath = true;
                                targetExtend.ruleset.paths.push(newSelector);
                            }
                        });
                    }
                }
            }
            if (extendsToAdd.length) {
                // try to detect circular references to stop a stack overflow.
                // may no longer be needed.
                this.extendChainCount++;
                if (iterationCount > 100) {
                    var selectorOne = "{unable to calculate}";
                    var selectorTwo = "{unable to calculate}";
                    try {
                        selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
                        selectorTwo = extendsToAdd[0].selector.toCSS();
                    }
                    catch (e) { }
                    throw { message: "extend circular reference detected. One of the circular extends is currently:" +
                            selectorOne + ":extend(" + selectorTwo + ")" };
                }
                // now process the new extends on the existing rules so that we can handle a extending b extending c extending
                // d extending e...
                return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
            }
            else {
                return extendsToAdd;
            }
        },
        visitDeclaration: function (ruleNode, visitArgs) {
            visitArgs.visitDeeper = false;
        },
        visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
            visitArgs.visitDeeper = false;
        },
        visitSelector: function (selectorNode, visitArgs) {
            visitArgs.visitDeeper = false;
        },
        visitRuleset: function (rulesetNode, visitArgs) {
            if (rulesetNode.root) {
                return;
            }
            var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length - 1], selectorsToAdd = [], extendVisitor = this, selectorPath;
            // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
            for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
                for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
                    selectorPath = rulesetNode.paths[pathIndex];
                    // extending extends happens initially, before the main pass
                    if (rulesetNode.extendOnEveryPath) {
                        continue;
                    }
                    var extendList = selectorPath[selectorPath.length - 1].extendList;
                    if (extendList && extendList.length) {
                        continue;
                    }
                    matches = this.findMatch(allExtends[extendIndex], selectorPath);
                    if (matches.length) {
                        allExtends[extendIndex].hasFoundMatches = true;
                        allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
                            var extendedSelectors;
                            extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
                            selectorsToAdd.push(extendedSelectors);
                        });
                    }
                }
            }
            rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
        },
        findMatch: function (extend, haystackSelectorPath) {
            //
            // look through the haystack selector path to try and find the needle - extend.selector
            // returns an array of selector matches that can then be replaced
            //
            var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement, targetCombinator, i, extendVisitor = this, needleElements = extend.selector.elements, potentialMatches = [], potentialMatch, matches = [];
            // loop through the haystack elements
            for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
                hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
                for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
                    haystackElement = hackstackSelector.elements[hackstackElementIndex];
                    // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
                    if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
                        potentialMatches.push({ pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
                            initialCombinator: haystackElement.combinator });
                    }
                    for (i = 0; i < potentialMatches.length; i++) {
                        potentialMatch = potentialMatches[i];
                        // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
                        // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
                        // work out what the resulting combinator will be
                        targetCombinator = haystackElement.combinator.value;
                        if (targetCombinator === '' && hackstackElementIndex === 0) {
                            targetCombinator = ' ';
                        }
                        // if we don't match, null our match to indicate failure
                        if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
                            (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
                            potentialMatch = null;
                        }
                        else {
                            potentialMatch.matched++;
                        }
                        // if we are still valid and have finished, test whether we have elements after and whether these are allowed
                        if (potentialMatch) {
                            potentialMatch.finished = potentialMatch.matched === needleElements.length;
                            if (potentialMatch.finished &&
                                (!extend.allowAfter &&
                                    (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
                                potentialMatch = null;
                            }
                        }
                        // if null we remove, if not, we are still valid, so either push as a valid match or continue
                        if (potentialMatch) {
                            if (potentialMatch.finished) {
                                potentialMatch.length = needleElements.length;
                                potentialMatch.endPathIndex = haystackSelectorIndex;
                                potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
                                potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
                                matches.push(potentialMatch);
                            }
                        }
                        else {
                            potentialMatches.splice(i, 1);
                            i--;
                        }
                    }
                }
            }
            return matches;
        },
        isElementValuesEqual: function (elementValue1, elementValue2) {
            if (typeof elementValue1 === "string" || typeof elementValue2 === "string") {
                return elementValue1 === elementValue2;
            }
            if (elementValue1 instanceof tree.Attribute) {
                if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
                    return false;
                }
                if (!elementValue1.value || !elementValue2.value) {
                    if (elementValue1.value || elementValue2.value) {
                        return false;
                    }
                    return true;
                }
                elementValue1 = elementValue1.value.value || elementValue1.value;
                elementValue2 = elementValue2.value.value || elementValue2.value;
                return elementValue1 === elementValue2;
            }
            elementValue1 = elementValue1.value;
            elementValue2 = elementValue2.value;
            if (elementValue1 instanceof tree.Selector) {
                if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
                    return false;
                }
                for (var i = 0; i < elementValue1.elements.length; i++) {
                    if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
                        if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
                            return false;
                        }
                    }
                    if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        },
        extendSelector: function (matches, selectorPath, replacementSelector, isVisible) {
            // for a set of matches, replace each match with the replacement selector
            var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements;
            for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
                match = matches[matchIndex];
                selector = selectorPath[match.pathIndex];
                firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
                if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
                    path[path.length - 1].elements = path[path.length - 1]
                        .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
                    currentSelectorPathElementIndex = 0;
                    currentSelectorPathIndex++;
                }
                newElements = selector.elements
                    .slice(currentSelectorPathElementIndex, match.index)
                    .concat([firstElement])
                    .concat(replacementSelector.elements.slice(1));
                if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
                    path[path.length - 1].elements =
                        path[path.length - 1].elements.concat(newElements);
                }
                else {
                    path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
                    path.push(new tree.Selector(newElements));
                }
                currentSelectorPathIndex = match.endPathIndex;
                currentSelectorPathElementIndex = match.endPathElementIndex;
                if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
                    currentSelectorPathElementIndex = 0;
                    currentSelectorPathIndex++;
                }
            }
            if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
                path[path.length - 1].elements = path[path.length - 1]
                    .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
                currentSelectorPathIndex++;
            }
            path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
            path = path.map(function (currentValue) {
                // we can re-use elements here, because the visibility property matters only for selectors
                var derived = currentValue.createDerived(currentValue.elements);
                if (isVisible) {
                    derived.ensureVisibility();
                }
                else {
                    derived.ensureInvisibility();
                }
                return derived;
            });
            return path;
        },
        visitMedia: function (mediaNode, visitArgs) {
            var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
            newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
            this.allExtendsStack.push(newAllExtends);
        },
        visitMediaOut: function (mediaNode) {
            var lastIndex = this.allExtendsStack.length - 1;
            this.allExtendsStack.length = lastIndex;
        },
        visitAtRule: function (atRuleNode, visitArgs) {
            var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
            newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
            this.allExtendsStack.push(newAllExtends);
        },
        visitAtRuleOut: function (atRuleNode) {
            var lastIndex = this.allExtendsStack.length - 1;
            this.allExtendsStack.length = lastIndex;
        }
    };
    module.exports = ProcessExtendsVisitor;
}
,
/* less/lib/less/visitors/import-sequencer */ function _(require, module, exports) {
    function ImportSequencer(onSequencerEmpty) {
        this.imports = [];
        this.variableImports = [];
        this._onSequencerEmpty = onSequencerEmpty;
        this._currentDepth = 0;
    }
    ImportSequencer.prototype.addImport = function (callback) {
        var importSequencer = this, importItem = {
            callback: callback,
            args: null,
            isReady: false
        };
        this.imports.push(importItem);
        return function () {
            importItem.args = Array.prototype.slice.call(arguments, 0);
            importItem.isReady = true;
            importSequencer.tryRun();
        };
    };
    ImportSequencer.prototype.addVariableImport = function (callback) {
        this.variableImports.push(callback);
    };
    ImportSequencer.prototype.tryRun = function () {
        this._currentDepth++;
        try {
            while (true) {
                while (this.imports.length > 0) {
                    var importItem = this.imports[0];
                    if (!importItem.isReady) {
                        return;
                    }
                    this.imports = this.imports.slice(1);
                    importItem.callback.apply(null, importItem.args);
                }
                if (this.variableImports.length === 0) {
                    break;
                }
                var variableImport = this.variableImports[0];
                this.variableImports = this.variableImports.slice(1);
                variableImport();
            }
        }
        finally {
            this._currentDepth--;
        }
        if (this._currentDepth === 0 && this._onSequencerEmpty) {
            this._onSequencerEmpty();
        }
    };
    module.exports = ImportSequencer;
}
,
/* less/lib/less/visitors/import-visitor */ function _(require, module, exports) {
    var contexts = require(173) /* ../contexts */, Visitor = require(255) /* ./visitor */, ImportSequencer = require(249) /* ./import-sequencer */, utils = require(247) /* ../utils */;
    var ImportVisitor = function (importer, finish) {
        this._visitor = new Visitor(this);
        this._importer = importer;
        this._finish = finish;
        this.context = new contexts.Eval();
        this.importCount = 0;
        this.onceFileDetectionMap = {};
        this.recursionDetector = {};
        this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
    };
    ImportVisitor.prototype = {
        isReplacing: false,
        run: function (root) {
            try {
                // process the contents
                this._visitor.visit(root);
            }
            catch (e) {
                this.error = e;
            }
            this.isFinished = true;
            this._sequencer.tryRun();
        },
        _onSequencerEmpty: function () {
            if (!this.isFinished) {
                return;
            }
            this._finish(this.error);
        },
        visitImport: function (importNode, visitArgs) {
            var inlineCSS = importNode.options.inline;
            if (!importNode.css || inlineCSS) {
                var context = new contexts.Eval(this.context, utils.copyArray(this.context.frames));
                var importParent = context.frames[0];
                this.importCount++;
                if (importNode.isVariableImport()) {
                    this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
                }
                else {
                    this.processImportNode(importNode, context, importParent);
                }
            }
            visitArgs.visitDeeper = false;
        },
        processImportNode: function (importNode, context, importParent) {
            var evaldImportNode, inlineCSS = importNode.options.inline;
            try {
                evaldImportNode = importNode.evalForImport(context);
            }
            catch (e) {
                if (!e.filename) {
                    e.index = importNode.getIndex();
                    e.filename = importNode.fileInfo().filename;
                }
                // attempt to eval properly and treat as css
                importNode.css = true;
                // if that fails, this error will be thrown
                importNode.error = e;
            }
            if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
                if (evaldImportNode.options.multiple) {
                    context.importMultiple = true;
                }
                // try appending if we haven't determined if it is css or not
                var tryAppendLessExtension = evaldImportNode.css === undefined;
                for (var i = 0; i < importParent.rules.length; i++) {
                    if (importParent.rules[i] === importNode) {
                        importParent.rules[i] = evaldImportNode;
                        break;
                    }
                }
                var onImported = this.onImported.bind(this, evaldImportNode, context), sequencedOnImported = this._sequencer.addImport(onImported);
                this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
            }
            else {
                this.importCount--;
                if (this.isFinished) {
                    this._sequencer.tryRun();
                }
            }
        },
        onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
            if (e) {
                if (!e.filename) {
                    e.index = importNode.getIndex();
                    e.filename = importNode.fileInfo().filename;
                }
                this.error = e;
            }
            var importVisitor = this, inlineCSS = importNode.options.inline, isPlugin = importNode.options.isPlugin, isOptional = importNode.options.optional, duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
            if (!context.importMultiple) {
                if (duplicateImport) {
                    importNode.skip = true;
                }
                else {
                    importNode.skip = function () {
                        if (fullPath in importVisitor.onceFileDetectionMap) {
                            return true;
                        }
                        importVisitor.onceFileDetectionMap[fullPath] = true;
                        return false;
                    };
                }
            }
            if (!fullPath && isOptional) {
                importNode.skip = true;
            }
            if (root) {
                importNode.root = root;
                importNode.importedFilename = fullPath;
                if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
                    importVisitor.recursionDetector[fullPath] = true;
                    var oldContext = this.context;
                    this.context = context;
                    try {
                        this._visitor.visit(root);
                    }
                    catch (e) {
                        this.error = e;
                    }
                    this.context = oldContext;
                }
            }
            importVisitor.importCount--;
            if (importVisitor.isFinished) {
                importVisitor._sequencer.tryRun();
            }
        },
        visitDeclaration: function (declNode, visitArgs) {
            if (declNode.value.type === "DetachedRuleset") {
                this.context.frames.unshift(declNode);
            }
            else {
                visitArgs.visitDeeper = false;
            }
        },
        visitDeclarationOut: function (declNode) {
            if (declNode.value.type === "DetachedRuleset") {
                this.context.frames.shift();
            }
        },
        visitAtRule: function (atRuleNode, visitArgs) {
            this.context.frames.unshift(atRuleNode);
        },
        visitAtRuleOut: function (atRuleNode) {
            this.context.frames.shift();
        },
        visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
            this.context.frames.unshift(mixinDefinitionNode);
        },
        visitMixinDefinitionOut: function (mixinDefinitionNode) {
            this.context.frames.shift();
        },
        visitRuleset: function (rulesetNode, visitArgs) {
            this.context.frames.unshift(rulesetNode);
        },
        visitRulesetOut: function (rulesetNode) {
            this.context.frames.shift();
        },
        visitMedia: function (mediaNode, visitArgs) {
            this.context.frames.unshift(mediaNode.rules[0]);
        },
        visitMediaOut: function (mediaNode) {
            this.context.frames.shift();
        }
    };
    module.exports = ImportVisitor;
}
,
/* less/lib/less/visitors/index */ function _(require, module, exports) {
    var visitors = {
        Visitor: require(255) /* ./visitor */,
        ImportVisitor: require(250) /* ./import-visitor */,
        MarkVisibleSelectorsVisitor: require(253) /* ./set-tree-visibility-visitor */,
        ExtendVisitor: require(248) /* ./extend-visitor */,
        JoinSelectorVisitor: require(252) /* ./join-selector-visitor */,
        ToCSSVisitor: require(254) /* ./to-css-visitor */
    };
    module.exports = visitors;
}
,
/* less/lib/less/visitors/join-selector-visitor */ function _(require, module, exports) {
    var Visitor = require(255) /* ./visitor */;
    var JoinSelectorVisitor = function () {
        this.contexts = [[]];
        this._visitor = new Visitor(this);
    };
    JoinSelectorVisitor.prototype = {
        run: function (root) {
            return this._visitor.visit(root);
        },
        visitDeclaration: function (declNode, visitArgs) {
            visitArgs.visitDeeper = false;
        },
        visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
            visitArgs.visitDeeper = false;
        },
        visitRuleset: function (rulesetNode, visitArgs) {
            var context = this.contexts[this.contexts.length - 1], paths = [], selectors;
            this.contexts.push(paths);
            if (!rulesetNode.root) {
                selectors = rulesetNode.selectors;
                if (selectors) {
                    selectors = selectors.filter(function (selector) { return selector.getIsOutput(); });
                    rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
                    if (selectors) {
                        rulesetNode.joinSelectors(paths, context, selectors);
                    }
                }
                if (!selectors) {
                    rulesetNode.rules = null;
                }
                rulesetNode.paths = paths;
            }
        },
        visitRulesetOut: function (rulesetNode) {
            this.contexts.length = this.contexts.length - 1;
        },
        visitMedia: function (mediaNode, visitArgs) {
            var context = this.contexts[this.contexts.length - 1];
            mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
        },
        visitAtRule: function (atRuleNode, visitArgs) {
            var context = this.contexts[this.contexts.length - 1];
            if (atRuleNode.rules && atRuleNode.rules.length) {
                atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
            }
        }
    };
    module.exports = JoinSelectorVisitor;
}
,
/* less/lib/less/visitors/set-tree-visibility-visitor */ function _(require, module, exports) {
    var SetTreeVisibilityVisitor = function (visible) {
        this.visible = visible;
    };
    SetTreeVisibilityVisitor.prototype.run = function (root) {
        this.visit(root);
    };
    SetTreeVisibilityVisitor.prototype.visitArray = function (nodes) {
        if (!nodes) {
            return nodes;
        }
        var cnt = nodes.length, i;
        for (i = 0; i < cnt; i++) {
            this.visit(nodes[i]);
        }
        return nodes;
    };
    SetTreeVisibilityVisitor.prototype.visit = function (node) {
        if (!node) {
            return node;
        }
        if (node.constructor === Array) {
            return this.visitArray(node);
        }
        if (!node.blocksVisibility || node.blocksVisibility()) {
            return node;
        }
        if (this.visible) {
            node.ensureVisibility();
        }
        else {
            node.ensureInvisibility();
        }
        node.accept(this);
        return node;
    };
    module.exports = SetTreeVisibilityVisitor;
}
,
/* less/lib/less/visitors/to-css-visitor */ function _(require, module, exports) {
    var tree = require(226) /* ../tree */, Visitor = require(255) /* ./visitor */;
    var CSSVisitorUtils = function (context) {
        this._visitor = new Visitor(this);
        this._context = context;
    };
    CSSVisitorUtils.prototype = {
        containsSilentNonBlockedChild: function (bodyRules) {
            var rule;
            if (!bodyRules) {
                return false;
            }
            for (var r = 0; r < bodyRules.length; r++) {
                rule = bodyRules[r];
                if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
                    // the atrule contains something that was referenced (likely by extend)
                    // therefore it needs to be shown in output too
                    return true;
                }
            }
            return false;
        },
        keepOnlyVisibleChilds: function (owner) {
            if (owner && owner.rules) {
                owner.rules = owner.rules.filter(function (thing) {
                    return thing.isVisible();
                });
            }
        },
        isEmpty: function (owner) {
            return (owner && owner.rules)
                ? (owner.rules.length === 0) : true;
        },
        hasVisibleSelector: function (rulesetNode) {
            return (rulesetNode && rulesetNode.paths)
                ? (rulesetNode.paths.length > 0) : false;
        },
        resolveVisibility: function (node, originalRules) {
            if (!node.blocksVisibility()) {
                if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
                    return;
                }
                return node;
            }
            var compiledRulesBody = node.rules[0];
            this.keepOnlyVisibleChilds(compiledRulesBody);
            if (this.isEmpty(compiledRulesBody)) {
                return;
            }
            node.ensureVisibility();
            node.removeVisibilityBlock();
            return node;
        },
        isVisibleRuleset: function (rulesetNode) {
            if (rulesetNode.firstRoot) {
                return true;
            }
            if (this.isEmpty(rulesetNode)) {
                return false;
            }
            if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
                return false;
            }
            return true;
        }
    };
    var ToCSSVisitor = function (context) {
        this._visitor = new Visitor(this);
        this._context = context;
        this.utils = new CSSVisitorUtils(context);
    };
    ToCSSVisitor.prototype = {
        isReplacing: true,
        run: function (root) {
            return this._visitor.visit(root);
        },
        visitDeclaration: function (declNode, visitArgs) {
            if (declNode.blocksVisibility() || declNode.variable) {
                return;
            }
            return declNode;
        },
        visitMixinDefinition: function (mixinNode, visitArgs) {
            // mixin definitions do not get eval'd - this means they keep state
            // so we have to clear that state here so it isn't used if toCSS is called twice
            mixinNode.frames = [];
        },
        visitExtend: function (extendNode, visitArgs) {
        },
        visitComment: function (commentNode, visitArgs) {
            if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
                return;
            }
            return commentNode;
        },
        visitMedia: function (mediaNode, visitArgs) {
            var originalRules = mediaNode.rules[0].rules;
            mediaNode.accept(this._visitor);
            visitArgs.visitDeeper = false;
            return this.utils.resolveVisibility(mediaNode, originalRules);
        },
        visitImport: function (importNode, visitArgs) {
            if (importNode.blocksVisibility()) {
                return;
            }
            return importNode;
        },
        visitAtRule: function (atRuleNode, visitArgs) {
            if (atRuleNode.rules && atRuleNode.rules.length) {
                return this.visitAtRuleWithBody(atRuleNode, visitArgs);
            }
            else {
                return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
            }
        },
        visitAnonymous: function (anonymousNode, visitArgs) {
            if (!anonymousNode.blocksVisibility()) {
                anonymousNode.accept(this._visitor);
                return anonymousNode;
            }
        },
        visitAtRuleWithBody: function (atRuleNode, visitArgs) {
            // if there is only one nested ruleset and that one has no path, then it is
            // just fake ruleset
            function hasFakeRuleset(atRuleNode) {
                var bodyRules = atRuleNode.rules;
                return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
            }
            function getBodyRules(atRuleNode) {
                var nodeRules = atRuleNode.rules;
                if (hasFakeRuleset(atRuleNode)) {
                    return nodeRules[0].rules;
                }
                return nodeRules;
            }
            // it is still true that it is only one ruleset in array
            // this is last such moment
            // process childs
            var originalRules = getBodyRules(atRuleNode);
            atRuleNode.accept(this._visitor);
            visitArgs.visitDeeper = false;
            if (!this.utils.isEmpty(atRuleNode)) {
                this._mergeRules(atRuleNode.rules[0].rules);
            }
            return this.utils.resolveVisibility(atRuleNode, originalRules);
        },
        visitAtRuleWithoutBody: function (atRuleNode, visitArgs) {
            if (atRuleNode.blocksVisibility()) {
                return;
            }
            if (atRuleNode.name === "@charset") {
                // Only output the debug info together with subsequent @charset definitions
                // a comment (or @media statement) before the actual @charset atrule would
                // be considered illegal css as it has to be on the first line
                if (this.charset) {
                    if (atRuleNode.debugInfo) {
                        var comment = new tree.Comment("/* " + atRuleNode.toCSS(this._context).replace(/\n/g, "") + " */\n");
                        comment.debugInfo = atRuleNode.debugInfo;
                        return this._visitor.visit(comment);
                    }
                    return;
                }
                this.charset = true;
            }
            return atRuleNode;
        },
        checkValidNodes: function (rules, isRoot) {
            if (!rules) {
                return;
            }
            for (var i = 0; i < rules.length; i++) {
                var ruleNode = rules[i];
                if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
                    throw { message: "Properties must be inside selector blocks. They cannot be in the root",
                        index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
                }
                if (ruleNode instanceof tree.Call) {
                    throw { message: "Function '" + ruleNode.name + "' is undefined",
                        index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
                }
                if (ruleNode.type && !ruleNode.allowRoot) {
                    throw { message: ruleNode.type + " node returned by a function is not valid here",
                        index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
                }
            }
        },
        visitRuleset: function (rulesetNode, visitArgs) {
            // at this point rulesets are nested into each other
            var rule, rulesets = [];
            this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
            if (!rulesetNode.root) {
                // remove invisible paths
                this._compileRulesetPaths(rulesetNode);
                // remove rulesets from this ruleset body and compile them separately
                var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0;
                for (var i = 0; i < nodeRuleCnt;) {
                    rule = nodeRules[i];
                    if (rule && rule.rules) {
                        // visit because we are moving them out from being a child
                        rulesets.push(this._visitor.visit(rule));
                        nodeRules.splice(i, 1);
                        nodeRuleCnt--;
                        continue;
                    }
                    i++;
                }
                // accept the visitor to remove rules and refactor itself
                // then we can decide nogw whether we want it or not
                // compile body
                if (nodeRuleCnt > 0) {
                    rulesetNode.accept(this._visitor);
                }
                else {
                    rulesetNode.rules = null;
                }
                visitArgs.visitDeeper = false;
            }
            else { // if (! rulesetNode.root) {
                rulesetNode.accept(this._visitor);
                visitArgs.visitDeeper = false;
            }
            if (rulesetNode.rules) {
                this._mergeRules(rulesetNode.rules);
                this._removeDuplicateRules(rulesetNode.rules);
            }
            // now decide whether we keep the ruleset
            if (this.utils.isVisibleRuleset(rulesetNode)) {
                rulesetNode.ensureVisibility();
                rulesets.splice(0, 0, rulesetNode);
            }
            if (rulesets.length === 1) {
                return rulesets[0];
            }
            return rulesets;
        },
        _compileRulesetPaths: function (rulesetNode) {
            if (rulesetNode.paths) {
                rulesetNode.paths = rulesetNode.paths
                    .filter(function (p) {
                    var i;
                    if (p[0].elements[0].combinator.value === ' ') {
                        p[0].elements[0].combinator = new (tree.Combinator)('');
                    }
                    for (i = 0; i < p.length; i++) {
                        if (p[i].isVisible() && p[i].getIsOutput()) {
                            return true;
                        }
                    }
                    return false;
                });
            }
        },
        _removeDuplicateRules: function (rules) {
            if (!rules) {
                return;
            }
            // remove duplicates
            var ruleCache = {}, ruleList, rule, i;
            for (i = rules.length - 1; i >= 0; i--) {
                rule = rules[i];
                if (rule instanceof tree.Declaration) {
                    if (!ruleCache[rule.name]) {
                        ruleCache[rule.name] = rule;
                    }
                    else {
                        ruleList = ruleCache[rule.name];
                        if (ruleList instanceof tree.Declaration) {
                            ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
                        }
                        var ruleCSS = rule.toCSS(this._context);
                        if (ruleList.indexOf(ruleCSS) !== -1) {
                            rules.splice(i, 1);
                        }
                        else {
                            ruleList.push(ruleCSS);
                        }
                    }
                }
            }
        },
        _mergeRules: function (rules) {
            if (!rules) {
                return;
            }
            var groups = {}, groupsArr = [];
            for (var i = 0; i < rules.length; i++) {
                var rule = rules[i];
                if (rule.merge) {
                    var key = rule.name;
                    groups[key] ? rules.splice(i--, 1) :
                        groupsArr.push(groups[key] = []);
                    groups[key].push(rule);
                }
            }
            groupsArr.forEach(function (group) {
                if (group.length > 0) {
                    var result = group[0], space = [], comma = [new tree.Expression(space)];
                    group.forEach(function (rule) {
                        if ((rule.merge === '+') && (space.length > 0)) {
                            comma.push(new tree.Expression(space = []));
                        }
                        space.push(rule.value);
                        result.important = result.important || rule.important;
                    });
                    result.value = new tree.Value(comma);
                }
            });
        }
    };
    module.exports = ToCSSVisitor;
}
,
/* less/lib/less/visitors/visitor */ function _(require, module, exports) {
    var tree = require(226) /* ../tree */;
    var _visitArgs = { visitDeeper: true }, _hasIndexed = false;
    function _noop(node) {
        return node;
    }
    function indexNodeTypes(parent, ticker) {
        // add .typeIndex to tree node types for lookup table
        var key, child;
        for (key in parent) {
            /* eslint guard-for-in: 0 */
            child = parent[key];
            switch (typeof child) {
                case "function":
                    // ignore bound functions directly on tree which do not have a prototype
                    // or aren't nodes
                    if (child.prototype && child.prototype.type) {
                        child.prototype.typeIndex = ticker++;
                    }
                    break;
                case "object":
                    ticker = indexNodeTypes(child, ticker);
                    break;
            }
        }
        return ticker;
    }
    var Visitor = function (implementation) {
        this._implementation = implementation;
        this._visitFnCache = [];
        if (!_hasIndexed) {
            indexNodeTypes(tree, 1);
            _hasIndexed = true;
        }
    };
    Visitor.prototype = {
        visit: function (node) {
            if (!node) {
                return node;
            }
            var nodeTypeIndex = node.typeIndex;
            if (!nodeTypeIndex) {
                return node;
            }
            var visitFnCache = this._visitFnCache, impl = this._implementation, aryIndx = nodeTypeIndex << 1, outAryIndex = aryIndx | 1, func = visitFnCache[aryIndx], funcOut = visitFnCache[outAryIndex], visitArgs = _visitArgs, fnName;
            visitArgs.visitDeeper = true;
            if (!func) {
                fnName = "visit" + node.type;
                func = impl[fnName] || _noop;
                funcOut = impl[fnName + "Out"] || _noop;
                visitFnCache[aryIndx] = func;
                visitFnCache[outAryIndex] = funcOut;
            }
            if (func !== _noop) {
                var newNode = func.call(impl, node, visitArgs);
                if (impl.isReplacing) {
                    node = newNode;
                }
            }
            if (visitArgs.visitDeeper && node && node.accept) {
                node.accept(this);
            }
            if (funcOut != _noop) {
                funcOut.call(impl, node);
            }
            return node;
        },
        visitArray: function (nodes, nonReplacing) {
            if (!nodes) {
                return nodes;
            }
            var cnt = nodes.length, i;
            // Non-replacing
            if (nonReplacing || !this._implementation.isReplacing) {
                for (i = 0; i < cnt; i++) {
                    this.visit(nodes[i]);
                }
                return nodes;
            }
            // Replacing
            var out = [];
            for (i = 0; i < cnt; i++) {
                var evald = this.visit(nodes[i]);
                if (evald === undefined) {
                    continue;
                }
                if (!evald.splice) {
                    out.push(evald);
                }
                else if (evald.length) {
                    this.flatten(evald, out);
                }
            }
            return out;
        },
        flatten: function (arr, out) {
            if (!out) {
                out = [];
            }
            var cnt, i, item, nestedCnt, j, nestedItem;
            for (i = 0, cnt = arr.length; i < cnt; i++) {
                item = arr[i];
                if (item === undefined) {
                    continue;
                }
                if (!item.splice) {
                    out.push(item);
                    continue;
                }
                for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
                    nestedItem = item[j];
                    if (nestedItem === undefined) {
                        continue;
                    }
                    if (!nestedItem.splice) {
                        out.push(nestedItem);
                    }
                    else if (nestedItem.length) {
                        this.flatten(nestedItem, out);
                    }
                }
            }
            return out;
        }
    };
    module.exports = Visitor;
}
,
/* less/node_modules/graceful-fs/fs */ function _(require, module, exports) {
    var fs = require('fs');
    module.exports = clone(fs);
    function clone(obj) {
        if (obj === null || typeof obj !== 'object')
            return obj;
        if (obj instanceof Object)
            var copy = { __proto__: obj.__proto__ };
        else
            var copy = Object.create(null);
        Object.getOwnPropertyNames(obj).forEach(function (key) {
            Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
        });
        return copy;
    }
}
,
/* less/node_modules/graceful-fs/graceful-fs */ function _(require, module, exports) {
    var fs = require('fs');
    var polyfills = require(259) /* ./polyfills.js */;
    var legacy = require(258) /* ./legacy-streams.js */;
    var queue = [];
    var util = require('util');
    function noop() { }
    var debug = noop;
    if (util.debuglog)
        debug = util.debuglog('gfs4');
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
        debug = function () {
            var m = util.format.apply(util, arguments);
            m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
            console.error(m);
        };
    if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
        process.on('exit', function () {
            debug(queue);
            require('assert').equal(queue.length, 0);
        });
    }
    module.exports = patch(require(256) /* ./fs.js */);
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) {
        module.exports = patch(fs);
    }
    // Always patch fs.close/closeSync, because we want to
    // retry() whenever a close happens *anywhere* in the program.
    // This is essential when multiple graceful-fs instances are
    // in play at the same time.
    module.exports.close =
        fs.close = (function (fs$close) {
            return function (fd, cb) {
                return fs$close.call(fs, fd, function (err) {
                    if (!err)
                        retry();
                    if (typeof cb === 'function')
                        cb.apply(this, arguments);
                });
            };
        })(fs.close);
    module.exports.closeSync =
        fs.closeSync = (function (fs$closeSync) {
            return function (fd) {
                // Note that graceful-fs also retries when fs.closeSync() fails.
                // Looks like a bug to me, although it's probably a harmless one.
                var rval = fs$closeSync.apply(fs, arguments);
                retry();
                return rval;
            };
        })(fs.closeSync);
    function patch(fs) {
        // Everything that references the open() function needs to be in here
        polyfills(fs);
        fs.gracefulify = patch;
        fs.FileReadStream = ReadStream; // Legacy name.
        fs.FileWriteStream = WriteStream; // Legacy name.
        fs.createReadStream = createReadStream;
        fs.createWriteStream = createWriteStream;
        var fs$readFile = fs.readFile;
        fs.readFile = readFile;
        function readFile(path, options, cb) {
            if (typeof options === 'function')
                cb = options, options = null;
            return go$readFile(path, options, cb);
            function go$readFile(path, options, cb) {
                return fs$readFile(path, options, function (err) {
                    if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
                        enqueue([go$readFile, [path, options, cb]]);
                    else {
                        if (typeof cb === 'function')
                            cb.apply(this, arguments);
                        retry();
                    }
                });
            }
        }
        var fs$writeFile = fs.writeFile;
        fs.writeFile = writeFile;
        function writeFile(path, data, options, cb) {
            if (typeof options === 'function')
                cb = options, options = null;
            return go$writeFile(path, data, options, cb);
            function go$writeFile(path, data, options, cb) {
                return fs$writeFile(path, data, options, function (err) {
                    if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
                        enqueue([go$writeFile, [path, data, options, cb]]);
                    else {
                        if (typeof cb === 'function')
                            cb.apply(this, arguments);
                        retry();
                    }
                });
            }
        }
        var fs$appendFile = fs.appendFile;
        if (fs$appendFile)
            fs.appendFile = appendFile;
        function appendFile(path, data, options, cb) {
            if (typeof options === 'function')
                cb = options, options = null;
            return go$appendFile(path, data, options, cb);
            function go$appendFile(path, data, options, cb) {
                return fs$appendFile(path, data, options, function (err) {
                    if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
                        enqueue([go$appendFile, [path, data, options, cb]]);
                    else {
                        if (typeof cb === 'function')
                            cb.apply(this, arguments);
                        retry();
                    }
                });
            }
        }
        var fs$readdir = fs.readdir;
        fs.readdir = readdir;
        function readdir(path, options, cb) {
            var args = [path];
            if (typeof options !== 'function') {
                args.push(options);
            }
            else {
                cb = options;
            }
            args.push(go$readdir$cb);
            return go$readdir(args);
            function go$readdir$cb(err, files) {
                if (files && files.sort)
                    files.sort();
                if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
                    enqueue([go$readdir, [args]]);
                else {
                    if (typeof cb === 'function')
                        cb.apply(this, arguments);
                    retry();
                }
            }
        }
        function go$readdir(args) {
            return fs$readdir.apply(fs, args);
        }
        if (process.version.substr(0, 4) === 'v0.8') {
            var legStreams = legacy(fs);
            ReadStream = legStreams.ReadStream;
            WriteStream = legStreams.WriteStream;
        }
        var fs$ReadStream = fs.ReadStream;
        ReadStream.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream.prototype.open = ReadStream$open;
        var fs$WriteStream = fs.WriteStream;
        WriteStream.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream.prototype.open = WriteStream$open;
        fs.ReadStream = ReadStream;
        fs.WriteStream = WriteStream;
        function ReadStream(path, options) {
            if (this instanceof ReadStream)
                return fs$ReadStream.apply(this, arguments), this;
            else
                return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
        }
        function ReadStream$open() {
            var that = this;
            open(that.path, that.flags, that.mode, function (err, fd) {
                if (err) {
                    if (that.autoClose)
                        that.destroy();
                    that.emit('error', err);
                }
                else {
                    that.fd = fd;
                    that.emit('open', fd);
                    that.read();
                }
            });
        }
        function WriteStream(path, options) {
            if (this instanceof WriteStream)
                return fs$WriteStream.apply(this, arguments), this;
            else
                return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
        }
        function WriteStream$open() {
            var that = this;
            open(that.path, that.flags, that.mode, function (err, fd) {
                if (err) {
                    that.destroy();
                    that.emit('error', err);
                }
                else {
                    that.fd = fd;
                    that.emit('open', fd);
                }
            });
        }
        function createReadStream(path, options) {
            return new ReadStream(path, options);
        }
        function createWriteStream(path, options) {
            return new WriteStream(path, options);
        }
        var fs$open = fs.open;
        fs.open = open;
        function open(path, flags, mode, cb) {
            if (typeof mode === 'function')
                cb = mode, mode = null;
            return go$open(path, flags, mode, cb);
            function go$open(path, flags, mode, cb) {
                return fs$open(path, flags, mode, function (err, fd) {
                    if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
                        enqueue([go$open, [path, flags, mode, cb]]);
                    else {
                        if (typeof cb === 'function')
                            cb.apply(this, arguments);
                        retry();
                    }
                });
            }
        }
        return fs;
    }
    function enqueue(elem) {
        debug('ENQUEUE', elem[0].name, elem[1]);
        queue.push(elem);
    }
    function retry() {
        var elem = queue.shift();
        if (elem) {
            debug('RETRY', elem[0].name, elem[1]);
            elem[0].apply(null, elem[1]);
        }
    }
}
,
/* less/node_modules/graceful-fs/legacy-streams */ function _(require, module, exports) {
    var Stream = require('stream').Stream;
    module.exports = legacy;
    function legacy(fs) {
        return {
            ReadStream: ReadStream,
            WriteStream: WriteStream
        };
        function ReadStream(path, options) {
            if (!(this instanceof ReadStream))
                return new ReadStream(path, options);
            Stream.call(this);
            var self = this;
            this.path = path;
            this.fd = null;
            this.readable = true;
            this.paused = false;
            this.flags = 'r';
            this.mode = 438; /*=0666*/
            this.bufferSize = 64 * 1024;
            options = options || {};
            // Mixin options into this
            var keys = Object.keys(options);
            for (var index = 0, length = keys.length; index < length; index++) {
                var key = keys[index];
                this[key] = options[key];
            }
            if (this.encoding)
                this.setEncoding(this.encoding);
            if (this.start !== undefined) {
                if ('number' !== typeof this.start) {
                    throw TypeError('start must be a Number');
                }
                if (this.end === undefined) {
                    this.end = Infinity;
                }
                else if ('number' !== typeof this.end) {
                    throw TypeError('end must be a Number');
                }
                if (this.start > this.end) {
                    throw new Error('start must be <= end');
                }
                this.pos = this.start;
            }
            if (this.fd !== null) {
                process.nextTick(function () {
                    self._read();
                });
                return;
            }
            fs.open(this.path, this.flags, this.mode, function (err, fd) {
                if (err) {
                    self.emit('error', err);
                    self.readable = false;
                    return;
                }
                self.fd = fd;
                self.emit('open', fd);
                self._read();
            });
        }
        function WriteStream(path, options) {
            if (!(this instanceof WriteStream))
                return new WriteStream(path, options);
            Stream.call(this);
            this.path = path;
            this.fd = null;
            this.writable = true;
            this.flags = 'w';
            this.encoding = 'binary';
            this.mode = 438; /*=0666*/
            this.bytesWritten = 0;
            options = options || {};
            // Mixin options into this
            var keys = Object.keys(options);
            for (var index = 0, length = keys.length; index < length; index++) {
                var key = keys[index];
                this[key] = options[key];
            }
            if (this.start !== undefined) {
                if ('number' !== typeof this.start) {
                    throw TypeError('start must be a Number');
                }
                if (this.start < 0) {
                    throw new Error('start must be >= zero');
                }
                this.pos = this.start;
            }
            this.busy = false;
            this._queue = [];
            if (this.fd === null) {
                this._open = fs.open;
                this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
                this.flush();
            }
        }
    }
}
,
/* less/node_modules/graceful-fs/polyfills */ function _(require, module, exports) {
    var fs = require(256) /* ./fs.js */;
    var constants = require('constants');
    var origCwd = process.cwd;
    var cwd = null;
    var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function () {
        if (!cwd)
            cwd = origCwd.call(process);
        return cwd;
    };
    try {
        process.cwd();
    }
    catch (er) { }
    var chdir = process.chdir;
    process.chdir = function (d) {
        cwd = null;
        chdir.call(process, d);
    };
    module.exports = patch;
    function patch(fs) {
        // (re-)implement some things that are known busted or missing.
        // lchmod, broken prior to 0.6.2
        // back-port the fix here.
        if (constants.hasOwnProperty('O_SYMLINK') &&
            process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
            patchLchmod(fs);
        }
        // lutimes implementation, or no-op
        if (!fs.lutimes) {
            patchLutimes(fs);
        }
        // https://github.com/isaacs/node-graceful-fs/issues/4
        // Chown should not fail on einval or eperm if non-root.
        // It should not fail on enosys ever, as this just indicates
        // that a fs doesn't support the intended operation.
        fs.chown = chownFix(fs.chown);
        fs.fchown = chownFix(fs.fchown);
        fs.lchown = chownFix(fs.lchown);
        fs.chmod = chmodFix(fs.chmod);
        fs.fchmod = chmodFix(fs.fchmod);
        fs.lchmod = chmodFix(fs.lchmod);
        fs.chownSync = chownFixSync(fs.chownSync);
        fs.fchownSync = chownFixSync(fs.fchownSync);
        fs.lchownSync = chownFixSync(fs.lchownSync);
        fs.chmodSync = chmodFixSync(fs.chmodSync);
        fs.fchmodSync = chmodFixSync(fs.fchmodSync);
        fs.lchmodSync = chmodFixSync(fs.lchmodSync);
        fs.stat = statFix(fs.stat);
        fs.fstat = statFix(fs.fstat);
        fs.lstat = statFix(fs.lstat);
        fs.statSync = statFixSync(fs.statSync);
        fs.fstatSync = statFixSync(fs.fstatSync);
        fs.lstatSync = statFixSync(fs.lstatSync);
        // if lchmod/lchown do not exist, then make them no-ops
        if (!fs.lchmod) {
            fs.lchmod = function (path, mode, cb) {
                if (cb)
                    process.nextTick(cb);
            };
            fs.lchmodSync = function () { };
        }
        if (!fs.lchown) {
            fs.lchown = function (path, uid, gid, cb) {
                if (cb)
                    process.nextTick(cb);
            };
            fs.lchownSync = function () { };
        }
        // on Windows, A/V software can lock the directory, causing this
        // to fail with an EACCES or EPERM if the directory contains newly
        // created files.  Try again on failure, for up to 60 seconds.
        // Set the timeout this long because some Windows Anti-Virus, such as Parity
        // bit9, may lock files for up to a minute, causing npm package install
        // failures. Also, take care to yield the scheduler. Windows scheduling gives
        // CPU to a busy looping process, which can cause the program causing the lock
        // contention to be starved of CPU by node, so the contention doesn't resolve.
        if (platform === "win32") {
            fs.rename = (function (fs$rename) {
                return function (from, to, cb) {
                    var start = Date.now();
                    var backoff = 0;
                    fs$rename(from, to, function CB(er) {
                        if (er
                            && (er.code === "EACCES" || er.code === "EPERM")
                            && Date.now() - start < 60000) {
                            setTimeout(function () {
                                fs.stat(to, function (stater, st) {
                                    if (stater && stater.code === "ENOENT")
                                        fs$rename(from, to, CB);
                                    else
                                        cb(er);
                                });
                            }, backoff);
                            if (backoff < 100)
                                backoff += 10;
                            return;
                        }
                        if (cb)
                            cb(er);
                    });
                };
            })(fs.rename);
        }
        // if read() returns EAGAIN, then just try it again.
        fs.read = (function (fs$read) {
            return function (fd, buffer, offset, length, position, callback_) {
                var callback;
                if (callback_ && typeof callback_ === 'function') {
                    var eagCounter = 0;
                    callback = function (er, _, __) {
                        if (er && er.code === 'EAGAIN' && eagCounter < 10) {
                            eagCounter++;
                            return fs$read.call(fs, fd, buffer, offset, length, position, callback);
                        }
                        callback_.apply(this, arguments);
                    };
                }
                return fs$read.call(fs, fd, buffer, offset, length, position, callback);
            };
        })(fs.read);
        fs.readSync = (function (fs$readSync) {
            return function (fd, buffer, offset, length, position) {
                var eagCounter = 0;
                while (true) {
                    try {
                        return fs$readSync.call(fs, fd, buffer, offset, length, position);
                    }
                    catch (er) {
                        if (er.code === 'EAGAIN' && eagCounter < 10) {
                            eagCounter++;
                            continue;
                        }
                        throw er;
                    }
                }
            };
        })(fs.readSync);
    }
    function patchLchmod(fs) {
        fs.lchmod = function (path, mode, callback) {
            fs.open(path, constants.O_WRONLY | constants.O_SYMLINK, mode, function (err, fd) {
                if (err) {
                    if (callback)
                        callback(err);
                    return;
                }
                // prefer to return the chmod error, if one occurs,
                // but still try to close, and report closing errors if they occur.
                fs.fchmod(fd, mode, function (err) {
                    fs.close(fd, function (err2) {
                        if (callback)
                            callback(err || err2);
                    });
                });
            });
        };
        fs.lchmodSync = function (path, mode) {
            var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
            // prefer to return the chmod error, if one occurs,
            // but still try to close, and report closing errors if they occur.
            var threw = true;
            var ret;
            try {
                ret = fs.fchmodSync(fd, mode);
                threw = false;
            }
            finally {
                if (threw) {
                    try {
                        fs.closeSync(fd);
                    }
                    catch (er) { }
                }
                else {
                    fs.closeSync(fd);
                }
            }
            return ret;
        };
    }
    function patchLutimes(fs) {
        if (constants.hasOwnProperty("O_SYMLINK")) {
            fs.lutimes = function (path, at, mt, cb) {
                fs.open(path, constants.O_SYMLINK, function (er, fd) {
                    if (er) {
                        if (cb)
                            cb(er);
                        return;
                    }
                    fs.futimes(fd, at, mt, function (er) {
                        fs.close(fd, function (er2) {
                            if (cb)
                                cb(er || er2);
                        });
                    });
                });
            };
            fs.lutimesSync = function (path, at, mt) {
                var fd = fs.openSync(path, constants.O_SYMLINK);
                var ret;
                var threw = true;
                try {
                    ret = fs.futimesSync(fd, at, mt);
                    threw = false;
                }
                finally {
                    if (threw) {
                        try {
                            fs.closeSync(fd);
                        }
                        catch (er) { }
                    }
                    else {
                        fs.closeSync(fd);
                    }
                }
                return ret;
            };
        }
        else {
            fs.lutimes = function (_a, _b, _c, cb) { if (cb)
                process.nextTick(cb); };
            fs.lutimesSync = function () { };
        }
    }
    function chmodFix(orig) {
        if (!orig)
            return orig;
        return function (target, mode, cb) {
            return orig.call(fs, target, mode, function (er) {
                if (chownErOk(er))
                    er = null;
                if (cb)
                    cb.apply(this, arguments);
            });
        };
    }
    function chmodFixSync(orig) {
        if (!orig)
            return orig;
        return function (target, mode) {
            try {
                return orig.call(fs, target, mode);
            }
            catch (er) {
                if (!chownErOk(er))
                    throw er;
            }
        };
    }
    function chownFix(orig) {
        if (!orig)
            return orig;
        return function (target, uid, gid, cb) {
            return orig.call(fs, target, uid, gid, function (er) {
                if (chownErOk(er))
                    er = null;
                if (cb)
                    cb.apply(this, arguments);
            });
        };
    }
    function chownFixSync(orig) {
        if (!orig)
            return orig;
        return function (target, uid, gid) {
            try {
                return orig.call(fs, target, uid, gid);
            }
            catch (er) {
                if (!chownErOk(er))
                    throw er;
            }
        };
    }
    function statFix(orig) {
        if (!orig)
            return orig;
        // Older versions of Node erroneously returned signed integers for
        // uid + gid.
        return function (target, cb) {
            return orig.call(fs, target, function (er, stats) {
                if (!stats)
                    return cb.apply(this, arguments);
                if (stats.uid < 0)
                    stats.uid += 0x100000000;
                if (stats.gid < 0)
                    stats.gid += 0x100000000;
                if (cb)
                    cb.apply(this, arguments);
            });
        };
    }
    function statFixSync(orig) {
        if (!orig)
            return orig;
        // Older versions of Node erroneously returned signed integers for
        // uid + gid.
        return function (target) {
            var stats = orig.call(fs, target);
            if (stats.uid < 0)
                stats.uid += 0x100000000;
            if (stats.gid < 0)
                stats.gid += 0x100000000;
            return stats;
        };
    }
    // ENOSYS means that the fs doesn't support the op. Just ignore
    // that, because it doesn't matter.
    //
    // if there's no getuid, or if getuid() is something other
    // than 0, and the error is EINVAL or EPERM, then just ignore
    // it.
    //
    // This specific case is a silent failure in cp, install, tar,
    // and most other unix tools that manage permissions.
    //
    // When running as root, or if other types of errors are
    // encountered, then it's strict.
    function chownErOk(er) {
        if (!er)
            return true;
        if (er.code === "ENOSYS")
            return true;
        var nonroot = !process.getuid || process.getuid() !== 0;
        if (nonroot) {
            if (er.code === "EINVAL" || er.code === "EPERM")
                return true;
        }
        return false;
    }
}
,
/* locate-path/index */ function _(require, module, exports) {
    const path = require('path');
    const pathExists = require(276) /* path-exists */;
    const pLocate = require(274) /* p-locate */;
    module.exports = (iterable, opts) => {
        opts = Object.assign({
            cwd: process.cwd()
        }, opts);
        return pLocate(iterable, el => pathExists(path.resolve(opts.cwd, el)), opts);
    };
    module.exports.sync = (iterable, opts) => {
        opts = Object.assign({
            cwd: process.cwd()
        }, opts);
        for (const el of iterable) {
            if (pathExists.sync(path.resolve(opts.cwd, el))) {
                return el;
            }
        }
    };
}
,
/* longest/index */ function _(require, module, exports) {
    module.exports = function (arr) {
        if (!arr) {
            return null;
        }
        var len = arr.length;
        if (!len) {
            return null;
        }
        var c = 0;
        var i = 0;
        var ele;
        var elen;
        var res;
        for (; i < len; i++) {
            ele = arr[i].toString();
            elen = ele.length;
            if (elen > c) {
                res = ele;
                c = elen;
            }
        }
        return res;
    };
}
,
/* mem/index */ function _(require, module, exports) {
    const mimicFn = require(268) /* mimic-fn */;
    const cacheStore = new WeakMap();
    const defaultCacheKey = function (x) {
        if (arguments.length === 1 && (x === null || x === undefined || (typeof x !== 'function' && typeof x !== 'object'))) {
            return x;
        }
        return JSON.stringify(arguments);
    };
    module.exports = (fn, opts) => {
        opts = Object.assign({
            cacheKey: defaultCacheKey,
            cache: new Map()
        }, opts);
        const memoized = function () {
            const cache = cacheStore.get(memoized);
            const key = opts.cacheKey.apply(null, arguments);
            if (cache.has(key)) {
                const c = cache.get(key);
                if (typeof opts.maxAge !== 'number' || Date.now() < c.maxAge) {
                    return c.data;
                }
            }
            const ret = fn.apply(null, arguments);
            cache.set(key, {
                data: ret,
                maxAge: Date.now() + (opts.maxAge || 0)
            });
            return ret;
        };
        mimicFn(memoized, fn);
        cacheStore.set(memoized, opts.cache);
        return memoized;
    };
    module.exports.clear = fn => {
        const cache = cacheStore.get(fn);
        if (cache && typeof cache.clear === 'function') {
            cache.clear();
        }
    };
}
,
/* mime-db/db.json */ function _(require, module, exports) {
    {
        "application/1d-interleaved-parityfec";
        {
            "source";
            "iana";
        }
        "application/3gpdash-qoe-report+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/3gpp-ims+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/a2l";
        {
            "source";
            "iana";
        }
        "application/activemessage";
        {
            "source";
            "iana";
        }
        "application/activity+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-costmap+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-costmapfilter+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-directory+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-endpointcost+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-endpointcostparams+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-endpointprop+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-endpointpropparams+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-error+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-networkmap+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/alto-networkmapfilter+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/aml";
        {
            "source";
            "iana";
        }
        "application/andrew-inset";
        {
            "source";
            "iana",
                "extensions";
            ["ez"];
        }
        "application/applefile";
        {
            "source";
            "iana";
        }
        "application/applixware";
        {
            "source";
            "apache",
                "extensions";
            ["aw"];
        }
        "application/atf";
        {
            "source";
            "iana";
        }
        "application/atfx";
        {
            "source";
            "iana";
        }
        "application/atom+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["atom"];
        }
        "application/atomcat+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["atomcat"];
        }
        "application/atomdeleted+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/atomicmail";
        {
            "source";
            "iana";
        }
        "application/atomsvc+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["atomsvc"];
        }
        "application/atxml";
        {
            "source";
            "iana";
        }
        "application/auth-policy+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/bacnet-xdd+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/batch-smtp";
        {
            "source";
            "iana";
        }
        "application/bdoc";
        {
            "compressible";
            false,
                "extensions";
            ["bdoc"];
        }
        "application/beep+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/calendar+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/calendar+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/call-completion";
        {
            "source";
            "iana";
        }
        "application/cals-1840";
        {
            "source";
            "iana";
        }
        "application/cbor";
        {
            "source";
            "iana";
        }
        "application/cccex";
        {
            "source";
            "iana";
        }
        "application/ccmp+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/ccxml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["ccxml"];
        }
        "application/cdfx+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/cdmi-capability";
        {
            "source";
            "iana",
                "extensions";
            ["cdmia"];
        }
        "application/cdmi-container";
        {
            "source";
            "iana",
                "extensions";
            ["cdmic"];
        }
        "application/cdmi-domain";
        {
            "source";
            "iana",
                "extensions";
            ["cdmid"];
        }
        "application/cdmi-object";
        {
            "source";
            "iana",
                "extensions";
            ["cdmio"];
        }
        "application/cdmi-queue";
        {
            "source";
            "iana",
                "extensions";
            ["cdmiq"];
        }
        "application/cdni";
        {
            "source";
            "iana";
        }
        "application/cea";
        {
            "source";
            "iana";
        }
        "application/cea-2018+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/cellml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/cfw";
        {
            "source";
            "iana";
        }
        "application/clue_info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/cms";
        {
            "source";
            "iana";
        }
        "application/cnrp+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/coap-group+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/coap-payload";
        {
            "source";
            "iana";
        }
        "application/commonground";
        {
            "source";
            "iana";
        }
        "application/conference-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/cose";
        {
            "source";
            "iana";
        }
        "application/cose-key";
        {
            "source";
            "iana";
        }
        "application/cose-key-set";
        {
            "source";
            "iana";
        }
        "application/cpl+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/csrattrs";
        {
            "source";
            "iana";
        }
        "application/csta+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/cstadata+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/csvm+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/cu-seeme";
        {
            "source";
            "apache",
                "extensions";
            ["cu"];
        }
        "application/cwt";
        {
            "source";
            "iana";
        }
        "application/cybercash";
        {
            "source";
            "iana";
        }
        "application/dart";
        {
            "compressible";
            true;
        }
        "application/dash+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mpd"];
        }
        "application/dashdelta";
        {
            "source";
            "iana";
        }
        "application/davmount+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["davmount"];
        }
        "application/dca-rft";
        {
            "source";
            "iana";
        }
        "application/dcd";
        {
            "source";
            "iana";
        }
        "application/dec-dx";
        {
            "source";
            "iana";
        }
        "application/dialog-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/dicom";
        {
            "source";
            "iana";
        }
        "application/dicom+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/dicom+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/dii";
        {
            "source";
            "iana";
        }
        "application/dit";
        {
            "source";
            "iana";
        }
        "application/dns";
        {
            "source";
            "iana";
        }
        "application/dns+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/docbook+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["dbk"];
        }
        "application/dskpp+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/dssc+der";
        {
            "source";
            "iana",
                "extensions";
            ["dssc"];
        }
        "application/dssc+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xdssc"];
        }
        "application/dvcs";
        {
            "source";
            "iana";
        }
        "application/ecmascript";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["ecma", "es"];
        }
        "application/edi-consent";
        {
            "source";
            "iana";
        }
        "application/edi-x12";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/edifact";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/efi";
        {
            "source";
            "iana";
        }
        "application/emergencycalldata.comment+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/emergencycalldata.control+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/emergencycalldata.deviceinfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/emergencycalldata.ecall.msd";
        {
            "source";
            "iana";
        }
        "application/emergencycalldata.providerinfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/emergencycalldata.serviceinfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/emergencycalldata.subscriberinfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/emergencycalldata.veds+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/emma+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["emma"];
        }
        "application/emotionml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/encaprtp";
        {
            "source";
            "iana";
        }
        "application/epp+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/epub+zip";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["epub"];
        }
        "application/eshop";
        {
            "source";
            "iana";
        }
        "application/exi";
        {
            "source";
            "iana",
                "extensions";
            ["exi"];
        }
        "application/fastinfoset";
        {
            "source";
            "iana";
        }
        "application/fastsoap";
        {
            "source";
            "iana";
        }
        "application/fdt+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/fhir+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/fhir+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/fido.trusted-apps+json";
        {
            "compressible";
            true;
        }
        "application/fits";
        {
            "source";
            "iana";
        }
        "application/font-sfnt";
        {
            "source";
            "iana";
        }
        "application/font-tdpfr";
        {
            "source";
            "iana",
                "extensions";
            ["pfr"];
        }
        "application/font-woff";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/framework-attributes+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/geo+json";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["geojson"];
        }
        "application/geo+json-seq";
        {
            "source";
            "iana";
        }
        "application/geopackage+sqlite3";
        {
            "source";
            "iana";
        }
        "application/geoxacml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/gltf-buffer";
        {
            "source";
            "iana";
        }
        "application/gml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["gml"];
        }
        "application/gpx+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["gpx"];
        }
        "application/gxf";
        {
            "source";
            "apache",
                "extensions";
            ["gxf"];
        }
        "application/gzip";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["gz"];
        }
        "application/h224";
        {
            "source";
            "iana";
        }
        "application/held+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/hjson";
        {
            "extensions";
            ["hjson"];
        }
        "application/http";
        {
            "source";
            "iana";
        }
        "application/hyperstudio";
        {
            "source";
            "iana",
                "extensions";
            ["stk"];
        }
        "application/ibe-key-request+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/ibe-pkg-reply+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/ibe-pp-data";
        {
            "source";
            "iana";
        }
        "application/iges";
        {
            "source";
            "iana";
        }
        "application/im-iscomposing+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/index";
        {
            "source";
            "iana";
        }
        "application/index.cmd";
        {
            "source";
            "iana";
        }
        "application/index.obj";
        {
            "source";
            "iana";
        }
        "application/index.response";
        {
            "source";
            "iana";
        }
        "application/index.vnd";
        {
            "source";
            "iana";
        }
        "application/inkml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["ink", "inkml"];
        }
        "application/iotp";
        {
            "source";
            "iana";
        }
        "application/ipfix";
        {
            "source";
            "iana",
                "extensions";
            ["ipfix"];
        }
        "application/ipp";
        {
            "source";
            "iana";
        }
        "application/isup";
        {
            "source";
            "iana";
        }
        "application/its+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/java-archive";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["jar", "war", "ear"];
        }
        "application/java-serialized-object";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["ser"];
        }
        "application/java-vm";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["class"];
        }
        "application/javascript";
        {
            "source";
            "iana",
                "charset";
            "UTF-8",
                "compressible";
            true,
                "extensions";
            ["js", "mjs"];
        }
        "application/jf2feed+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/jose";
        {
            "source";
            "iana";
        }
        "application/jose+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/jrd+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/json";
        {
            "source";
            "iana",
                "charset";
            "UTF-8",
                "compressible";
            true,
                "extensions";
            ["json", "map"];
        }
        "application/json-patch+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/json-seq";
        {
            "source";
            "iana";
        }
        "application/json5";
        {
            "extensions";
            ["json5"];
        }
        "application/jsonml+json";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["jsonml"];
        }
        "application/jwk+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/jwk-set+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/jwt";
        {
            "source";
            "iana";
        }
        "application/kpml-request+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/kpml-response+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/ld+json";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["jsonld"];
        }
        "application/lgr+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/link-format";
        {
            "source";
            "iana";
        }
        "application/load-control+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/lost+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["lostxml"];
        }
        "application/lostsync+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/lxf";
        {
            "source";
            "iana";
        }
        "application/mac-binhex40";
        {
            "source";
            "iana",
                "extensions";
            ["hqx"];
        }
        "application/mac-compactpro";
        {
            "source";
            "apache",
                "extensions";
            ["cpt"];
        }
        "application/macwriteii";
        {
            "source";
            "iana";
        }
        "application/mads+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mads"];
        }
        "application/manifest+json";
        {
            "charset";
            "UTF-8",
                "compressible";
            true,
                "extensions";
            ["webmanifest"];
        }
        "application/marc";
        {
            "source";
            "iana",
                "extensions";
            ["mrc"];
        }
        "application/marcxml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mrcx"];
        }
        "application/mathematica";
        {
            "source";
            "iana",
                "extensions";
            ["ma", "nb", "mb"];
        }
        "application/mathml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mathml"];
        }
        "application/mathml-content+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mathml-presentation+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-associated-procedure-description+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-deregister+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-envelope+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-msk+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-msk-response+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-protection-description+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-reception-report+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-register+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-register-response+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-schedule+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbms-user-service-description+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mbox";
        {
            "source";
            "iana",
                "extensions";
            ["mbox"];
        }
        "application/media-policy-dataset+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/media_control+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mediaservercontrol+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mscml"];
        }
        "application/merge-patch+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/metalink+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["metalink"];
        }
        "application/metalink4+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["meta4"];
        }
        "application/mets+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mets"];
        }
        "application/mf4";
        {
            "source";
            "iana";
        }
        "application/mikey";
        {
            "source";
            "iana";
        }
        "application/mmt-usd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mods+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mods"];
        }
        "application/moss-keys";
        {
            "source";
            "iana";
        }
        "application/moss-signature";
        {
            "source";
            "iana";
        }
        "application/mosskey-data";
        {
            "source";
            "iana";
        }
        "application/mosskey-request";
        {
            "source";
            "iana";
        }
        "application/mp21";
        {
            "source";
            "iana",
                "extensions";
            ["m21", "mp21"];
        }
        "application/mp4";
        {
            "source";
            "iana",
                "extensions";
            ["mp4s", "m4p"];
        }
        "application/mpeg4-generic";
        {
            "source";
            "iana";
        }
        "application/mpeg4-iod";
        {
            "source";
            "iana";
        }
        "application/mpeg4-iod-xmt";
        {
            "source";
            "iana";
        }
        "application/mrb-consumer+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mrb-publish+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/msc-ivr+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/msc-mixer+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/msword";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["doc", "dot"];
        }
        "application/mud+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/mxf";
        {
            "source";
            "iana",
                "extensions";
            ["mxf"];
        }
        "application/n-quads";
        {
            "source";
            "iana";
        }
        "application/n-triples";
        {
            "source";
            "iana";
        }
        "application/nasdata";
        {
            "source";
            "iana";
        }
        "application/news-checkgroups";
        {
            "source";
            "iana";
        }
        "application/news-groupinfo";
        {
            "source";
            "iana";
        }
        "application/news-transmission";
        {
            "source";
            "iana";
        }
        "application/nlsml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/node";
        {
            "source";
            "iana";
        }
        "application/nss";
        {
            "source";
            "iana";
        }
        "application/ocsp-request";
        {
            "source";
            "iana";
        }
        "application/ocsp-response";
        {
            "source";
            "iana";
        }
        "application/octet-stream";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"];
        }
        "application/oda";
        {
            "source";
            "iana",
                "extensions";
            ["oda"];
        }
        "application/odx";
        {
            "source";
            "iana";
        }
        "application/oebps-package+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["opf"];
        }
        "application/ogg";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["ogx"];
        }
        "application/omdoc+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["omdoc"];
        }
        "application/onenote";
        {
            "source";
            "apache",
                "extensions";
            ["onetoc", "onetoc2", "onetmp", "onepkg"];
        }
        "application/oxps";
        {
            "source";
            "iana",
                "extensions";
            ["oxps"];
        }
        "application/p2p-overlay+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/parityfec";
        {
            "source";
            "iana";
        }
        "application/passport";
        {
            "source";
            "iana";
        }
        "application/patch-ops-error+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xer"];
        }
        "application/pdf";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["pdf"];
        }
        "application/pdx";
        {
            "source";
            "iana";
        }
        "application/pgp-encrypted";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["pgp"];
        }
        "application/pgp-keys";
        {
            "source";
            "iana";
        }
        "application/pgp-signature";
        {
            "source";
            "iana",
                "extensions";
            ["asc", "sig"];
        }
        "application/pics-rules";
        {
            "source";
            "apache",
                "extensions";
            ["prf"];
        }
        "application/pidf+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/pidf-diff+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/pkcs10";
        {
            "source";
            "iana",
                "extensions";
            ["p10"];
        }
        "application/pkcs12";
        {
            "source";
            "iana";
        }
        "application/pkcs7-mime";
        {
            "source";
            "iana",
                "extensions";
            ["p7m", "p7c"];
        }
        "application/pkcs7-signature";
        {
            "source";
            "iana",
                "extensions";
            ["p7s"];
        }
        "application/pkcs8";
        {
            "source";
            "iana",
                "extensions";
            ["p8"];
        }
        "application/pkcs8-encrypted";
        {
            "source";
            "iana";
        }
        "application/pkix-attr-cert";
        {
            "source";
            "iana",
                "extensions";
            ["ac"];
        }
        "application/pkix-cert";
        {
            "source";
            "iana",
                "extensions";
            ["cer"];
        }
        "application/pkix-crl";
        {
            "source";
            "iana",
                "extensions";
            ["crl"];
        }
        "application/pkix-pkipath";
        {
            "source";
            "iana",
                "extensions";
            ["pkipath"];
        }
        "application/pkixcmp";
        {
            "source";
            "iana",
                "extensions";
            ["pki"];
        }
        "application/pls+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["pls"];
        }
        "application/poc-settings+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/postscript";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["ai", "eps", "ps"];
        }
        "application/ppsp-tracker+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/problem+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/problem+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/provenance+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/prs.alvestrand.titrax-sheet";
        {
            "source";
            "iana";
        }
        "application/prs.cww";
        {
            "source";
            "iana",
                "extensions";
            ["cww"];
        }
        "application/prs.hpub+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/prs.nprend";
        {
            "source";
            "iana";
        }
        "application/prs.plucker";
        {
            "source";
            "iana";
        }
        "application/prs.rdf-xml-crypt";
        {
            "source";
            "iana";
        }
        "application/prs.xsf+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/pskc+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["pskcxml"];
        }
        "application/qsig";
        {
            "source";
            "iana";
        }
        "application/raml+yaml";
        {
            "compressible";
            true,
                "extensions";
            ["raml"];
        }
        "application/raptorfec";
        {
            "source";
            "iana";
        }
        "application/rdap+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/rdf+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rdf", "owl"];
        }
        "application/reginfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rif"];
        }
        "application/relax-ng-compact-syntax";
        {
            "source";
            "iana",
                "extensions";
            ["rnc"];
        }
        "application/remote-printing";
        {
            "source";
            "iana";
        }
        "application/reputon+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/resource-lists+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rl"];
        }
        "application/resource-lists-diff+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rld"];
        }
        "application/rfc+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/riscos";
        {
            "source";
            "iana";
        }
        "application/rlmi+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/rls-services+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rs"];
        }
        "application/route-apd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/route-s-tsid+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/route-usd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/rpki-ghostbusters";
        {
            "source";
            "iana",
                "extensions";
            ["gbr"];
        }
        "application/rpki-manifest";
        {
            "source";
            "iana",
                "extensions";
            ["mft"];
        }
        "application/rpki-publication";
        {
            "source";
            "iana";
        }
        "application/rpki-roa";
        {
            "source";
            "iana",
                "extensions";
            ["roa"];
        }
        "application/rpki-updown";
        {
            "source";
            "iana";
        }
        "application/rsd+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["rsd"];
        }
        "application/rss+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["rss"];
        }
        "application/rtf";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rtf"];
        }
        "application/rtploopback";
        {
            "source";
            "iana";
        }
        "application/rtx";
        {
            "source";
            "iana";
        }
        "application/samlassertion+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/samlmetadata+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/sbml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["sbml"];
        }
        "application/scaip+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/scim+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/scvp-cv-request";
        {
            "source";
            "iana",
                "extensions";
            ["scq"];
        }
        "application/scvp-cv-response";
        {
            "source";
            "iana",
                "extensions";
            ["scs"];
        }
        "application/scvp-vp-request";
        {
            "source";
            "iana",
                "extensions";
            ["spq"];
        }
        "application/scvp-vp-response";
        {
            "source";
            "iana",
                "extensions";
            ["spp"];
        }
        "application/sdp";
        {
            "source";
            "iana",
                "extensions";
            ["sdp"];
        }
        "application/secevent+jwt";
        {
            "source";
            "iana";
        }
        "application/senml+cbor";
        {
            "source";
            "iana";
        }
        "application/senml+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/senml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/senml-exi";
        {
            "source";
            "iana";
        }
        "application/sensml+cbor";
        {
            "source";
            "iana";
        }
        "application/sensml+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/sensml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/sensml-exi";
        {
            "source";
            "iana";
        }
        "application/sep+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/sep-exi";
        {
            "source";
            "iana";
        }
        "application/session-info";
        {
            "source";
            "iana";
        }
        "application/set-payment";
        {
            "source";
            "iana";
        }
        "application/set-payment-initiation";
        {
            "source";
            "iana",
                "extensions";
            ["setpay"];
        }
        "application/set-registration";
        {
            "source";
            "iana";
        }
        "application/set-registration-initiation";
        {
            "source";
            "iana",
                "extensions";
            ["setreg"];
        }
        "application/sgml";
        {
            "source";
            "iana";
        }
        "application/sgml-open-catalog";
        {
            "source";
            "iana";
        }
        "application/shf+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["shf"];
        }
        "application/sieve";
        {
            "source";
            "iana";
        }
        "application/simple-filter+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/simple-message-summary";
        {
            "source";
            "iana";
        }
        "application/simplesymbolcontainer";
        {
            "source";
            "iana";
        }
        "application/slate";
        {
            "source";
            "iana";
        }
        "application/smil";
        {
            "source";
            "iana";
        }
        "application/smil+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["smi", "smil"];
        }
        "application/smpte336m";
        {
            "source";
            "iana";
        }
        "application/soap+fastinfoset";
        {
            "source";
            "iana";
        }
        "application/soap+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/sparql-query";
        {
            "source";
            "iana",
                "extensions";
            ["rq"];
        }
        "application/sparql-results+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["srx"];
        }
        "application/spirits-event+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/sql";
        {
            "source";
            "iana";
        }
        "application/srgs";
        {
            "source";
            "iana",
                "extensions";
            ["gram"];
        }
        "application/srgs+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["grxml"];
        }
        "application/sru+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["sru"];
        }
        "application/ssdl+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["ssdl"];
        }
        "application/ssml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["ssml"];
        }
        "application/stix+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/tamp-apex-update";
        {
            "source";
            "iana";
        }
        "application/tamp-apex-update-confirm";
        {
            "source";
            "iana";
        }
        "application/tamp-community-update";
        {
            "source";
            "iana";
        }
        "application/tamp-community-update-confirm";
        {
            "source";
            "iana";
        }
        "application/tamp-error";
        {
            "source";
            "iana";
        }
        "application/tamp-sequence-adjust";
        {
            "source";
            "iana";
        }
        "application/tamp-sequence-adjust-confirm";
        {
            "source";
            "iana";
        }
        "application/tamp-status-query";
        {
            "source";
            "iana";
        }
        "application/tamp-status-response";
        {
            "source";
            "iana";
        }
        "application/tamp-update";
        {
            "source";
            "iana";
        }
        "application/tamp-update-confirm";
        {
            "source";
            "iana";
        }
        "application/tar";
        {
            "compressible";
            true;
        }
        "application/taxii+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/tei+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["tei", "teicorpus"];
        }
        "application/thraud+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["tfi"];
        }
        "application/timestamp-query";
        {
            "source";
            "iana";
        }
        "application/timestamp-reply";
        {
            "source";
            "iana";
        }
        "application/timestamped-data";
        {
            "source";
            "iana",
                "extensions";
            ["tsd"];
        }
        "application/tlsrpt+gzip";
        {
            "source";
            "iana";
        }
        "application/tlsrpt+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/tnauthlist";
        {
            "source";
            "iana";
        }
        "application/trickle-ice-sdpfrag";
        {
            "source";
            "iana";
        }
        "application/trig";
        {
            "source";
            "iana";
        }
        "application/ttml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/tve-trigger";
        {
            "source";
            "iana";
        }
        "application/ulpfec";
        {
            "source";
            "iana";
        }
        "application/urc-grpsheet+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/urc-ressheet+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/urc-targetdesc+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/urc-uisocketdesc+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vcard+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vcard+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vemmi";
        {
            "source";
            "iana";
        }
        "application/vividence.scriptfile";
        {
            "source";
            "apache";
        }
        "application/vnd.1000minds.decision-model+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp-prose+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp-prose-pc3ch+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp-v2x-local-service-information";
        {
            "source";
            "iana";
        }
        "application/vnd.3gpp.access-transfer-events+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.bsf+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.gmop+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.mc-signalling-ear";
        {
            "source";
            "iana";
        }
        "application/vnd.3gpp.mcdata-payload";
        {
            "source";
            "iana";
        }
        "application/vnd.3gpp.mcdata-signalling";
        {
            "source";
            "iana";
        }
        "application/vnd.3gpp.mcptt-affiliation-command+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.mcptt-floor-request+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.mcptt-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.mcptt-location-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.mcptt-mbms-usage-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.mcptt-signed+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.mid-call+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.pic-bw-large";
        {
            "source";
            "iana",
                "extensions";
            ["plb"];
        }
        "application/vnd.3gpp.pic-bw-small";
        {
            "source";
            "iana",
                "extensions";
            ["psb"];
        }
        "application/vnd.3gpp.pic-bw-var";
        {
            "source";
            "iana",
                "extensions";
            ["pvb"];
        }
        "application/vnd.3gpp.sms";
        {
            "source";
            "iana";
        }
        "application/vnd.3gpp.sms+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.srvcc-ext+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.srvcc-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.state-and-event-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp.ussd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp2.bcmcsinfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.3gpp2.sms";
        {
            "source";
            "iana";
        }
        "application/vnd.3gpp2.tcap";
        {
            "source";
            "iana",
                "extensions";
            ["tcap"];
        }
        "application/vnd.3lightssoftware.imagescal";
        {
            "source";
            "iana";
        }
        "application/vnd.3m.post-it-notes";
        {
            "source";
            "iana",
                "extensions";
            ["pwn"];
        }
        "application/vnd.accpac.simply.aso";
        {
            "source";
            "iana",
                "extensions";
            ["aso"];
        }
        "application/vnd.accpac.simply.imp";
        {
            "source";
            "iana",
                "extensions";
            ["imp"];
        }
        "application/vnd.acucobol";
        {
            "source";
            "iana",
                "extensions";
            ["acu"];
        }
        "application/vnd.acucorp";
        {
            "source";
            "iana",
                "extensions";
            ["atc", "acutc"];
        }
        "application/vnd.adobe.air-application-installer-package+zip";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["air"];
        }
        "application/vnd.adobe.flash.movie";
        {
            "source";
            "iana";
        }
        "application/vnd.adobe.formscentral.fcdt";
        {
            "source";
            "iana",
                "extensions";
            ["fcdt"];
        }
        "application/vnd.adobe.fxp";
        {
            "source";
            "iana",
                "extensions";
            ["fxp", "fxpl"];
        }
        "application/vnd.adobe.partial-upload";
        {
            "source";
            "iana";
        }
        "application/vnd.adobe.xdp+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xdp"];
        }
        "application/vnd.adobe.xfdf";
        {
            "source";
            "iana",
                "extensions";
            ["xfdf"];
        }
        "application/vnd.aether.imp";
        {
            "source";
            "iana";
        }
        "application/vnd.afpc.afplinedata";
        {
            "source";
            "iana";
        }
        "application/vnd.afpc.modca";
        {
            "source";
            "iana";
        }
        "application/vnd.ah-barcode";
        {
            "source";
            "iana";
        }
        "application/vnd.ahead.space";
        {
            "source";
            "iana",
                "extensions";
            ["ahead"];
        }
        "application/vnd.airzip.filesecure.azf";
        {
            "source";
            "iana",
                "extensions";
            ["azf"];
        }
        "application/vnd.airzip.filesecure.azs";
        {
            "source";
            "iana",
                "extensions";
            ["azs"];
        }
        "application/vnd.amadeus+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.amazon.ebook";
        {
            "source";
            "apache",
                "extensions";
            ["azw"];
        }
        "application/vnd.amazon.mobi8-ebook";
        {
            "source";
            "iana";
        }
        "application/vnd.americandynamics.acc";
        {
            "source";
            "iana",
                "extensions";
            ["acc"];
        }
        "application/vnd.amiga.ami";
        {
            "source";
            "iana",
                "extensions";
            ["ami"];
        }
        "application/vnd.amundsen.maze+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.android.package-archive";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["apk"];
        }
        "application/vnd.anki";
        {
            "source";
            "iana";
        }
        "application/vnd.anser-web-certificate-issue-initiation";
        {
            "source";
            "iana",
                "extensions";
            ["cii"];
        }
        "application/vnd.anser-web-funds-transfer-initiation";
        {
            "source";
            "apache",
                "extensions";
            ["fti"];
        }
        "application/vnd.antix.game-component";
        {
            "source";
            "iana",
                "extensions";
            ["atx"];
        }
        "application/vnd.apache.thrift.binary";
        {
            "source";
            "iana";
        }
        "application/vnd.apache.thrift.compact";
        {
            "source";
            "iana";
        }
        "application/vnd.apache.thrift.json";
        {
            "source";
            "iana";
        }
        "application/vnd.api+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.apothekende.reservation+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.apple.installer+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mpkg"];
        }
        "application/vnd.apple.keynote";
        {
            "source";
            "iana",
                "extensions";
            ["keynote"];
        }
        "application/vnd.apple.mpegurl";
        {
            "source";
            "iana",
                "extensions";
            ["m3u8"];
        }
        "application/vnd.apple.numbers";
        {
            "source";
            "iana",
                "extensions";
            ["numbers"];
        }
        "application/vnd.apple.pages";
        {
            "source";
            "iana",
                "extensions";
            ["pages"];
        }
        "application/vnd.apple.pkpass";
        {
            "compressible";
            false,
                "extensions";
            ["pkpass"];
        }
        "application/vnd.arastra.swi";
        {
            "source";
            "iana";
        }
        "application/vnd.aristanetworks.swi";
        {
            "source";
            "iana",
                "extensions";
            ["swi"];
        }
        "application/vnd.artisan+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.artsquare";
        {
            "source";
            "iana";
        }
        "application/vnd.astraea-software.iota";
        {
            "source";
            "iana",
                "extensions";
            ["iota"];
        }
        "application/vnd.audiograph";
        {
            "source";
            "iana",
                "extensions";
            ["aep"];
        }
        "application/vnd.autopackage";
        {
            "source";
            "iana";
        }
        "application/vnd.avalon+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.avistar+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.balsamiq.bmml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.balsamiq.bmpr";
        {
            "source";
            "iana";
        }
        "application/vnd.banana-accounting";
        {
            "source";
            "iana";
        }
        "application/vnd.bbf.usp.msg";
        {
            "source";
            "iana";
        }
        "application/vnd.bbf.usp.msg+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.bekitzur-stech+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.bint.med-content";
        {
            "source";
            "iana";
        }
        "application/vnd.biopax.rdf+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.blink-idb-value-wrapper";
        {
            "source";
            "iana";
        }
        "application/vnd.blueice.multipass";
        {
            "source";
            "iana",
                "extensions";
            ["mpm"];
        }
        "application/vnd.bluetooth.ep.oob";
        {
            "source";
            "iana";
        }
        "application/vnd.bluetooth.le.oob";
        {
            "source";
            "iana";
        }
        "application/vnd.bmi";
        {
            "source";
            "iana",
                "extensions";
            ["bmi"];
        }
        "application/vnd.businessobjects";
        {
            "source";
            "iana",
                "extensions";
            ["rep"];
        }
        "application/vnd.byu.uapi+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.cab-jscript";
        {
            "source";
            "iana";
        }
        "application/vnd.canon-cpdl";
        {
            "source";
            "iana";
        }
        "application/vnd.canon-lips";
        {
            "source";
            "iana";
        }
        "application/vnd.capasystems-pg+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.cendio.thinlinc.clientconf";
        {
            "source";
            "iana";
        }
        "application/vnd.century-systems.tcp_stream";
        {
            "source";
            "iana";
        }
        "application/vnd.chemdraw+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["cdxml"];
        }
        "application/vnd.chess-pgn";
        {
            "source";
            "iana";
        }
        "application/vnd.chipnuts.karaoke-mmd";
        {
            "source";
            "iana",
                "extensions";
            ["mmd"];
        }
        "application/vnd.cinderella";
        {
            "source";
            "iana",
                "extensions";
            ["cdy"];
        }
        "application/vnd.cirpack.isdn-ext";
        {
            "source";
            "iana";
        }
        "application/vnd.citationstyles.style+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["csl"];
        }
        "application/vnd.claymore";
        {
            "source";
            "iana",
                "extensions";
            ["cla"];
        }
        "application/vnd.cloanto.rp9";
        {
            "source";
            "iana",
                "extensions";
            ["rp9"];
        }
        "application/vnd.clonk.c4group";
        {
            "source";
            "iana",
                "extensions";
            ["c4g", "c4d", "c4f", "c4p", "c4u"];
        }
        "application/vnd.cluetrust.cartomobile-config";
        {
            "source";
            "iana",
                "extensions";
            ["c11amc"];
        }
        "application/vnd.cluetrust.cartomobile-config-pkg";
        {
            "source";
            "iana",
                "extensions";
            ["c11amz"];
        }
        "application/vnd.coffeescript";
        {
            "source";
            "iana";
        }
        "application/vnd.collabio.xodocuments.document";
        {
            "source";
            "iana";
        }
        "application/vnd.collabio.xodocuments.document-template";
        {
            "source";
            "iana";
        }
        "application/vnd.collabio.xodocuments.presentation";
        {
            "source";
            "iana";
        }
        "application/vnd.collabio.xodocuments.presentation-template";
        {
            "source";
            "iana";
        }
        "application/vnd.collabio.xodocuments.spreadsheet";
        {
            "source";
            "iana";
        }
        "application/vnd.collabio.xodocuments.spreadsheet-template";
        {
            "source";
            "iana";
        }
        "application/vnd.collection+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.collection.doc+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.collection.next+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.comicbook+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.comicbook-rar";
        {
            "source";
            "iana";
        }
        "application/vnd.commerce-battelle";
        {
            "source";
            "iana";
        }
        "application/vnd.commonspace";
        {
            "source";
            "iana",
                "extensions";
            ["csp"];
        }
        "application/vnd.contact.cmsg";
        {
            "source";
            "iana",
                "extensions";
            ["cdbcmsg"];
        }
        "application/vnd.coreos.ignition+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.cosmocaller";
        {
            "source";
            "iana",
                "extensions";
            ["cmc"];
        }
        "application/vnd.crick.clicker";
        {
            "source";
            "iana",
                "extensions";
            ["clkx"];
        }
        "application/vnd.crick.clicker.keyboard";
        {
            "source";
            "iana",
                "extensions";
            ["clkk"];
        }
        "application/vnd.crick.clicker.palette";
        {
            "source";
            "iana",
                "extensions";
            ["clkp"];
        }
        "application/vnd.crick.clicker.template";
        {
            "source";
            "iana",
                "extensions";
            ["clkt"];
        }
        "application/vnd.crick.clicker.wordbank";
        {
            "source";
            "iana",
                "extensions";
            ["clkw"];
        }
        "application/vnd.criticaltools.wbs+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["wbs"];
        }
        "application/vnd.ctc-posml";
        {
            "source";
            "iana",
                "extensions";
            ["pml"];
        }
        "application/vnd.ctct.ws+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.cups-pdf";
        {
            "source";
            "iana";
        }
        "application/vnd.cups-postscript";
        {
            "source";
            "iana";
        }
        "application/vnd.cups-ppd";
        {
            "source";
            "iana",
                "extensions";
            ["ppd"];
        }
        "application/vnd.cups-raster";
        {
            "source";
            "iana";
        }
        "application/vnd.cups-raw";
        {
            "source";
            "iana";
        }
        "application/vnd.curl";
        {
            "source";
            "iana";
        }
        "application/vnd.curl.car";
        {
            "source";
            "apache",
                "extensions";
            ["car"];
        }
        "application/vnd.curl.pcurl";
        {
            "source";
            "apache",
                "extensions";
            ["pcurl"];
        }
        "application/vnd.cyan.dean.root+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.cybank";
        {
            "source";
            "iana";
        }
        "application/vnd.d2l.coursepackage1p0+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.dart";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["dart"];
        }
        "application/vnd.data-vision.rdz";
        {
            "source";
            "iana",
                "extensions";
            ["rdz"];
        }
        "application/vnd.datapackage+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dataresource+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.debian.binary-package";
        {
            "source";
            "iana";
        }
        "application/vnd.dece.data";
        {
            "source";
            "iana",
                "extensions";
            ["uvf", "uvvf", "uvd", "uvvd"];
        }
        "application/vnd.dece.ttml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["uvt", "uvvt"];
        }
        "application/vnd.dece.unspecified";
        {
            "source";
            "iana",
                "extensions";
            ["uvx", "uvvx"];
        }
        "application/vnd.dece.zip";
        {
            "source";
            "iana",
                "extensions";
            ["uvz", "uvvz"];
        }
        "application/vnd.denovo.fcselayout-link";
        {
            "source";
            "iana",
                "extensions";
            ["fe_launch"];
        }
        "application/vnd.desmume.movie";
        {
            "source";
            "iana";
        }
        "application/vnd.dir-bi.plate-dl-nosuffix";
        {
            "source";
            "iana";
        }
        "application/vnd.dm.delegation+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dna";
        {
            "source";
            "iana",
                "extensions";
            ["dna"];
        }
        "application/vnd.document+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dolby.mlp";
        {
            "source";
            "apache",
                "extensions";
            ["mlp"];
        }
        "application/vnd.dolby.mobile.1";
        {
            "source";
            "iana";
        }
        "application/vnd.dolby.mobile.2";
        {
            "source";
            "iana";
        }
        "application/vnd.doremir.scorecloud-binary-document";
        {
            "source";
            "iana";
        }
        "application/vnd.dpgraph";
        {
            "source";
            "iana",
                "extensions";
            ["dpg"];
        }
        "application/vnd.dreamfactory";
        {
            "source";
            "iana",
                "extensions";
            ["dfac"];
        }
        "application/vnd.drive+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ds-keypoint";
        {
            "source";
            "apache",
                "extensions";
            ["kpxx"];
        }
        "application/vnd.dtg.local";
        {
            "source";
            "iana";
        }
        "application/vnd.dtg.local.flash";
        {
            "source";
            "iana";
        }
        "application/vnd.dtg.local.html";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.ait";
        {
            "source";
            "iana",
                "extensions";
            ["ait"];
        }
        "application/vnd.dvb.dvbj";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.esgcontainer";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.ipdcdftnotifaccess";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.ipdcesgaccess";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.ipdcesgaccess2";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.ipdcesgpdd";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.ipdcroaming";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.iptv.alfec-base";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.iptv.alfec-enhancement";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.notif-aggregate-root+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dvb.notif-container+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dvb.notif-generic+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dvb.notif-ia-msglist+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dvb.notif-ia-registration-request+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dvb.notif-ia-registration-response+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dvb.notif-init+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.dvb.pfr";
        {
            "source";
            "iana";
        }
        "application/vnd.dvb.service";
        {
            "source";
            "iana",
                "extensions";
            ["svc"];
        }
        "application/vnd.dxr";
        {
            "source";
            "iana";
        }
        "application/vnd.dynageo";
        {
            "source";
            "iana",
                "extensions";
            ["geo"];
        }
        "application/vnd.dzr";
        {
            "source";
            "iana";
        }
        "application/vnd.easykaraoke.cdgdownload";
        {
            "source";
            "iana";
        }
        "application/vnd.ecdis-update";
        {
            "source";
            "iana";
        }
        "application/vnd.ecip.rlp";
        {
            "source";
            "iana";
        }
        "application/vnd.ecowin.chart";
        {
            "source";
            "iana",
                "extensions";
            ["mag"];
        }
        "application/vnd.ecowin.filerequest";
        {
            "source";
            "iana";
        }
        "application/vnd.ecowin.fileupdate";
        {
            "source";
            "iana";
        }
        "application/vnd.ecowin.series";
        {
            "source";
            "iana";
        }
        "application/vnd.ecowin.seriesrequest";
        {
            "source";
            "iana";
        }
        "application/vnd.ecowin.seriesupdate";
        {
            "source";
            "iana";
        }
        "application/vnd.efi.img";
        {
            "source";
            "iana";
        }
        "application/vnd.efi.iso";
        {
            "source";
            "iana";
        }
        "application/vnd.emclient.accessrequest+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.enliven";
        {
            "source";
            "iana",
                "extensions";
            ["nml"];
        }
        "application/vnd.enphase.envoy";
        {
            "source";
            "iana";
        }
        "application/vnd.eprints.data+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.epson.esf";
        {
            "source";
            "iana",
                "extensions";
            ["esf"];
        }
        "application/vnd.epson.msf";
        {
            "source";
            "iana",
                "extensions";
            ["msf"];
        }
        "application/vnd.epson.quickanime";
        {
            "source";
            "iana",
                "extensions";
            ["qam"];
        }
        "application/vnd.epson.salt";
        {
            "source";
            "iana",
                "extensions";
            ["slt"];
        }
        "application/vnd.epson.ssf";
        {
            "source";
            "iana",
                "extensions";
            ["ssf"];
        }
        "application/vnd.ericsson.quickcall";
        {
            "source";
            "iana";
        }
        "application/vnd.espass-espass+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.eszigno3+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["es3", "et3"];
        }
        "application/vnd.etsi.aoc+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.asic-e+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.etsi.asic-s+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.etsi.cug+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvcommand+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvdiscovery+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvprofile+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvsad-bc+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvsad-cod+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvsad-npvr+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvservice+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvsync+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.iptvueprofile+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.mcid+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.mheg5";
        {
            "source";
            "iana";
        }
        "application/vnd.etsi.overload-control-policy-dataset+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.pstn+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.sci+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.simservs+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.timestamp-token";
        {
            "source";
            "iana";
        }
        "application/vnd.etsi.tsl+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.etsi.tsl.der";
        {
            "source";
            "iana";
        }
        "application/vnd.eudora.data";
        {
            "source";
            "iana";
        }
        "application/vnd.evolv.ecig.profile";
        {
            "source";
            "iana";
        }
        "application/vnd.evolv.ecig.settings";
        {
            "source";
            "iana";
        }
        "application/vnd.evolv.ecig.theme";
        {
            "source";
            "iana";
        }
        "application/vnd.ezpix-album";
        {
            "source";
            "iana",
                "extensions";
            ["ez2"];
        }
        "application/vnd.ezpix-package";
        {
            "source";
            "iana",
                "extensions";
            ["ez3"];
        }
        "application/vnd.f-secure.mobile";
        {
            "source";
            "iana";
        }
        "application/vnd.fastcopy-disk-image";
        {
            "source";
            "iana";
        }
        "application/vnd.fdf";
        {
            "source";
            "iana",
                "extensions";
            ["fdf"];
        }
        "application/vnd.fdsn.mseed";
        {
            "source";
            "iana",
                "extensions";
            ["mseed"];
        }
        "application/vnd.fdsn.seed";
        {
            "source";
            "iana",
                "extensions";
            ["seed", "dataless"];
        }
        "application/vnd.ffsns";
        {
            "source";
            "iana";
        }
        "application/vnd.filmit.zfc";
        {
            "source";
            "iana";
        }
        "application/vnd.fints";
        {
            "source";
            "iana";
        }
        "application/vnd.firemonkeys.cloudcell";
        {
            "source";
            "iana";
        }
        "application/vnd.flographit";
        {
            "source";
            "iana",
                "extensions";
            ["gph"];
        }
        "application/vnd.fluxtime.clip";
        {
            "source";
            "iana",
                "extensions";
            ["ftc"];
        }
        "application/vnd.font-fontforge-sfd";
        {
            "source";
            "iana";
        }
        "application/vnd.framemaker";
        {
            "source";
            "iana",
                "extensions";
            ["fm", "frame", "maker", "book"];
        }
        "application/vnd.frogans.fnc";
        {
            "source";
            "iana",
                "extensions";
            ["fnc"];
        }
        "application/vnd.frogans.ltf";
        {
            "source";
            "iana",
                "extensions";
            ["ltf"];
        }
        "application/vnd.fsc.weblaunch";
        {
            "source";
            "iana",
                "extensions";
            ["fsc"];
        }
        "application/vnd.fujitsu.oasys";
        {
            "source";
            "iana",
                "extensions";
            ["oas"];
        }
        "application/vnd.fujitsu.oasys2";
        {
            "source";
            "iana",
                "extensions";
            ["oa2"];
        }
        "application/vnd.fujitsu.oasys3";
        {
            "source";
            "iana",
                "extensions";
            ["oa3"];
        }
        "application/vnd.fujitsu.oasysgp";
        {
            "source";
            "iana",
                "extensions";
            ["fg5"];
        }
        "application/vnd.fujitsu.oasysprs";
        {
            "source";
            "iana",
                "extensions";
            ["bh2"];
        }
        "application/vnd.fujixerox.art-ex";
        {
            "source";
            "iana";
        }
        "application/vnd.fujixerox.art4";
        {
            "source";
            "iana";
        }
        "application/vnd.fujixerox.ddd";
        {
            "source";
            "iana",
                "extensions";
            ["ddd"];
        }
        "application/vnd.fujixerox.docuworks";
        {
            "source";
            "iana",
                "extensions";
            ["xdw"];
        }
        "application/vnd.fujixerox.docuworks.binder";
        {
            "source";
            "iana",
                "extensions";
            ["xbd"];
        }
        "application/vnd.fujixerox.docuworks.container";
        {
            "source";
            "iana";
        }
        "application/vnd.fujixerox.hbpl";
        {
            "source";
            "iana";
        }
        "application/vnd.fut-misnet";
        {
            "source";
            "iana";
        }
        "application/vnd.futoin+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.fuzzysheet";
        {
            "source";
            "iana",
                "extensions";
            ["fzs"];
        }
        "application/vnd.genomatix.tuxedo";
        {
            "source";
            "iana",
                "extensions";
            ["txd"];
        }
        "application/vnd.geo+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.geocube+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.geogebra.file";
        {
            "source";
            "iana",
                "extensions";
            ["ggb"];
        }
        "application/vnd.geogebra.tool";
        {
            "source";
            "iana",
                "extensions";
            ["ggt"];
        }
        "application/vnd.geometry-explorer";
        {
            "source";
            "iana",
                "extensions";
            ["gex", "gre"];
        }
        "application/vnd.geonext";
        {
            "source";
            "iana",
                "extensions";
            ["gxt"];
        }
        "application/vnd.geoplan";
        {
            "source";
            "iana",
                "extensions";
            ["g2w"];
        }
        "application/vnd.geospace";
        {
            "source";
            "iana",
                "extensions";
            ["g3w"];
        }
        "application/vnd.gerber";
        {
            "source";
            "iana";
        }
        "application/vnd.globalplatform.card-content-mgt";
        {
            "source";
            "iana";
        }
        "application/vnd.globalplatform.card-content-mgt-response";
        {
            "source";
            "iana";
        }
        "application/vnd.gmx";
        {
            "source";
            "iana",
                "extensions";
            ["gmx"];
        }
        "application/vnd.google-apps.document";
        {
            "compressible";
            false,
                "extensions";
            ["gdoc"];
        }
        "application/vnd.google-apps.presentation";
        {
            "compressible";
            false,
                "extensions";
            ["gslides"];
        }
        "application/vnd.google-apps.spreadsheet";
        {
            "compressible";
            false,
                "extensions";
            ["gsheet"];
        }
        "application/vnd.google-earth.kml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["kml"];
        }
        "application/vnd.google-earth.kmz";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["kmz"];
        }
        "application/vnd.gov.sk.e-form+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.gov.sk.e-form+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.gov.sk.xmldatacontainer+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.grafeq";
        {
            "source";
            "iana",
                "extensions";
            ["gqf", "gqs"];
        }
        "application/vnd.gridmp";
        {
            "source";
            "iana";
        }
        "application/vnd.groove-account";
        {
            "source";
            "iana",
                "extensions";
            ["gac"];
        }
        "application/vnd.groove-help";
        {
            "source";
            "iana",
                "extensions";
            ["ghf"];
        }
        "application/vnd.groove-identity-message";
        {
            "source";
            "iana",
                "extensions";
            ["gim"];
        }
        "application/vnd.groove-injector";
        {
            "source";
            "iana",
                "extensions";
            ["grv"];
        }
        "application/vnd.groove-tool-message";
        {
            "source";
            "iana",
                "extensions";
            ["gtm"];
        }
        "application/vnd.groove-tool-template";
        {
            "source";
            "iana",
                "extensions";
            ["tpl"];
        }
        "application/vnd.groove-vcard";
        {
            "source";
            "iana",
                "extensions";
            ["vcg"];
        }
        "application/vnd.hal+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.hal+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["hal"];
        }
        "application/vnd.handheld-entertainment+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["zmm"];
        }
        "application/vnd.hbci";
        {
            "source";
            "iana",
                "extensions";
            ["hbci"];
        }
        "application/vnd.hc+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.hcl-bireports";
        {
            "source";
            "iana";
        }
        "application/vnd.hdt";
        {
            "source";
            "iana";
        }
        "application/vnd.heroku+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.hhe.lesson-player";
        {
            "source";
            "iana",
                "extensions";
            ["les"];
        }
        "application/vnd.hp-hpgl";
        {
            "source";
            "iana",
                "extensions";
            ["hpgl"];
        }
        "application/vnd.hp-hpid";
        {
            "source";
            "iana",
                "extensions";
            ["hpid"];
        }
        "application/vnd.hp-hps";
        {
            "source";
            "iana",
                "extensions";
            ["hps"];
        }
        "application/vnd.hp-jlyt";
        {
            "source";
            "iana",
                "extensions";
            ["jlt"];
        }
        "application/vnd.hp-pcl";
        {
            "source";
            "iana",
                "extensions";
            ["pcl"];
        }
        "application/vnd.hp-pclxl";
        {
            "source";
            "iana",
                "extensions";
            ["pclxl"];
        }
        "application/vnd.httphone";
        {
            "source";
            "iana";
        }
        "application/vnd.hydrostatix.sof-data";
        {
            "source";
            "iana",
                "extensions";
            ["sfd-hdstx"];
        }
        "application/vnd.hyper+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.hyper-item+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.hyperdrive+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.hzn-3d-crossword";
        {
            "source";
            "iana";
        }
        "application/vnd.ibm.afplinedata";
        {
            "source";
            "iana";
        }
        "application/vnd.ibm.electronic-media";
        {
            "source";
            "iana";
        }
        "application/vnd.ibm.minipay";
        {
            "source";
            "iana",
                "extensions";
            ["mpy"];
        }
        "application/vnd.ibm.modcap";
        {
            "source";
            "iana",
                "extensions";
            ["afp", "listafp", "list3820"];
        }
        "application/vnd.ibm.rights-management";
        {
            "source";
            "iana",
                "extensions";
            ["irm"];
        }
        "application/vnd.ibm.secure-container";
        {
            "source";
            "iana",
                "extensions";
            ["sc"];
        }
        "application/vnd.iccprofile";
        {
            "source";
            "iana",
                "extensions";
            ["icc", "icm"];
        }
        "application/vnd.ieee.1905";
        {
            "source";
            "iana";
        }
        "application/vnd.igloader";
        {
            "source";
            "iana",
                "extensions";
            ["igl"];
        }
        "application/vnd.imagemeter.folder+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.imagemeter.image+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "application/vnd.immervision-ivp";
        {
            "source";
            "iana",
                "extensions";
            ["ivp"];
        }
        "application/vnd.immervision-ivu";
        {
            "source";
            "iana",
                "extensions";
            ["ivu"];
        }
        "application/vnd.ims.imsccv1p1";
        {
            "source";
            "iana";
        }
        "application/vnd.ims.imsccv1p2";
        {
            "source";
            "iana";
        }
        "application/vnd.ims.imsccv1p3";
        {
            "source";
            "iana";
        }
        "application/vnd.ims.lis.v2.result+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ims.lti.v2.toolconsumerprofile+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ims.lti.v2.toolproxy+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ims.lti.v2.toolproxy.id+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ims.lti.v2.toolsettings+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ims.lti.v2.toolsettings.simple+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.informedcontrol.rms+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.informix-visionary";
        {
            "source";
            "iana";
        }
        "application/vnd.infotech.project";
        {
            "source";
            "iana";
        }
        "application/vnd.infotech.project+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.innopath.wamp.notification";
        {
            "source";
            "iana";
        }
        "application/vnd.insors.igm";
        {
            "source";
            "iana",
                "extensions";
            ["igm"];
        }
        "application/vnd.intercon.formnet";
        {
            "source";
            "iana",
                "extensions";
            ["xpw", "xpx"];
        }
        "application/vnd.intergeo";
        {
            "source";
            "iana",
                "extensions";
            ["i2g"];
        }
        "application/vnd.intertrust.digibox";
        {
            "source";
            "iana";
        }
        "application/vnd.intertrust.nncp";
        {
            "source";
            "iana";
        }
        "application/vnd.intu.qbo";
        {
            "source";
            "iana",
                "extensions";
            ["qbo"];
        }
        "application/vnd.intu.qfx";
        {
            "source";
            "iana",
                "extensions";
            ["qfx"];
        }
        "application/vnd.iptc.g2.catalogitem+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.iptc.g2.conceptitem+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.iptc.g2.knowledgeitem+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.iptc.g2.newsitem+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.iptc.g2.newsmessage+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.iptc.g2.packageitem+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.iptc.g2.planningitem+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ipunplugged.rcprofile";
        {
            "source";
            "iana",
                "extensions";
            ["rcprofile"];
        }
        "application/vnd.irepository.package+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["irp"];
        }
        "application/vnd.is-xpr";
        {
            "source";
            "iana",
                "extensions";
            ["xpr"];
        }
        "application/vnd.isac.fcs";
        {
            "source";
            "iana",
                "extensions";
            ["fcs"];
        }
        "application/vnd.jam";
        {
            "source";
            "iana",
                "extensions";
            ["jam"];
        }
        "application/vnd.japannet-directory-service";
        {
            "source";
            "iana";
        }
        "application/vnd.japannet-jpnstore-wakeup";
        {
            "source";
            "iana";
        }
        "application/vnd.japannet-payment-wakeup";
        {
            "source";
            "iana";
        }
        "application/vnd.japannet-registration";
        {
            "source";
            "iana";
        }
        "application/vnd.japannet-registration-wakeup";
        {
            "source";
            "iana";
        }
        "application/vnd.japannet-setstore-wakeup";
        {
            "source";
            "iana";
        }
        "application/vnd.japannet-verification";
        {
            "source";
            "iana";
        }
        "application/vnd.japannet-verification-wakeup";
        {
            "source";
            "iana";
        }
        "application/vnd.jcp.javame.midlet-rms";
        {
            "source";
            "iana",
                "extensions";
            ["rms"];
        }
        "application/vnd.jisp";
        {
            "source";
            "iana",
                "extensions";
            ["jisp"];
        }
        "application/vnd.joost.joda-archive";
        {
            "source";
            "iana",
                "extensions";
            ["joda"];
        }
        "application/vnd.jsk.isdn-ngn";
        {
            "source";
            "iana";
        }
        "application/vnd.kahootz";
        {
            "source";
            "iana",
                "extensions";
            ["ktz", "ktr"];
        }
        "application/vnd.kde.karbon";
        {
            "source";
            "iana",
                "extensions";
            ["karbon"];
        }
        "application/vnd.kde.kchart";
        {
            "source";
            "iana",
                "extensions";
            ["chrt"];
        }
        "application/vnd.kde.kformula";
        {
            "source";
            "iana",
                "extensions";
            ["kfo"];
        }
        "application/vnd.kde.kivio";
        {
            "source";
            "iana",
                "extensions";
            ["flw"];
        }
        "application/vnd.kde.kontour";
        {
            "source";
            "iana",
                "extensions";
            ["kon"];
        }
        "application/vnd.kde.kpresenter";
        {
            "source";
            "iana",
                "extensions";
            ["kpr", "kpt"];
        }
        "application/vnd.kde.kspread";
        {
            "source";
            "iana",
                "extensions";
            ["ksp"];
        }
        "application/vnd.kde.kword";
        {
            "source";
            "iana",
                "extensions";
            ["kwd", "kwt"];
        }
        "application/vnd.kenameaapp";
        {
            "source";
            "iana",
                "extensions";
            ["htke"];
        }
        "application/vnd.kidspiration";
        {
            "source";
            "iana",
                "extensions";
            ["kia"];
        }
        "application/vnd.kinar";
        {
            "source";
            "iana",
                "extensions";
            ["kne", "knp"];
        }
        "application/vnd.koan";
        {
            "source";
            "iana",
                "extensions";
            ["skp", "skd", "skt", "skm"];
        }
        "application/vnd.kodak-descriptor";
        {
            "source";
            "iana",
                "extensions";
            ["sse"];
        }
        "application/vnd.las.las+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.las.las+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["lasxml"];
        }
        "application/vnd.leap+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.liberty-request+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.llamagraphics.life-balance.desktop";
        {
            "source";
            "iana",
                "extensions";
            ["lbd"];
        }
        "application/vnd.llamagraphics.life-balance.exchange+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["lbe"];
        }
        "application/vnd.lotus-1-2-3";
        {
            "source";
            "iana",
                "extensions";
            ["123"];
        }
        "application/vnd.lotus-approach";
        {
            "source";
            "iana",
                "extensions";
            ["apr"];
        }
        "application/vnd.lotus-freelance";
        {
            "source";
            "iana",
                "extensions";
            ["pre"];
        }
        "application/vnd.lotus-notes";
        {
            "source";
            "iana",
                "extensions";
            ["nsf"];
        }
        "application/vnd.lotus-organizer";
        {
            "source";
            "iana",
                "extensions";
            ["org"];
        }
        "application/vnd.lotus-screencam";
        {
            "source";
            "iana",
                "extensions";
            ["scm"];
        }
        "application/vnd.lotus-wordpro";
        {
            "source";
            "iana",
                "extensions";
            ["lwp"];
        }
        "application/vnd.macports.portpkg";
        {
            "source";
            "iana",
                "extensions";
            ["portpkg"];
        }
        "application/vnd.mapbox-vector-tile";
        {
            "source";
            "iana";
        }
        "application/vnd.marlin.drm.actiontoken+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.marlin.drm.conftoken+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.marlin.drm.license+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.marlin.drm.mdcf";
        {
            "source";
            "iana";
        }
        "application/vnd.mason+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.maxmind.maxmind-db";
        {
            "source";
            "iana";
        }
        "application/vnd.mcd";
        {
            "source";
            "iana",
                "extensions";
            ["mcd"];
        }
        "application/vnd.medcalcdata";
        {
            "source";
            "iana",
                "extensions";
            ["mc1"];
        }
        "application/vnd.mediastation.cdkey";
        {
            "source";
            "iana",
                "extensions";
            ["cdkey"];
        }
        "application/vnd.meridian-slingshot";
        {
            "source";
            "iana";
        }
        "application/vnd.mfer";
        {
            "source";
            "iana",
                "extensions";
            ["mwf"];
        }
        "application/vnd.mfmp";
        {
            "source";
            "iana",
                "extensions";
            ["mfm"];
        }
        "application/vnd.micro+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.micrografx.flo";
        {
            "source";
            "iana",
                "extensions";
            ["flo"];
        }
        "application/vnd.micrografx.igx";
        {
            "source";
            "iana",
                "extensions";
            ["igx"];
        }
        "application/vnd.microsoft.portable-executable";
        {
            "source";
            "iana";
        }
        "application/vnd.microsoft.windows.thumbnail-cache";
        {
            "source";
            "iana";
        }
        "application/vnd.miele+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.mif";
        {
            "source";
            "iana",
                "extensions";
            ["mif"];
        }
        "application/vnd.minisoft-hp3000-save";
        {
            "source";
            "iana";
        }
        "application/vnd.mitsubishi.misty-guard.trustweb";
        {
            "source";
            "iana";
        }
        "application/vnd.mobius.daf";
        {
            "source";
            "iana",
                "extensions";
            ["daf"];
        }
        "application/vnd.mobius.dis";
        {
            "source";
            "iana",
                "extensions";
            ["dis"];
        }
        "application/vnd.mobius.mbk";
        {
            "source";
            "iana",
                "extensions";
            ["mbk"];
        }
        "application/vnd.mobius.mqy";
        {
            "source";
            "iana",
                "extensions";
            ["mqy"];
        }
        "application/vnd.mobius.msl";
        {
            "source";
            "iana",
                "extensions";
            ["msl"];
        }
        "application/vnd.mobius.plc";
        {
            "source";
            "iana",
                "extensions";
            ["plc"];
        }
        "application/vnd.mobius.txf";
        {
            "source";
            "iana",
                "extensions";
            ["txf"];
        }
        "application/vnd.mophun.application";
        {
            "source";
            "iana",
                "extensions";
            ["mpn"];
        }
        "application/vnd.mophun.certificate";
        {
            "source";
            "iana",
                "extensions";
            ["mpc"];
        }
        "application/vnd.motorola.flexsuite";
        {
            "source";
            "iana";
        }
        "application/vnd.motorola.flexsuite.adsi";
        {
            "source";
            "iana";
        }
        "application/vnd.motorola.flexsuite.fis";
        {
            "source";
            "iana";
        }
        "application/vnd.motorola.flexsuite.gotap";
        {
            "source";
            "iana";
        }
        "application/vnd.motorola.flexsuite.kmr";
        {
            "source";
            "iana";
        }
        "application/vnd.motorola.flexsuite.ttc";
        {
            "source";
            "iana";
        }
        "application/vnd.motorola.flexsuite.wem";
        {
            "source";
            "iana";
        }
        "application/vnd.motorola.iprm";
        {
            "source";
            "iana";
        }
        "application/vnd.mozilla.xul+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xul"];
        }
        "application/vnd.ms-3mfdocument";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-artgalry";
        {
            "source";
            "iana",
                "extensions";
            ["cil"];
        }
        "application/vnd.ms-asf";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-cab-compressed";
        {
            "source";
            "iana",
                "extensions";
            ["cab"];
        }
        "application/vnd.ms-color.iccprofile";
        {
            "source";
            "apache";
        }
        "application/vnd.ms-excel";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["xls", "xlm", "xla", "xlc", "xlt", "xlw"];
        }
        "application/vnd.ms-excel.addin.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["xlam"];
        }
        "application/vnd.ms-excel.sheet.binary.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["xlsb"];
        }
        "application/vnd.ms-excel.sheet.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["xlsm"];
        }
        "application/vnd.ms-excel.template.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["xltm"];
        }
        "application/vnd.ms-fontobject";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["eot"];
        }
        "application/vnd.ms-htmlhelp";
        {
            "source";
            "iana",
                "extensions";
            ["chm"];
        }
        "application/vnd.ms-ims";
        {
            "source";
            "iana",
                "extensions";
            ["ims"];
        }
        "application/vnd.ms-lrm";
        {
            "source";
            "iana",
                "extensions";
            ["lrm"];
        }
        "application/vnd.ms-office.activex+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ms-officetheme";
        {
            "source";
            "iana",
                "extensions";
            ["thmx"];
        }
        "application/vnd.ms-opentype";
        {
            "source";
            "apache",
                "compressible";
            true;
        }
        "application/vnd.ms-outlook";
        {
            "compressible";
            false,
                "extensions";
            ["msg"];
        }
        "application/vnd.ms-package.obfuscated-opentype";
        {
            "source";
            "apache";
        }
        "application/vnd.ms-pki.seccat";
        {
            "source";
            "apache",
                "extensions";
            ["cat"];
        }
        "application/vnd.ms-pki.stl";
        {
            "source";
            "apache",
                "extensions";
            ["stl"];
        }
        "application/vnd.ms-playready.initiator+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ms-powerpoint";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["ppt", "pps", "pot"];
        }
        "application/vnd.ms-powerpoint.addin.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["ppam"];
        }
        "application/vnd.ms-powerpoint.presentation.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["pptm"];
        }
        "application/vnd.ms-powerpoint.slide.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["sldm"];
        }
        "application/vnd.ms-powerpoint.slideshow.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["ppsm"];
        }
        "application/vnd.ms-powerpoint.template.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["potm"];
        }
        "application/vnd.ms-printdevicecapabilities+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ms-printing.printticket+xml";
        {
            "source";
            "apache",
                "compressible";
            true;
        }
        "application/vnd.ms-printschematicket+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.ms-project";
        {
            "source";
            "iana",
                "extensions";
            ["mpp", "mpt"];
        }
        "application/vnd.ms-tnef";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-windows.devicepairing";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-windows.nwprinting.oob";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-windows.printerpairing";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-windows.wsd.oob";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-wmdrm.lic-chlg-req";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-wmdrm.lic-resp";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-wmdrm.meter-chlg-req";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-wmdrm.meter-resp";
        {
            "source";
            "iana";
        }
        "application/vnd.ms-word.document.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["docm"];
        }
        "application/vnd.ms-word.template.macroenabled.12";
        {
            "source";
            "iana",
                "extensions";
            ["dotm"];
        }
        "application/vnd.ms-works";
        {
            "source";
            "iana",
                "extensions";
            ["wps", "wks", "wcm", "wdb"];
        }
        "application/vnd.ms-wpl";
        {
            "source";
            "iana",
                "extensions";
            ["wpl"];
        }
        "application/vnd.ms-xpsdocument";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["xps"];
        }
        "application/vnd.msa-disk-image";
        {
            "source";
            "iana";
        }
        "application/vnd.mseq";
        {
            "source";
            "iana",
                "extensions";
            ["mseq"];
        }
        "application/vnd.msign";
        {
            "source";
            "iana";
        }
        "application/vnd.multiad.creator";
        {
            "source";
            "iana";
        }
        "application/vnd.multiad.creator.cif";
        {
            "source";
            "iana";
        }
        "application/vnd.music-niff";
        {
            "source";
            "iana";
        }
        "application/vnd.musician";
        {
            "source";
            "iana",
                "extensions";
            ["mus"];
        }
        "application/vnd.muvee.style";
        {
            "source";
            "iana",
                "extensions";
            ["msty"];
        }
        "application/vnd.mynfc";
        {
            "source";
            "iana",
                "extensions";
            ["taglet"];
        }
        "application/vnd.ncd.control";
        {
            "source";
            "iana";
        }
        "application/vnd.ncd.reference";
        {
            "source";
            "iana";
        }
        "application/vnd.nearst.inv+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.nervana";
        {
            "source";
            "iana";
        }
        "application/vnd.netfpx";
        {
            "source";
            "iana";
        }
        "application/vnd.neurolanguage.nlu";
        {
            "source";
            "iana",
                "extensions";
            ["nlu"];
        }
        "application/vnd.nimn";
        {
            "source";
            "iana";
        }
        "application/vnd.nintendo.nitro.rom";
        {
            "source";
            "iana";
        }
        "application/vnd.nintendo.snes.rom";
        {
            "source";
            "iana";
        }
        "application/vnd.nitf";
        {
            "source";
            "iana",
                "extensions";
            ["ntf", "nitf"];
        }
        "application/vnd.noblenet-directory";
        {
            "source";
            "iana",
                "extensions";
            ["nnd"];
        }
        "application/vnd.noblenet-sealer";
        {
            "source";
            "iana",
                "extensions";
            ["nns"];
        }
        "application/vnd.noblenet-web";
        {
            "source";
            "iana",
                "extensions";
            ["nnw"];
        }
        "application/vnd.nokia.catalogs";
        {
            "source";
            "iana";
        }
        "application/vnd.nokia.conml+wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.nokia.conml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.nokia.iptv.config+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.nokia.isds-radio-presets";
        {
            "source";
            "iana";
        }
        "application/vnd.nokia.landmark+wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.nokia.landmark+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.nokia.landmarkcollection+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.nokia.n-gage.ac+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.nokia.n-gage.data";
        {
            "source";
            "iana",
                "extensions";
            ["ngdat"];
        }
        "application/vnd.nokia.n-gage.symbian.install";
        {
            "source";
            "iana",
                "extensions";
            ["n-gage"];
        }
        "application/vnd.nokia.ncd";
        {
            "source";
            "iana";
        }
        "application/vnd.nokia.pcd+wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.nokia.pcd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.nokia.radio-preset";
        {
            "source";
            "iana",
                "extensions";
            ["rpst"];
        }
        "application/vnd.nokia.radio-presets";
        {
            "source";
            "iana",
                "extensions";
            ["rpss"];
        }
        "application/vnd.novadigm.edm";
        {
            "source";
            "iana",
                "extensions";
            ["edm"];
        }
        "application/vnd.novadigm.edx";
        {
            "source";
            "iana",
                "extensions";
            ["edx"];
        }
        "application/vnd.novadigm.ext";
        {
            "source";
            "iana",
                "extensions";
            ["ext"];
        }
        "application/vnd.ntt-local.content-share";
        {
            "source";
            "iana";
        }
        "application/vnd.ntt-local.file-transfer";
        {
            "source";
            "iana";
        }
        "application/vnd.ntt-local.ogw_remote-access";
        {
            "source";
            "iana";
        }
        "application/vnd.ntt-local.sip-ta_remote";
        {
            "source";
            "iana";
        }
        "application/vnd.ntt-local.sip-ta_tcp_stream";
        {
            "source";
            "iana";
        }
        "application/vnd.oasis.opendocument.chart";
        {
            "source";
            "iana",
                "extensions";
            ["odc"];
        }
        "application/vnd.oasis.opendocument.chart-template";
        {
            "source";
            "iana",
                "extensions";
            ["otc"];
        }
        "application/vnd.oasis.opendocument.database";
        {
            "source";
            "iana",
                "extensions";
            ["odb"];
        }
        "application/vnd.oasis.opendocument.formula";
        {
            "source";
            "iana",
                "extensions";
            ["odf"];
        }
        "application/vnd.oasis.opendocument.formula-template";
        {
            "source";
            "iana",
                "extensions";
            ["odft"];
        }
        "application/vnd.oasis.opendocument.graphics";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["odg"];
        }
        "application/vnd.oasis.opendocument.graphics-template";
        {
            "source";
            "iana",
                "extensions";
            ["otg"];
        }
        "application/vnd.oasis.opendocument.image";
        {
            "source";
            "iana",
                "extensions";
            ["odi"];
        }
        "application/vnd.oasis.opendocument.image-template";
        {
            "source";
            "iana",
                "extensions";
            ["oti"];
        }
        "application/vnd.oasis.opendocument.presentation";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["odp"];
        }
        "application/vnd.oasis.opendocument.presentation-template";
        {
            "source";
            "iana",
                "extensions";
            ["otp"];
        }
        "application/vnd.oasis.opendocument.spreadsheet";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["ods"];
        }
        "application/vnd.oasis.opendocument.spreadsheet-template";
        {
            "source";
            "iana",
                "extensions";
            ["ots"];
        }
        "application/vnd.oasis.opendocument.text";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["odt"];
        }
        "application/vnd.oasis.opendocument.text-master";
        {
            "source";
            "iana",
                "extensions";
            ["odm"];
        }
        "application/vnd.oasis.opendocument.text-template";
        {
            "source";
            "iana",
                "extensions";
            ["ott"];
        }
        "application/vnd.oasis.opendocument.text-web";
        {
            "source";
            "iana",
                "extensions";
            ["oth"];
        }
        "application/vnd.obn";
        {
            "source";
            "iana";
        }
        "application/vnd.ocf+cbor";
        {
            "source";
            "iana";
        }
        "application/vnd.oftn.l10n+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.contentaccessdownload+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.contentaccessstreaming+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.cspg-hexbinary";
        {
            "source";
            "iana";
        }
        "application/vnd.oipf.dae.svg+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.dae.xhtml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.mippvcontrolmessage+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.pae.gem";
        {
            "source";
            "iana";
        }
        "application/vnd.oipf.spdiscovery+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.spdlist+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.ueprofile+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oipf.userprofile+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.olpc-sugar";
        {
            "source";
            "iana",
                "extensions";
            ["xo"];
        }
        "application/vnd.oma-scws-config";
        {
            "source";
            "iana";
        }
        "application/vnd.oma-scws-http-request";
        {
            "source";
            "iana";
        }
        "application/vnd.oma-scws-http-response";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.bcast.associated-procedure-parameter+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.bcast.drm-trigger+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.bcast.imd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.bcast.ltkm";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.bcast.notification+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.bcast.provisioningtrigger";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.bcast.sgboot";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.bcast.sgdd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.bcast.sgdu";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.bcast.simple-symbol-container";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.bcast.smartcard-trigger+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.bcast.sprov+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.bcast.stkm";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.cab-address-book+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.cab-feature-handler+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.cab-pcc+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.cab-subs-invite+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.cab-user-prefs+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.dcd";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.dcdc";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.dd2+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["dd2"];
        }
        "application/vnd.oma.drm.risd+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.group-usage-list+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.lwm2m+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.lwm2m+tlv";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.pal+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.poc.detailed-progress-report+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.poc.final-report+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.poc.groups+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.poc.invocation-descriptor+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.poc.optimized-progress-report+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.push";
        {
            "source";
            "iana";
        }
        "application/vnd.oma.scidm.messages+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oma.xcap-directory+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.omads-email+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.omads-file+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.omads-folder+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.omaloc-supl-init";
        {
            "source";
            "iana";
        }
        "application/vnd.onepager";
        {
            "source";
            "iana";
        }
        "application/vnd.onepagertamp";
        {
            "source";
            "iana";
        }
        "application/vnd.onepagertamx";
        {
            "source";
            "iana";
        }
        "application/vnd.onepagertat";
        {
            "source";
            "iana";
        }
        "application/vnd.onepagertatp";
        {
            "source";
            "iana";
        }
        "application/vnd.onepagertatx";
        {
            "source";
            "iana";
        }
        "application/vnd.openblox.game+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openblox.game-binary";
        {
            "source";
            "iana";
        }
        "application/vnd.openeye.oeb";
        {
            "source";
            "iana";
        }
        "application/vnd.openofficeorg.extension";
        {
            "source";
            "apache",
                "extensions";
            ["oxt"];
        }
        "application/vnd.openstreetmap.data+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.custom-properties+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.customxmlproperties+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.drawing+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.drawingml.chart+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.extended-properties+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.comments+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["pptx"];
        }
        "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.slide";
        {
            "source";
            "iana",
                "extensions";
            ["sldx"];
        }
        "application/vnd.openxmlformats-officedocument.presentationml.slide+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
        {
            "source";
            "iana",
                "extensions";
            ["ppsx"];
        }
        "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.tags+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.template";
        {
            "source";
            "iana",
                "extensions";
            ["potx"];
        }
        "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["xlsx"];
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
        {
            "source";
            "iana",
                "extensions";
            ["xltx"];
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.theme+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.themeoverride+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.vmldrawing";
        {
            "source";
            "iana";
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["docx"];
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
        {
            "source";
            "iana",
                "extensions";
            ["dotx"];
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-package.core-properties+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.openxmlformats-package.relationships+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oracle.resource+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.orange.indata";
        {
            "source";
            "iana";
        }
        "application/vnd.osa.netdeploy";
        {
            "source";
            "iana";
        }
        "application/vnd.osgeo.mapguide.package";
        {
            "source";
            "iana",
                "extensions";
            ["mgp"];
        }
        "application/vnd.osgi.bundle";
        {
            "source";
            "iana";
        }
        "application/vnd.osgi.dp";
        {
            "source";
            "iana",
                "extensions";
            ["dp"];
        }
        "application/vnd.osgi.subsystem";
        {
            "source";
            "iana",
                "extensions";
            ["esa"];
        }
        "application/vnd.otps.ct-kip+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.oxli.countgraph";
        {
            "source";
            "iana";
        }
        "application/vnd.pagerduty+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.palm";
        {
            "source";
            "iana",
                "extensions";
            ["pdb", "pqa", "oprc"];
        }
        "application/vnd.panoply";
        {
            "source";
            "iana";
        }
        "application/vnd.paos.xml";
        {
            "source";
            "iana";
        }
        "application/vnd.patentdive";
        {
            "source";
            "iana";
        }
        "application/vnd.pawaafile";
        {
            "source";
            "iana",
                "extensions";
            ["paw"];
        }
        "application/vnd.pcos";
        {
            "source";
            "iana";
        }
        "application/vnd.pg.format";
        {
            "source";
            "iana",
                "extensions";
            ["str"];
        }
        "application/vnd.pg.osasli";
        {
            "source";
            "iana",
                "extensions";
            ["ei6"];
        }
        "application/vnd.piaccess.application-licence";
        {
            "source";
            "iana";
        }
        "application/vnd.picsel";
        {
            "source";
            "iana",
                "extensions";
            ["efif"];
        }
        "application/vnd.pmi.widget";
        {
            "source";
            "iana",
                "extensions";
            ["wg"];
        }
        "application/vnd.poc.group-advertisement+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.pocketlearn";
        {
            "source";
            "iana",
                "extensions";
            ["plf"];
        }
        "application/vnd.powerbuilder6";
        {
            "source";
            "iana",
                "extensions";
            ["pbd"];
        }
        "application/vnd.powerbuilder6-s";
        {
            "source";
            "iana";
        }
        "application/vnd.powerbuilder7";
        {
            "source";
            "iana";
        }
        "application/vnd.powerbuilder7-s";
        {
            "source";
            "iana";
        }
        "application/vnd.powerbuilder75";
        {
            "source";
            "iana";
        }
        "application/vnd.powerbuilder75-s";
        {
            "source";
            "iana";
        }
        "application/vnd.preminet";
        {
            "source";
            "iana";
        }
        "application/vnd.previewsystems.box";
        {
            "source";
            "iana",
                "extensions";
            ["box"];
        }
        "application/vnd.proteus.magazine";
        {
            "source";
            "iana",
                "extensions";
            ["mgz"];
        }
        "application/vnd.psfs";
        {
            "source";
            "iana";
        }
        "application/vnd.publishare-delta-tree";
        {
            "source";
            "iana",
                "extensions";
            ["qps"];
        }
        "application/vnd.pvi.ptid1";
        {
            "source";
            "iana",
                "extensions";
            ["ptid"];
        }
        "application/vnd.pwg-multiplexed";
        {
            "source";
            "iana";
        }
        "application/vnd.pwg-xhtml-print+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.qualcomm.brew-app-res";
        {
            "source";
            "iana";
        }
        "application/vnd.quarantainenet";
        {
            "source";
            "iana";
        }
        "application/vnd.quark.quarkxpress";
        {
            "source";
            "iana",
                "extensions";
            ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"];
        }
        "application/vnd.quobject-quoxdocument";
        {
            "source";
            "iana";
        }
        "application/vnd.radisys.moml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-audit+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-audit-conf+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-audit-conn+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-audit-dialog+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-audit-stream+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-conf+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-dialog+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-dialog-base+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-dialog-fax-detect+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-dialog-fax-sendrecv+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-dialog-group+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-dialog-speech+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.radisys.msml-dialog-transform+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.rainstor.data";
        {
            "source";
            "iana";
        }
        "application/vnd.rapid";
        {
            "source";
            "iana";
        }
        "application/vnd.rar";
        {
            "source";
            "iana";
        }
        "application/vnd.realvnc.bed";
        {
            "source";
            "iana",
                "extensions";
            ["bed"];
        }
        "application/vnd.recordare.musicxml";
        {
            "source";
            "iana",
                "extensions";
            ["mxl"];
        }
        "application/vnd.recordare.musicxml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["musicxml"];
        }
        "application/vnd.renlearn.rlprint";
        {
            "source";
            "iana";
        }
        "application/vnd.restful+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.rig.cryptonote";
        {
            "source";
            "iana",
                "extensions";
            ["cryptonote"];
        }
        "application/vnd.rim.cod";
        {
            "source";
            "apache",
                "extensions";
            ["cod"];
        }
        "application/vnd.rn-realmedia";
        {
            "source";
            "apache",
                "extensions";
            ["rm"];
        }
        "application/vnd.rn-realmedia-vbr";
        {
            "source";
            "apache",
                "extensions";
            ["rmvb"];
        }
        "application/vnd.route66.link66+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["link66"];
        }
        "application/vnd.rs-274x";
        {
            "source";
            "iana";
        }
        "application/vnd.ruckus.download";
        {
            "source";
            "iana";
        }
        "application/vnd.s3sms";
        {
            "source";
            "iana";
        }
        "application/vnd.sailingtracker.track";
        {
            "source";
            "iana",
                "extensions";
            ["st"];
        }
        "application/vnd.sbm.cid";
        {
            "source";
            "iana";
        }
        "application/vnd.sbm.mid2";
        {
            "source";
            "iana";
        }
        "application/vnd.scribus";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.3df";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.csf";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.doc";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.eml";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.mht";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.net";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.ppt";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.tiff";
        {
            "source";
            "iana";
        }
        "application/vnd.sealed.xls";
        {
            "source";
            "iana";
        }
        "application/vnd.sealedmedia.softseal.html";
        {
            "source";
            "iana";
        }
        "application/vnd.sealedmedia.softseal.pdf";
        {
            "source";
            "iana";
        }
        "application/vnd.seemail";
        {
            "source";
            "iana",
                "extensions";
            ["see"];
        }
        "application/vnd.sema";
        {
            "source";
            "iana",
                "extensions";
            ["sema"];
        }
        "application/vnd.semd";
        {
            "source";
            "iana",
                "extensions";
            ["semd"];
        }
        "application/vnd.semf";
        {
            "source";
            "iana",
                "extensions";
            ["semf"];
        }
        "application/vnd.shana.informed.formdata";
        {
            "source";
            "iana",
                "extensions";
            ["ifm"];
        }
        "application/vnd.shana.informed.formtemplate";
        {
            "source";
            "iana",
                "extensions";
            ["itp"];
        }
        "application/vnd.shana.informed.interchange";
        {
            "source";
            "iana",
                "extensions";
            ["iif"];
        }
        "application/vnd.shana.informed.package";
        {
            "source";
            "iana",
                "extensions";
            ["ipk"];
        }
        "application/vnd.shootproof+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.sigrok.session";
        {
            "source";
            "iana";
        }
        "application/vnd.simtech-mindmapper";
        {
            "source";
            "iana",
                "extensions";
            ["twd", "twds"];
        }
        "application/vnd.siren+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.smaf";
        {
            "source";
            "iana",
                "extensions";
            ["mmf"];
        }
        "application/vnd.smart.notebook";
        {
            "source";
            "iana";
        }
        "application/vnd.smart.teacher";
        {
            "source";
            "iana",
                "extensions";
            ["teacher"];
        }
        "application/vnd.software602.filler.form+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.software602.filler.form-xml-zip";
        {
            "source";
            "iana";
        }
        "application/vnd.solent.sdkm+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["sdkm", "sdkd"];
        }
        "application/vnd.spotfire.dxp";
        {
            "source";
            "iana",
                "extensions";
            ["dxp"];
        }
        "application/vnd.spotfire.sfs";
        {
            "source";
            "iana",
                "extensions";
            ["sfs"];
        }
        "application/vnd.sqlite3";
        {
            "source";
            "iana";
        }
        "application/vnd.sss-cod";
        {
            "source";
            "iana";
        }
        "application/vnd.sss-dtf";
        {
            "source";
            "iana";
        }
        "application/vnd.sss-ntf";
        {
            "source";
            "iana";
        }
        "application/vnd.stardivision.calc";
        {
            "source";
            "apache",
                "extensions";
            ["sdc"];
        }
        "application/vnd.stardivision.draw";
        {
            "source";
            "apache",
                "extensions";
            ["sda"];
        }
        "application/vnd.stardivision.impress";
        {
            "source";
            "apache",
                "extensions";
            ["sdd"];
        }
        "application/vnd.stardivision.math";
        {
            "source";
            "apache",
                "extensions";
            ["smf"];
        }
        "application/vnd.stardivision.writer";
        {
            "source";
            "apache",
                "extensions";
            ["sdw", "vor"];
        }
        "application/vnd.stardivision.writer-global";
        {
            "source";
            "apache",
                "extensions";
            ["sgl"];
        }
        "application/vnd.stepmania.package";
        {
            "source";
            "iana",
                "extensions";
            ["smzip"];
        }
        "application/vnd.stepmania.stepchart";
        {
            "source";
            "iana",
                "extensions";
            ["sm"];
        }
        "application/vnd.street-stream";
        {
            "source";
            "iana";
        }
        "application/vnd.sun.wadl+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["wadl"];
        }
        "application/vnd.sun.xml.calc";
        {
            "source";
            "apache",
                "extensions";
            ["sxc"];
        }
        "application/vnd.sun.xml.calc.template";
        {
            "source";
            "apache",
                "extensions";
            ["stc"];
        }
        "application/vnd.sun.xml.draw";
        {
            "source";
            "apache",
                "extensions";
            ["sxd"];
        }
        "application/vnd.sun.xml.draw.template";
        {
            "source";
            "apache",
                "extensions";
            ["std"];
        }
        "application/vnd.sun.xml.impress";
        {
            "source";
            "apache",
                "extensions";
            ["sxi"];
        }
        "application/vnd.sun.xml.impress.template";
        {
            "source";
            "apache",
                "extensions";
            ["sti"];
        }
        "application/vnd.sun.xml.math";
        {
            "source";
            "apache",
                "extensions";
            ["sxm"];
        }
        "application/vnd.sun.xml.writer";
        {
            "source";
            "apache",
                "extensions";
            ["sxw"];
        }
        "application/vnd.sun.xml.writer.global";
        {
            "source";
            "apache",
                "extensions";
            ["sxg"];
        }
        "application/vnd.sun.xml.writer.template";
        {
            "source";
            "apache",
                "extensions";
            ["stw"];
        }
        "application/vnd.sus-calendar";
        {
            "source";
            "iana",
                "extensions";
            ["sus", "susp"];
        }
        "application/vnd.svd";
        {
            "source";
            "iana",
                "extensions";
            ["svd"];
        }
        "application/vnd.swiftview-ics";
        {
            "source";
            "iana";
        }
        "application/vnd.symbian.install";
        {
            "source";
            "apache",
                "extensions";
            ["sis", "sisx"];
        }
        "application/vnd.syncml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xsm"];
        }
        "application/vnd.syncml.dm+wbxml";
        {
            "source";
            "iana",
                "extensions";
            ["bdm"];
        }
        "application/vnd.syncml.dm+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xdm"];
        }
        "application/vnd.syncml.dm.notification";
        {
            "source";
            "iana";
        }
        "application/vnd.syncml.dmddf+wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.syncml.dmddf+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.syncml.dmtnds+wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.syncml.dmtnds+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.syncml.ds.notification";
        {
            "source";
            "iana";
        }
        "application/vnd.tableschema+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.tao.intent-module-archive";
        {
            "source";
            "iana",
                "extensions";
            ["tao"];
        }
        "application/vnd.tcpdump.pcap";
        {
            "source";
            "iana",
                "extensions";
            ["pcap", "cap", "dmp"];
        }
        "application/vnd.think-cell.ppttc+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.tmd.mediaflex.api+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.tml";
        {
            "source";
            "iana";
        }
        "application/vnd.tmobile-livetv";
        {
            "source";
            "iana",
                "extensions";
            ["tmo"];
        }
        "application/vnd.tri.onesource";
        {
            "source";
            "iana";
        }
        "application/vnd.trid.tpt";
        {
            "source";
            "iana",
                "extensions";
            ["tpt"];
        }
        "application/vnd.triscape.mxs";
        {
            "source";
            "iana",
                "extensions";
            ["mxs"];
        }
        "application/vnd.trueapp";
        {
            "source";
            "iana",
                "extensions";
            ["tra"];
        }
        "application/vnd.truedoc";
        {
            "source";
            "iana";
        }
        "application/vnd.ubisoft.webplayer";
        {
            "source";
            "iana";
        }
        "application/vnd.ufdl";
        {
            "source";
            "iana",
                "extensions";
            ["ufd", "ufdl"];
        }
        "application/vnd.uiq.theme";
        {
            "source";
            "iana",
                "extensions";
            ["utz"];
        }
        "application/vnd.umajin";
        {
            "source";
            "iana",
                "extensions";
            ["umj"];
        }
        "application/vnd.unity";
        {
            "source";
            "iana",
                "extensions";
            ["unityweb"];
        }
        "application/vnd.uoml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["uoml"];
        }
        "application/vnd.uplanet.alert";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.alert-wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.bearer-choice";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.bearer-choice-wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.cacheop";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.cacheop-wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.channel";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.channel-wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.list";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.list-wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.listcmd";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.listcmd-wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.uplanet.signal";
        {
            "source";
            "iana";
        }
        "application/vnd.uri-map";
        {
            "source";
            "iana";
        }
        "application/vnd.valve.source.material";
        {
            "source";
            "iana";
        }
        "application/vnd.vcx";
        {
            "source";
            "iana",
                "extensions";
            ["vcx"];
        }
        "application/vnd.vd-study";
        {
            "source";
            "iana";
        }
        "application/vnd.vectorworks";
        {
            "source";
            "iana";
        }
        "application/vnd.vel+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.verimatrix.vcas";
        {
            "source";
            "iana";
        }
        "application/vnd.vidsoft.vidconference";
        {
            "source";
            "iana";
        }
        "application/vnd.visio";
        {
            "source";
            "iana",
                "extensions";
            ["vsd", "vst", "vss", "vsw"];
        }
        "application/vnd.visionary";
        {
            "source";
            "iana",
                "extensions";
            ["vis"];
        }
        "application/vnd.vividence.scriptfile";
        {
            "source";
            "iana";
        }
        "application/vnd.vsf";
        {
            "source";
            "iana",
                "extensions";
            ["vsf"];
        }
        "application/vnd.wap.sic";
        {
            "source";
            "iana";
        }
        "application/vnd.wap.slc";
        {
            "source";
            "iana";
        }
        "application/vnd.wap.wbxml";
        {
            "source";
            "iana",
                "extensions";
            ["wbxml"];
        }
        "application/vnd.wap.wmlc";
        {
            "source";
            "iana",
                "extensions";
            ["wmlc"];
        }
        "application/vnd.wap.wmlscriptc";
        {
            "source";
            "iana",
                "extensions";
            ["wmlsc"];
        }
        "application/vnd.webturbo";
        {
            "source";
            "iana",
                "extensions";
            ["wtb"];
        }
        "application/vnd.wfa.p2p";
        {
            "source";
            "iana";
        }
        "application/vnd.wfa.wsc";
        {
            "source";
            "iana";
        }
        "application/vnd.windows.devicepairing";
        {
            "source";
            "iana";
        }
        "application/vnd.wmc";
        {
            "source";
            "iana";
        }
        "application/vnd.wmf.bootstrap";
        {
            "source";
            "iana";
        }
        "application/vnd.wolfram.mathematica";
        {
            "source";
            "iana";
        }
        "application/vnd.wolfram.mathematica.package";
        {
            "source";
            "iana";
        }
        "application/vnd.wolfram.player";
        {
            "source";
            "iana",
                "extensions";
            ["nbp"];
        }
        "application/vnd.wordperfect";
        {
            "source";
            "iana",
                "extensions";
            ["wpd"];
        }
        "application/vnd.wqd";
        {
            "source";
            "iana",
                "extensions";
            ["wqd"];
        }
        "application/vnd.wrq-hp3000-labelled";
        {
            "source";
            "iana";
        }
        "application/vnd.wt.stf";
        {
            "source";
            "iana",
                "extensions";
            ["stf"];
        }
        "application/vnd.wv.csp+wbxml";
        {
            "source";
            "iana";
        }
        "application/vnd.wv.csp+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.wv.ssp+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.xacml+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.xara";
        {
            "source";
            "iana",
                "extensions";
            ["xar"];
        }
        "application/vnd.xfdl";
        {
            "source";
            "iana",
                "extensions";
            ["xfdl"];
        }
        "application/vnd.xfdl.webform";
        {
            "source";
            "iana";
        }
        "application/vnd.xmi+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vnd.xmpie.cpkg";
        {
            "source";
            "iana";
        }
        "application/vnd.xmpie.dpkg";
        {
            "source";
            "iana";
        }
        "application/vnd.xmpie.plan";
        {
            "source";
            "iana";
        }
        "application/vnd.xmpie.ppkg";
        {
            "source";
            "iana";
        }
        "application/vnd.xmpie.xlim";
        {
            "source";
            "iana";
        }
        "application/vnd.yamaha.hv-dic";
        {
            "source";
            "iana",
                "extensions";
            ["hvd"];
        }
        "application/vnd.yamaha.hv-script";
        {
            "source";
            "iana",
                "extensions";
            ["hvs"];
        }
        "application/vnd.yamaha.hv-voice";
        {
            "source";
            "iana",
                "extensions";
            ["hvp"];
        }
        "application/vnd.yamaha.openscoreformat";
        {
            "source";
            "iana",
                "extensions";
            ["osf"];
        }
        "application/vnd.yamaha.openscoreformat.osfpvg+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["osfpvg"];
        }
        "application/vnd.yamaha.remote-setup";
        {
            "source";
            "iana";
        }
        "application/vnd.yamaha.smaf-audio";
        {
            "source";
            "iana",
                "extensions";
            ["saf"];
        }
        "application/vnd.yamaha.smaf-phrase";
        {
            "source";
            "iana",
                "extensions";
            ["spf"];
        }
        "application/vnd.yamaha.through-ngn";
        {
            "source";
            "iana";
        }
        "application/vnd.yamaha.tunnel-udpencap";
        {
            "source";
            "iana";
        }
        "application/vnd.yaoweme";
        {
            "source";
            "iana";
        }
        "application/vnd.yellowriver-custom-menu";
        {
            "source";
            "iana",
                "extensions";
            ["cmp"];
        }
        "application/vnd.youtube.yt";
        {
            "source";
            "iana";
        }
        "application/vnd.zul";
        {
            "source";
            "iana",
                "extensions";
            ["zir", "zirz"];
        }
        "application/vnd.zzazz.deck+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["zaz"];
        }
        "application/voicexml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["vxml"];
        }
        "application/voucher-cms+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/vq-rtcpxr";
        {
            "source";
            "iana";
        }
        "application/wasm";
        {
            "compressible";
            true,
                "extensions";
            ["wasm"];
        }
        "application/watcherinfo+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/webpush-options+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/whoispp-query";
        {
            "source";
            "iana";
        }
        "application/whoispp-response";
        {
            "source";
            "iana";
        }
        "application/widget";
        {
            "source";
            "iana",
                "extensions";
            ["wgt"];
        }
        "application/winhlp";
        {
            "source";
            "apache",
                "extensions";
            ["hlp"];
        }
        "application/wita";
        {
            "source";
            "iana";
        }
        "application/wordperfect5.1";
        {
            "source";
            "iana";
        }
        "application/wsdl+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["wsdl"];
        }
        "application/wspolicy+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["wspolicy"];
        }
        "application/x-7z-compressed";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["7z"];
        }
        "application/x-abiword";
        {
            "source";
            "apache",
                "extensions";
            ["abw"];
        }
        "application/x-ace-compressed";
        {
            "source";
            "apache",
                "extensions";
            ["ace"];
        }
        "application/x-amf";
        {
            "source";
            "apache";
        }
        "application/x-apple-diskimage";
        {
            "source";
            "apache",
                "extensions";
            ["dmg"];
        }
        "application/x-arj";
        {
            "compressible";
            false,
                "extensions";
            ["arj"];
        }
        "application/x-authorware-bin";
        {
            "source";
            "apache",
                "extensions";
            ["aab", "x32", "u32", "vox"];
        }
        "application/x-authorware-map";
        {
            "source";
            "apache",
                "extensions";
            ["aam"];
        }
        "application/x-authorware-seg";
        {
            "source";
            "apache",
                "extensions";
            ["aas"];
        }
        "application/x-bcpio";
        {
            "source";
            "apache",
                "extensions";
            ["bcpio"];
        }
        "application/x-bdoc";
        {
            "compressible";
            false,
                "extensions";
            ["bdoc"];
        }
        "application/x-bittorrent";
        {
            "source";
            "apache",
                "extensions";
            ["torrent"];
        }
        "application/x-blorb";
        {
            "source";
            "apache",
                "extensions";
            ["blb", "blorb"];
        }
        "application/x-bzip";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["bz"];
        }
        "application/x-bzip2";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["bz2", "boz"];
        }
        "application/x-cbr";
        {
            "source";
            "apache",
                "extensions";
            ["cbr", "cba", "cbt", "cbz", "cb7"];
        }
        "application/x-cdlink";
        {
            "source";
            "apache",
                "extensions";
            ["vcd"];
        }
        "application/x-cfs-compressed";
        {
            "source";
            "apache",
                "extensions";
            ["cfs"];
        }
        "application/x-chat";
        {
            "source";
            "apache",
                "extensions";
            ["chat"];
        }
        "application/x-chess-pgn";
        {
            "source";
            "apache",
                "extensions";
            ["pgn"];
        }
        "application/x-chrome-extension";
        {
            "extensions";
            ["crx"];
        }
        "application/x-cocoa";
        {
            "source";
            "nginx",
                "extensions";
            ["cco"];
        }
        "application/x-compress";
        {
            "source";
            "apache";
        }
        "application/x-conference";
        {
            "source";
            "apache",
                "extensions";
            ["nsc"];
        }
        "application/x-cpio";
        {
            "source";
            "apache",
                "extensions";
            ["cpio"];
        }
        "application/x-csh";
        {
            "source";
            "apache",
                "extensions";
            ["csh"];
        }
        "application/x-deb";
        {
            "compressible";
            false;
        }
        "application/x-debian-package";
        {
            "source";
            "apache",
                "extensions";
            ["deb", "udeb"];
        }
        "application/x-dgc-compressed";
        {
            "source";
            "apache",
                "extensions";
            ["dgc"];
        }
        "application/x-director";
        {
            "source";
            "apache",
                "extensions";
            ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"];
        }
        "application/x-doom";
        {
            "source";
            "apache",
                "extensions";
            ["wad"];
        }
        "application/x-dtbncx+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["ncx"];
        }
        "application/x-dtbook+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["dtb"];
        }
        "application/x-dtbresource+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["res"];
        }
        "application/x-dvi";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["dvi"];
        }
        "application/x-envoy";
        {
            "source";
            "apache",
                "extensions";
            ["evy"];
        }
        "application/x-eva";
        {
            "source";
            "apache",
                "extensions";
            ["eva"];
        }
        "application/x-font-bdf";
        {
            "source";
            "apache",
                "extensions";
            ["bdf"];
        }
        "application/x-font-dos";
        {
            "source";
            "apache";
        }
        "application/x-font-framemaker";
        {
            "source";
            "apache";
        }
        "application/x-font-ghostscript";
        {
            "source";
            "apache",
                "extensions";
            ["gsf"];
        }
        "application/x-font-libgrx";
        {
            "source";
            "apache";
        }
        "application/x-font-linux-psf";
        {
            "source";
            "apache",
                "extensions";
            ["psf"];
        }
        "application/x-font-pcf";
        {
            "source";
            "apache",
                "extensions";
            ["pcf"];
        }
        "application/x-font-snf";
        {
            "source";
            "apache",
                "extensions";
            ["snf"];
        }
        "application/x-font-speedo";
        {
            "source";
            "apache";
        }
        "application/x-font-sunos-news";
        {
            "source";
            "apache";
        }
        "application/x-font-type1";
        {
            "source";
            "apache",
                "extensions";
            ["pfa", "pfb", "pfm", "afm"];
        }
        "application/x-font-vfont";
        {
            "source";
            "apache";
        }
        "application/x-freearc";
        {
            "source";
            "apache",
                "extensions";
            ["arc"];
        }
        "application/x-futuresplash";
        {
            "source";
            "apache",
                "extensions";
            ["spl"];
        }
        "application/x-gca-compressed";
        {
            "source";
            "apache",
                "extensions";
            ["gca"];
        }
        "application/x-glulx";
        {
            "source";
            "apache",
                "extensions";
            ["ulx"];
        }
        "application/x-gnumeric";
        {
            "source";
            "apache",
                "extensions";
            ["gnumeric"];
        }
        "application/x-gramps-xml";
        {
            "source";
            "apache",
                "extensions";
            ["gramps"];
        }
        "application/x-gtar";
        {
            "source";
            "apache",
                "extensions";
            ["gtar"];
        }
        "application/x-gzip";
        {
            "source";
            "apache";
        }
        "application/x-hdf";
        {
            "source";
            "apache",
                "extensions";
            ["hdf"];
        }
        "application/x-httpd-php";
        {
            "compressible";
            true,
                "extensions";
            ["php"];
        }
        "application/x-install-instructions";
        {
            "source";
            "apache",
                "extensions";
            ["install"];
        }
        "application/x-iso9660-image";
        {
            "source";
            "apache",
                "extensions";
            ["iso"];
        }
        "application/x-java-archive-diff";
        {
            "source";
            "nginx",
                "extensions";
            ["jardiff"];
        }
        "application/x-java-jnlp-file";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["jnlp"];
        }
        "application/x-javascript";
        {
            "compressible";
            true;
        }
        "application/x-latex";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["latex"];
        }
        "application/x-lua-bytecode";
        {
            "extensions";
            ["luac"];
        }
        "application/x-lzh-compressed";
        {
            "source";
            "apache",
                "extensions";
            ["lzh", "lha"];
        }
        "application/x-makeself";
        {
            "source";
            "nginx",
                "extensions";
            ["run"];
        }
        "application/x-mie";
        {
            "source";
            "apache",
                "extensions";
            ["mie"];
        }
        "application/x-mobipocket-ebook";
        {
            "source";
            "apache",
                "extensions";
            ["prc", "mobi"];
        }
        "application/x-mpegurl";
        {
            "compressible";
            false;
        }
        "application/x-ms-application";
        {
            "source";
            "apache",
                "extensions";
            ["application"];
        }
        "application/x-ms-shortcut";
        {
            "source";
            "apache",
                "extensions";
            ["lnk"];
        }
        "application/x-ms-wmd";
        {
            "source";
            "apache",
                "extensions";
            ["wmd"];
        }
        "application/x-ms-wmz";
        {
            "source";
            "apache",
                "extensions";
            ["wmz"];
        }
        "application/x-ms-xbap";
        {
            "source";
            "apache",
                "extensions";
            ["xbap"];
        }
        "application/x-msaccess";
        {
            "source";
            "apache",
                "extensions";
            ["mdb"];
        }
        "application/x-msbinder";
        {
            "source";
            "apache",
                "extensions";
            ["obd"];
        }
        "application/x-mscardfile";
        {
            "source";
            "apache",
                "extensions";
            ["crd"];
        }
        "application/x-msclip";
        {
            "source";
            "apache",
                "extensions";
            ["clp"];
        }
        "application/x-msdos-program";
        {
            "extensions";
            ["exe"];
        }
        "application/x-msdownload";
        {
            "source";
            "apache",
                "extensions";
            ["exe", "dll", "com", "bat", "msi"];
        }
        "application/x-msmediaview";
        {
            "source";
            "apache",
                "extensions";
            ["mvb", "m13", "m14"];
        }
        "application/x-msmetafile";
        {
            "source";
            "apache",
                "extensions";
            ["wmf", "wmz", "emf", "emz"];
        }
        "application/x-msmoney";
        {
            "source";
            "apache",
                "extensions";
            ["mny"];
        }
        "application/x-mspublisher";
        {
            "source";
            "apache",
                "extensions";
            ["pub"];
        }
        "application/x-msschedule";
        {
            "source";
            "apache",
                "extensions";
            ["scd"];
        }
        "application/x-msterminal";
        {
            "source";
            "apache",
                "extensions";
            ["trm"];
        }
        "application/x-mswrite";
        {
            "source";
            "apache",
                "extensions";
            ["wri"];
        }
        "application/x-netcdf";
        {
            "source";
            "apache",
                "extensions";
            ["nc", "cdf"];
        }
        "application/x-ns-proxy-autoconfig";
        {
            "compressible";
            true,
                "extensions";
            ["pac"];
        }
        "application/x-nzb";
        {
            "source";
            "apache",
                "extensions";
            ["nzb"];
        }
        "application/x-perl";
        {
            "source";
            "nginx",
                "extensions";
            ["pl", "pm"];
        }
        "application/x-pilot";
        {
            "source";
            "nginx",
                "extensions";
            ["prc", "pdb"];
        }
        "application/x-pkcs12";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["p12", "pfx"];
        }
        "application/x-pkcs7-certificates";
        {
            "source";
            "apache",
                "extensions";
            ["p7b", "spc"];
        }
        "application/x-pkcs7-certreqresp";
        {
            "source";
            "apache",
                "extensions";
            ["p7r"];
        }
        "application/x-rar-compressed";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["rar"];
        }
        "application/x-redhat-package-manager";
        {
            "source";
            "nginx",
                "extensions";
            ["rpm"];
        }
        "application/x-research-info-systems";
        {
            "source";
            "apache",
                "extensions";
            ["ris"];
        }
        "application/x-sea";
        {
            "source";
            "nginx",
                "extensions";
            ["sea"];
        }
        "application/x-sh";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["sh"];
        }
        "application/x-shar";
        {
            "source";
            "apache",
                "extensions";
            ["shar"];
        }
        "application/x-shockwave-flash";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["swf"];
        }
        "application/x-silverlight-app";
        {
            "source";
            "apache",
                "extensions";
            ["xap"];
        }
        "application/x-sql";
        {
            "source";
            "apache",
                "extensions";
            ["sql"];
        }
        "application/x-stuffit";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["sit"];
        }
        "application/x-stuffitx";
        {
            "source";
            "apache",
                "extensions";
            ["sitx"];
        }
        "application/x-subrip";
        {
            "source";
            "apache",
                "extensions";
            ["srt"];
        }
        "application/x-sv4cpio";
        {
            "source";
            "apache",
                "extensions";
            ["sv4cpio"];
        }
        "application/x-sv4crc";
        {
            "source";
            "apache",
                "extensions";
            ["sv4crc"];
        }
        "application/x-t3vm-image";
        {
            "source";
            "apache",
                "extensions";
            ["t3"];
        }
        "application/x-tads";
        {
            "source";
            "apache",
                "extensions";
            ["gam"];
        }
        "application/x-tar";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["tar"];
        }
        "application/x-tcl";
        {
            "source";
            "apache",
                "extensions";
            ["tcl", "tk"];
        }
        "application/x-tex";
        {
            "source";
            "apache",
                "extensions";
            ["tex"];
        }
        "application/x-tex-tfm";
        {
            "source";
            "apache",
                "extensions";
            ["tfm"];
        }
        "application/x-texinfo";
        {
            "source";
            "apache",
                "extensions";
            ["texinfo", "texi"];
        }
        "application/x-tgif";
        {
            "source";
            "apache",
                "extensions";
            ["obj"];
        }
        "application/x-ustar";
        {
            "source";
            "apache",
                "extensions";
            ["ustar"];
        }
        "application/x-virtualbox-hdd";
        {
            "compressible";
            true,
                "extensions";
            ["hdd"];
        }
        "application/x-virtualbox-ova";
        {
            "compressible";
            true,
                "extensions";
            ["ova"];
        }
        "application/x-virtualbox-ovf";
        {
            "compressible";
            true,
                "extensions";
            ["ovf"];
        }
        "application/x-virtualbox-vbox";
        {
            "compressible";
            true,
                "extensions";
            ["vbox"];
        }
        "application/x-virtualbox-vbox-extpack";
        {
            "compressible";
            false,
                "extensions";
            ["vbox-extpack"];
        }
        "application/x-virtualbox-vdi";
        {
            "compressible";
            true,
                "extensions";
            ["vdi"];
        }
        "application/x-virtualbox-vhd";
        {
            "compressible";
            true,
                "extensions";
            ["vhd"];
        }
        "application/x-virtualbox-vmdk";
        {
            "compressible";
            true,
                "extensions";
            ["vmdk"];
        }
        "application/x-wais-source";
        {
            "source";
            "apache",
                "extensions";
            ["src"];
        }
        "application/x-web-app-manifest+json";
        {
            "compressible";
            true,
                "extensions";
            ["webapp"];
        }
        "application/x-www-form-urlencoded";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/x-x509-ca-cert";
        {
            "source";
            "apache",
                "extensions";
            ["der", "crt", "pem"];
        }
        "application/x-xfig";
        {
            "source";
            "apache",
                "extensions";
            ["fig"];
        }
        "application/x-xliff+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["xlf"];
        }
        "application/x-xpinstall";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["xpi"];
        }
        "application/x-xz";
        {
            "source";
            "apache",
                "extensions";
            ["xz"];
        }
        "application/x-zmachine";
        {
            "source";
            "apache",
                "extensions";
            ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"];
        }
        "application/x400-bp";
        {
            "source";
            "iana";
        }
        "application/xacml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xaml+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["xaml"];
        }
        "application/xcap-att+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xcap-caps+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xcap-diff+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xdf"];
        }
        "application/xcap-el+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xcap-error+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xcap-ns+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xcon-conference-info+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xcon-conference-info-diff+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xenc+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xenc"];
        }
        "application/xhtml+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xhtml", "xht"];
        }
        "application/xhtml-voice+xml";
        {
            "source";
            "apache",
                "compressible";
            true;
        }
        "application/xliff+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xml", "xsl", "xsd", "rng"];
        }
        "application/xml-dtd";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["dtd"];
        }
        "application/xml-external-parsed-entity";
        {
            "source";
            "iana";
        }
        "application/xml-patch+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xmpp+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/xop+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xop"];
        }
        "application/xproc+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["xpl"];
        }
        "application/xslt+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xslt"];
        }
        "application/xspf+xml";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["xspf"];
        }
        "application/xv+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["mxml", "xhvml", "xvml", "xvm"];
        }
        "application/yang";
        {
            "source";
            "iana",
                "extensions";
            ["yang"];
        }
        "application/yang-data+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/yang-data+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/yang-patch+json";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/yang-patch+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "application/yin+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["yin"];
        }
        "application/zip";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["zip"];
        }
        "application/zlib";
        {
            "source";
            "iana";
        }
        "application/zstd";
        {
            "source";
            "iana";
        }
        "audio/1d-interleaved-parityfec";
        {
            "source";
            "iana";
        }
        "audio/32kadpcm";
        {
            "source";
            "iana";
        }
        "audio/3gpp";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["3gpp"];
        }
        "audio/3gpp2";
        {
            "source";
            "iana";
        }
        "audio/aac";
        {
            "source";
            "iana";
        }
        "audio/ac3";
        {
            "source";
            "iana";
        }
        "audio/adpcm";
        {
            "source";
            "apache",
                "extensions";
            ["adp"];
        }
        "audio/amr";
        {
            "source";
            "iana";
        }
        "audio/amr-wb";
        {
            "source";
            "iana";
        }
        "audio/amr-wb+";
        {
            "source";
            "iana";
        }
        "audio/aptx";
        {
            "source";
            "iana";
        }
        "audio/asc";
        {
            "source";
            "iana";
        }
        "audio/atrac-advanced-lossless";
        {
            "source";
            "iana";
        }
        "audio/atrac-x";
        {
            "source";
            "iana";
        }
        "audio/atrac3";
        {
            "source";
            "iana";
        }
        "audio/basic";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["au", "snd"];
        }
        "audio/bv16";
        {
            "source";
            "iana";
        }
        "audio/bv32";
        {
            "source";
            "iana";
        }
        "audio/clearmode";
        {
            "source";
            "iana";
        }
        "audio/cn";
        {
            "source";
            "iana";
        }
        "audio/dat12";
        {
            "source";
            "iana";
        }
        "audio/dls";
        {
            "source";
            "iana";
        }
        "audio/dsr-es201108";
        {
            "source";
            "iana";
        }
        "audio/dsr-es202050";
        {
            "source";
            "iana";
        }
        "audio/dsr-es202211";
        {
            "source";
            "iana";
        }
        "audio/dsr-es202212";
        {
            "source";
            "iana";
        }
        "audio/dv";
        {
            "source";
            "iana";
        }
        "audio/dvi4";
        {
            "source";
            "iana";
        }
        "audio/eac3";
        {
            "source";
            "iana";
        }
        "audio/encaprtp";
        {
            "source";
            "iana";
        }
        "audio/evrc";
        {
            "source";
            "iana";
        }
        "audio/evrc-qcp";
        {
            "source";
            "iana";
        }
        "audio/evrc0";
        {
            "source";
            "iana";
        }
        "audio/evrc1";
        {
            "source";
            "iana";
        }
        "audio/evrcb";
        {
            "source";
            "iana";
        }
        "audio/evrcb0";
        {
            "source";
            "iana";
        }
        "audio/evrcb1";
        {
            "source";
            "iana";
        }
        "audio/evrcnw";
        {
            "source";
            "iana";
        }
        "audio/evrcnw0";
        {
            "source";
            "iana";
        }
        "audio/evrcnw1";
        {
            "source";
            "iana";
        }
        "audio/evrcwb";
        {
            "source";
            "iana";
        }
        "audio/evrcwb0";
        {
            "source";
            "iana";
        }
        "audio/evrcwb1";
        {
            "source";
            "iana";
        }
        "audio/evs";
        {
            "source";
            "iana";
        }
        "audio/fwdred";
        {
            "source";
            "iana";
        }
        "audio/g711-0";
        {
            "source";
            "iana";
        }
        "audio/g719";
        {
            "source";
            "iana";
        }
        "audio/g722";
        {
            "source";
            "iana";
        }
        "audio/g7221";
        {
            "source";
            "iana";
        }
        "audio/g723";
        {
            "source";
            "iana";
        }
        "audio/g726-16";
        {
            "source";
            "iana";
        }
        "audio/g726-24";
        {
            "source";
            "iana";
        }
        "audio/g726-32";
        {
            "source";
            "iana";
        }
        "audio/g726-40";
        {
            "source";
            "iana";
        }
        "audio/g728";
        {
            "source";
            "iana";
        }
        "audio/g729";
        {
            "source";
            "iana";
        }
        "audio/g7291";
        {
            "source";
            "iana";
        }
        "audio/g729d";
        {
            "source";
            "iana";
        }
        "audio/g729e";
        {
            "source";
            "iana";
        }
        "audio/gsm";
        {
            "source";
            "iana";
        }
        "audio/gsm-efr";
        {
            "source";
            "iana";
        }
        "audio/gsm-hr-08";
        {
            "source";
            "iana";
        }
        "audio/ilbc";
        {
            "source";
            "iana";
        }
        "audio/ip-mr_v2.5";
        {
            "source";
            "iana";
        }
        "audio/isac";
        {
            "source";
            "apache";
        }
        "audio/l16";
        {
            "source";
            "iana";
        }
        "audio/l20";
        {
            "source";
            "iana";
        }
        "audio/l24";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "audio/l8";
        {
            "source";
            "iana";
        }
        "audio/lpc";
        {
            "source";
            "iana";
        }
        "audio/melp";
        {
            "source";
            "iana";
        }
        "audio/melp1200";
        {
            "source";
            "iana";
        }
        "audio/melp2400";
        {
            "source";
            "iana";
        }
        "audio/melp600";
        {
            "source";
            "iana";
        }
        "audio/midi";
        {
            "source";
            "apache",
                "extensions";
            ["mid", "midi", "kar", "rmi"];
        }
        "audio/mobile-xmf";
        {
            "source";
            "iana";
        }
        "audio/mp3";
        {
            "compressible";
            false,
                "extensions";
            ["mp3"];
        }
        "audio/mp4";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["m4a", "mp4a"];
        }
        "audio/mp4a-latm";
        {
            "source";
            "iana";
        }
        "audio/mpa";
        {
            "source";
            "iana";
        }
        "audio/mpa-robust";
        {
            "source";
            "iana";
        }
        "audio/mpeg";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"];
        }
        "audio/mpeg4-generic";
        {
            "source";
            "iana";
        }
        "audio/musepack";
        {
            "source";
            "apache";
        }
        "audio/ogg";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["oga", "ogg", "spx"];
        }
        "audio/opus";
        {
            "source";
            "iana";
        }
        "audio/parityfec";
        {
            "source";
            "iana";
        }
        "audio/pcma";
        {
            "source";
            "iana";
        }
        "audio/pcma-wb";
        {
            "source";
            "iana";
        }
        "audio/pcmu";
        {
            "source";
            "iana";
        }
        "audio/pcmu-wb";
        {
            "source";
            "iana";
        }
        "audio/prs.sid";
        {
            "source";
            "iana";
        }
        "audio/qcelp";
        {
            "source";
            "iana";
        }
        "audio/raptorfec";
        {
            "source";
            "iana";
        }
        "audio/red";
        {
            "source";
            "iana";
        }
        "audio/rtp-enc-aescm128";
        {
            "source";
            "iana";
        }
        "audio/rtp-midi";
        {
            "source";
            "iana";
        }
        "audio/rtploopback";
        {
            "source";
            "iana";
        }
        "audio/rtx";
        {
            "source";
            "iana";
        }
        "audio/s3m";
        {
            "source";
            "apache",
                "extensions";
            ["s3m"];
        }
        "audio/silk";
        {
            "source";
            "apache",
                "extensions";
            ["sil"];
        }
        "audio/smv";
        {
            "source";
            "iana";
        }
        "audio/smv-qcp";
        {
            "source";
            "iana";
        }
        "audio/smv0";
        {
            "source";
            "iana";
        }
        "audio/sp-midi";
        {
            "source";
            "iana";
        }
        "audio/speex";
        {
            "source";
            "iana";
        }
        "audio/t140c";
        {
            "source";
            "iana";
        }
        "audio/t38";
        {
            "source";
            "iana";
        }
        "audio/telephone-event";
        {
            "source";
            "iana";
        }
        "audio/tone";
        {
            "source";
            "iana";
        }
        "audio/uemclip";
        {
            "source";
            "iana";
        }
        "audio/ulpfec";
        {
            "source";
            "iana";
        }
        "audio/usac";
        {
            "source";
            "iana";
        }
        "audio/vdvi";
        {
            "source";
            "iana";
        }
        "audio/vmr-wb";
        {
            "source";
            "iana";
        }
        "audio/vnd.3gpp.iufp";
        {
            "source";
            "iana";
        }
        "audio/vnd.4sb";
        {
            "source";
            "iana";
        }
        "audio/vnd.audiokoz";
        {
            "source";
            "iana";
        }
        "audio/vnd.celp";
        {
            "source";
            "iana";
        }
        "audio/vnd.cisco.nse";
        {
            "source";
            "iana";
        }
        "audio/vnd.cmles.radio-events";
        {
            "source";
            "iana";
        }
        "audio/vnd.cns.anp1";
        {
            "source";
            "iana";
        }
        "audio/vnd.cns.inf1";
        {
            "source";
            "iana";
        }
        "audio/vnd.dece.audio";
        {
            "source";
            "iana",
                "extensions";
            ["uva", "uvva"];
        }
        "audio/vnd.digital-winds";
        {
            "source";
            "iana",
                "extensions";
            ["eol"];
        }
        "audio/vnd.dlna.adts";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.heaac.1";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.heaac.2";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.mlp";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.mps";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.pl2";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.pl2x";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.pl2z";
        {
            "source";
            "iana";
        }
        "audio/vnd.dolby.pulse.1";
        {
            "source";
            "iana";
        }
        "audio/vnd.dra";
        {
            "source";
            "iana",
                "extensions";
            ["dra"];
        }
        "audio/vnd.dts";
        {
            "source";
            "iana",
                "extensions";
            ["dts"];
        }
        "audio/vnd.dts.hd";
        {
            "source";
            "iana",
                "extensions";
            ["dtshd"];
        }
        "audio/vnd.dvb.file";
        {
            "source";
            "iana";
        }
        "audio/vnd.everad.plj";
        {
            "source";
            "iana";
        }
        "audio/vnd.hns.audio";
        {
            "source";
            "iana";
        }
        "audio/vnd.lucent.voice";
        {
            "source";
            "iana",
                "extensions";
            ["lvp"];
        }
        "audio/vnd.ms-playready.media.pya";
        {
            "source";
            "iana",
                "extensions";
            ["pya"];
        }
        "audio/vnd.nokia.mobile-xmf";
        {
            "source";
            "iana";
        }
        "audio/vnd.nortel.vbk";
        {
            "source";
            "iana";
        }
        "audio/vnd.nuera.ecelp4800";
        {
            "source";
            "iana",
                "extensions";
            ["ecelp4800"];
        }
        "audio/vnd.nuera.ecelp7470";
        {
            "source";
            "iana",
                "extensions";
            ["ecelp7470"];
        }
        "audio/vnd.nuera.ecelp9600";
        {
            "source";
            "iana",
                "extensions";
            ["ecelp9600"];
        }
        "audio/vnd.octel.sbc";
        {
            "source";
            "iana";
        }
        "audio/vnd.presonus.multitrack";
        {
            "source";
            "iana";
        }
        "audio/vnd.qcelp";
        {
            "source";
            "iana";
        }
        "audio/vnd.rhetorex.32kadpcm";
        {
            "source";
            "iana";
        }
        "audio/vnd.rip";
        {
            "source";
            "iana",
                "extensions";
            ["rip"];
        }
        "audio/vnd.rn-realaudio";
        {
            "compressible";
            false;
        }
        "audio/vnd.sealedmedia.softseal.mpeg";
        {
            "source";
            "iana";
        }
        "audio/vnd.vmx.cvsd";
        {
            "source";
            "iana";
        }
        "audio/vnd.wave";
        {
            "compressible";
            false;
        }
        "audio/vorbis";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "audio/vorbis-config";
        {
            "source";
            "iana";
        }
        "audio/wav";
        {
            "compressible";
            false,
                "extensions";
            ["wav"];
        }
        "audio/wave";
        {
            "compressible";
            false,
                "extensions";
            ["wav"];
        }
        "audio/webm";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["weba"];
        }
        "audio/x-aac";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["aac"];
        }
        "audio/x-aiff";
        {
            "source";
            "apache",
                "extensions";
            ["aif", "aiff", "aifc"];
        }
        "audio/x-caf";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["caf"];
        }
        "audio/x-flac";
        {
            "source";
            "apache",
                "extensions";
            ["flac"];
        }
        "audio/x-m4a";
        {
            "source";
            "nginx",
                "extensions";
            ["m4a"];
        }
        "audio/x-matroska";
        {
            "source";
            "apache",
                "extensions";
            ["mka"];
        }
        "audio/x-mpegurl";
        {
            "source";
            "apache",
                "extensions";
            ["m3u"];
        }
        "audio/x-ms-wax";
        {
            "source";
            "apache",
                "extensions";
            ["wax"];
        }
        "audio/x-ms-wma";
        {
            "source";
            "apache",
                "extensions";
            ["wma"];
        }
        "audio/x-pn-realaudio";
        {
            "source";
            "apache",
                "extensions";
            ["ram", "ra"];
        }
        "audio/x-pn-realaudio-plugin";
        {
            "source";
            "apache",
                "extensions";
            ["rmp"];
        }
        "audio/x-realaudio";
        {
            "source";
            "nginx",
                "extensions";
            ["ra"];
        }
        "audio/x-tta";
        {
            "source";
            "apache";
        }
        "audio/x-wav";
        {
            "source";
            "apache",
                "extensions";
            ["wav"];
        }
        "audio/xm";
        {
            "source";
            "apache",
                "extensions";
            ["xm"];
        }
        "chemical/x-cdx";
        {
            "source";
            "apache",
                "extensions";
            ["cdx"];
        }
        "chemical/x-cif";
        {
            "source";
            "apache",
                "extensions";
            ["cif"];
        }
        "chemical/x-cmdf";
        {
            "source";
            "apache",
                "extensions";
            ["cmdf"];
        }
        "chemical/x-cml";
        {
            "source";
            "apache",
                "extensions";
            ["cml"];
        }
        "chemical/x-csml";
        {
            "source";
            "apache",
                "extensions";
            ["csml"];
        }
        "chemical/x-pdb";
        {
            "source";
            "apache";
        }
        "chemical/x-xyz";
        {
            "source";
            "apache",
                "extensions";
            ["xyz"];
        }
        "font/collection";
        {
            "source";
            "iana",
                "extensions";
            ["ttc"];
        }
        "font/otf";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["otf"];
        }
        "font/sfnt";
        {
            "source";
            "iana";
        }
        "font/ttf";
        {
            "source";
            "iana",
                "extensions";
            ["ttf"];
        }
        "font/woff";
        {
            "source";
            "iana",
                "extensions";
            ["woff"];
        }
        "font/woff2";
        {
            "source";
            "iana",
                "extensions";
            ["woff2"];
        }
        "image/aces";
        {
            "source";
            "iana",
                "extensions";
            ["exr"];
        }
        "image/apng";
        {
            "compressible";
            false,
                "extensions";
            ["apng"];
        }
        "image/avci";
        {
            "source";
            "iana";
        }
        "image/avcs";
        {
            "source";
            "iana";
        }
        "image/bmp";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["bmp"];
        }
        "image/cgm";
        {
            "source";
            "iana",
                "extensions";
            ["cgm"];
        }
        "image/dicom-rle";
        {
            "source";
            "iana",
                "extensions";
            ["drle"];
        }
        "image/emf";
        {
            "source";
            "iana",
                "extensions";
            ["emf"];
        }
        "image/fits";
        {
            "source";
            "iana",
                "extensions";
            ["fits"];
        }
        "image/g3fax";
        {
            "source";
            "iana",
                "extensions";
            ["g3"];
        }
        "image/gif";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["gif"];
        }
        "image/heic";
        {
            "source";
            "iana";
        }
        "image/heic-sequence";
        {
            "source";
            "iana";
        }
        "image/heif";
        {
            "source";
            "iana";
        }
        "image/heif-sequence";
        {
            "source";
            "iana";
        }
        "image/ief";
        {
            "source";
            "iana",
                "extensions";
            ["ief"];
        }
        "image/jls";
        {
            "source";
            "iana",
                "extensions";
            ["jls"];
        }
        "image/jp2";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["jp2", "jpg2"];
        }
        "image/jpeg";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["jpeg", "jpg", "jpe"];
        }
        "image/jpm";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["jpm"];
        }
        "image/jpx";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["jpx", "jpf"];
        }
        "image/ktx";
        {
            "source";
            "iana",
                "extensions";
            ["ktx"];
        }
        "image/naplps";
        {
            "source";
            "iana";
        }
        "image/pjpeg";
        {
            "compressible";
            false;
        }
        "image/png";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["png"];
        }
        "image/prs.btif";
        {
            "source";
            "iana",
                "extensions";
            ["btif"];
        }
        "image/prs.pti";
        {
            "source";
            "iana",
                "extensions";
            ["pti"];
        }
        "image/pwg-raster";
        {
            "source";
            "iana";
        }
        "image/sgi";
        {
            "source";
            "apache",
                "extensions";
            ["sgi"];
        }
        "image/svg+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["svg", "svgz"];
        }
        "image/t38";
        {
            "source";
            "iana",
                "extensions";
            ["t38"];
        }
        "image/tiff";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["tif", "tiff"];
        }
        "image/tiff-fx";
        {
            "source";
            "iana",
                "extensions";
            ["tfx"];
        }
        "image/vnd.adobe.photoshop";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["psd"];
        }
        "image/vnd.airzip.accelerator.azv";
        {
            "source";
            "iana",
                "extensions";
            ["azv"];
        }
        "image/vnd.cns.inf2";
        {
            "source";
            "iana";
        }
        "image/vnd.dece.graphic";
        {
            "source";
            "iana",
                "extensions";
            ["uvi", "uvvi", "uvg", "uvvg"];
        }
        "image/vnd.djvu";
        {
            "source";
            "iana",
                "extensions";
            ["djvu", "djv"];
        }
        "image/vnd.dvb.subtitle";
        {
            "source";
            "iana",
                "extensions";
            ["sub"];
        }
        "image/vnd.dwg";
        {
            "source";
            "iana",
                "extensions";
            ["dwg"];
        }
        "image/vnd.dxf";
        {
            "source";
            "iana",
                "extensions";
            ["dxf"];
        }
        "image/vnd.fastbidsheet";
        {
            "source";
            "iana",
                "extensions";
            ["fbs"];
        }
        "image/vnd.fpx";
        {
            "source";
            "iana",
                "extensions";
            ["fpx"];
        }
        "image/vnd.fst";
        {
            "source";
            "iana",
                "extensions";
            ["fst"];
        }
        "image/vnd.fujixerox.edmics-mmr";
        {
            "source";
            "iana",
                "extensions";
            ["mmr"];
        }
        "image/vnd.fujixerox.edmics-rlc";
        {
            "source";
            "iana",
                "extensions";
            ["rlc"];
        }
        "image/vnd.globalgraphics.pgb";
        {
            "source";
            "iana";
        }
        "image/vnd.microsoft.icon";
        {
            "source";
            "iana",
                "extensions";
            ["ico"];
        }
        "image/vnd.mix";
        {
            "source";
            "iana";
        }
        "image/vnd.mozilla.apng";
        {
            "source";
            "iana";
        }
        "image/vnd.ms-modi";
        {
            "source";
            "iana",
                "extensions";
            ["mdi"];
        }
        "image/vnd.ms-photo";
        {
            "source";
            "apache",
                "extensions";
            ["wdp"];
        }
        "image/vnd.net-fpx";
        {
            "source";
            "iana",
                "extensions";
            ["npx"];
        }
        "image/vnd.radiance";
        {
            "source";
            "iana";
        }
        "image/vnd.sealed.png";
        {
            "source";
            "iana";
        }
        "image/vnd.sealedmedia.softseal.gif";
        {
            "source";
            "iana";
        }
        "image/vnd.sealedmedia.softseal.jpg";
        {
            "source";
            "iana";
        }
        "image/vnd.svf";
        {
            "source";
            "iana";
        }
        "image/vnd.tencent.tap";
        {
            "source";
            "iana",
                "extensions";
            ["tap"];
        }
        "image/vnd.valve.source.texture";
        {
            "source";
            "iana",
                "extensions";
            ["vtf"];
        }
        "image/vnd.wap.wbmp";
        {
            "source";
            "iana",
                "extensions";
            ["wbmp"];
        }
        "image/vnd.xiff";
        {
            "source";
            "iana",
                "extensions";
            ["xif"];
        }
        "image/vnd.zbrush.pcx";
        {
            "source";
            "iana",
                "extensions";
            ["pcx"];
        }
        "image/webp";
        {
            "source";
            "apache",
                "extensions";
            ["webp"];
        }
        "image/wmf";
        {
            "source";
            "iana",
                "extensions";
            ["wmf"];
        }
        "image/x-3ds";
        {
            "source";
            "apache",
                "extensions";
            ["3ds"];
        }
        "image/x-cmu-raster";
        {
            "source";
            "apache",
                "extensions";
            ["ras"];
        }
        "image/x-cmx";
        {
            "source";
            "apache",
                "extensions";
            ["cmx"];
        }
        "image/x-freehand";
        {
            "source";
            "apache",
                "extensions";
            ["fh", "fhc", "fh4", "fh5", "fh7"];
        }
        "image/x-icon";
        {
            "source";
            "apache",
                "compressible";
            true,
                "extensions";
            ["ico"];
        }
        "image/x-jng";
        {
            "source";
            "nginx",
                "extensions";
            ["jng"];
        }
        "image/x-mrsid-image";
        {
            "source";
            "apache",
                "extensions";
            ["sid"];
        }
        "image/x-ms-bmp";
        {
            "source";
            "nginx",
                "compressible";
            true,
                "extensions";
            ["bmp"];
        }
        "image/x-pcx";
        {
            "source";
            "apache",
                "extensions";
            ["pcx"];
        }
        "image/x-pict";
        {
            "source";
            "apache",
                "extensions";
            ["pic", "pct"];
        }
        "image/x-portable-anymap";
        {
            "source";
            "apache",
                "extensions";
            ["pnm"];
        }
        "image/x-portable-bitmap";
        {
            "source";
            "apache",
                "extensions";
            ["pbm"];
        }
        "image/x-portable-graymap";
        {
            "source";
            "apache",
                "extensions";
            ["pgm"];
        }
        "image/x-portable-pixmap";
        {
            "source";
            "apache",
                "extensions";
            ["ppm"];
        }
        "image/x-rgb";
        {
            "source";
            "apache",
                "extensions";
            ["rgb"];
        }
        "image/x-tga";
        {
            "source";
            "apache",
                "extensions";
            ["tga"];
        }
        "image/x-xbitmap";
        {
            "source";
            "apache",
                "extensions";
            ["xbm"];
        }
        "image/x-xcf";
        {
            "compressible";
            false;
        }
        "image/x-xpixmap";
        {
            "source";
            "apache",
                "extensions";
            ["xpm"];
        }
        "image/x-xwindowdump";
        {
            "source";
            "apache",
                "extensions";
            ["xwd"];
        }
        "message/cpim";
        {
            "source";
            "iana";
        }
        "message/delivery-status";
        {
            "source";
            "iana";
        }
        "message/disposition-notification";
        {
            "source";
            "iana",
                "extensions";
            [
                "disposition-notification"
            ];
        }
        "message/external-body";
        {
            "source";
            "iana";
        }
        "message/feedback-report";
        {
            "source";
            "iana";
        }
        "message/global";
        {
            "source";
            "iana",
                "extensions";
            ["u8msg"];
        }
        "message/global-delivery-status";
        {
            "source";
            "iana",
                "extensions";
            ["u8dsn"];
        }
        "message/global-disposition-notification";
        {
            "source";
            "iana",
                "extensions";
            ["u8mdn"];
        }
        "message/global-headers";
        {
            "source";
            "iana",
                "extensions";
            ["u8hdr"];
        }
        "message/http";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "message/imdn+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "message/news";
        {
            "source";
            "iana";
        }
        "message/partial";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "message/rfc822";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["eml", "mime"];
        }
        "message/s-http";
        {
            "source";
            "iana";
        }
        "message/sip";
        {
            "source";
            "iana";
        }
        "message/sipfrag";
        {
            "source";
            "iana";
        }
        "message/tracking-status";
        {
            "source";
            "iana";
        }
        "message/vnd.si.simp";
        {
            "source";
            "iana";
        }
        "message/vnd.wfa.wsc";
        {
            "source";
            "iana",
                "extensions";
            ["wsc"];
        }
        "model/3mf";
        {
            "source";
            "iana";
        }
        "model/gltf+json";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["gltf"];
        }
        "model/gltf-binary";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["glb"];
        }
        "model/iges";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["igs", "iges"];
        }
        "model/mesh";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["msh", "mesh", "silo"];
        }
        "model/stl";
        {
            "source";
            "iana";
        }
        "model/vnd.collada+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["dae"];
        }
        "model/vnd.dwf";
        {
            "source";
            "iana",
                "extensions";
            ["dwf"];
        }
        "model/vnd.flatland.3dml";
        {
            "source";
            "iana";
        }
        "model/vnd.gdl";
        {
            "source";
            "iana",
                "extensions";
            ["gdl"];
        }
        "model/vnd.gs-gdl";
        {
            "source";
            "apache";
        }
        "model/vnd.gs.gdl";
        {
            "source";
            "iana";
        }
        "model/vnd.gtw";
        {
            "source";
            "iana",
                "extensions";
            ["gtw"];
        }
        "model/vnd.moml+xml";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "model/vnd.mts";
        {
            "source";
            "iana",
                "extensions";
            ["mts"];
        }
        "model/vnd.opengex";
        {
            "source";
            "iana";
        }
        "model/vnd.parasolid.transmit.binary";
        {
            "source";
            "iana";
        }
        "model/vnd.parasolid.transmit.text";
        {
            "source";
            "iana";
        }
        "model/vnd.rosette.annotated-data-model";
        {
            "source";
            "iana";
        }
        "model/vnd.usdz+zip";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "model/vnd.valve.source.compiled-map";
        {
            "source";
            "iana";
        }
        "model/vnd.vtu";
        {
            "source";
            "iana",
                "extensions";
            ["vtu"];
        }
        "model/vrml";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["wrl", "vrml"];
        }
        "model/x3d+binary";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["x3db", "x3dbz"];
        }
        "model/x3d+fastinfoset";
        {
            "source";
            "iana";
        }
        "model/x3d+vrml";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["x3dv", "x3dvz"];
        }
        "model/x3d+xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["x3d", "x3dz"];
        }
        "model/x3d-vrml";
        {
            "source";
            "iana";
        }
        "multipart/alternative";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "multipart/appledouble";
        {
            "source";
            "iana";
        }
        "multipart/byteranges";
        {
            "source";
            "iana";
        }
        "multipart/digest";
        {
            "source";
            "iana";
        }
        "multipart/encrypted";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "multipart/form-data";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "multipart/header-set";
        {
            "source";
            "iana";
        }
        "multipart/mixed";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "multipart/multilingual";
        {
            "source";
            "iana";
        }
        "multipart/parallel";
        {
            "source";
            "iana";
        }
        "multipart/related";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "multipart/report";
        {
            "source";
            "iana";
        }
        "multipart/signed";
        {
            "source";
            "iana",
                "compressible";
            false;
        }
        "multipart/vnd.bint.med-plus";
        {
            "source";
            "iana";
        }
        "multipart/voice-message";
        {
            "source";
            "iana";
        }
        "multipart/x-mixed-replace";
        {
            "source";
            "iana";
        }
        "text/1d-interleaved-parityfec";
        {
            "source";
            "iana";
        }
        "text/cache-manifest";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["appcache", "manifest"];
        }
        "text/calendar";
        {
            "source";
            "iana",
                "extensions";
            ["ics", "ifb"];
        }
        "text/calender";
        {
            "compressible";
            true;
        }
        "text/cmd";
        {
            "compressible";
            true;
        }
        "text/coffeescript";
        {
            "extensions";
            ["coffee", "litcoffee"];
        }
        "text/css";
        {
            "source";
            "iana",
                "charset";
            "UTF-8",
                "compressible";
            true,
                "extensions";
            ["css"];
        }
        "text/csv";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["csv"];
        }
        "text/csv-schema";
        {
            "source";
            "iana";
        }
        "text/directory";
        {
            "source";
            "iana";
        }
        "text/dns";
        {
            "source";
            "iana";
        }
        "text/ecmascript";
        {
            "source";
            "iana";
        }
        "text/encaprtp";
        {
            "source";
            "iana";
        }
        "text/enriched";
        {
            "source";
            "iana";
        }
        "text/fwdred";
        {
            "source";
            "iana";
        }
        "text/grammar-ref-list";
        {
            "source";
            "iana";
        }
        "text/html";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["html", "htm", "shtml"];
        }
        "text/jade";
        {
            "extensions";
            ["jade"];
        }
        "text/javascript";
        {
            "source";
            "iana",
                "compressible";
            true;
        }
        "text/jcr-cnd";
        {
            "source";
            "iana";
        }
        "text/jsx";
        {
            "compressible";
            true,
                "extensions";
            ["jsx"];
        }
        "text/less";
        {
            "extensions";
            ["less"];
        }
        "text/markdown";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["markdown", "md"];
        }
        "text/mathml";
        {
            "source";
            "nginx",
                "extensions";
            ["mml"];
        }
        "text/mizar";
        {
            "source";
            "iana";
        }
        "text/n3";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["n3"];
        }
        "text/parameters";
        {
            "source";
            "iana";
        }
        "text/parityfec";
        {
            "source";
            "iana";
        }
        "text/plain";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["txt", "text", "conf", "def", "list", "log", "in", "ini"];
        }
        "text/provenance-notation";
        {
            "source";
            "iana";
        }
        "text/prs.fallenstein.rst";
        {
            "source";
            "iana";
        }
        "text/prs.lines.tag";
        {
            "source";
            "iana",
                "extensions";
            ["dsc"];
        }
        "text/prs.prop.logic";
        {
            "source";
            "iana";
        }
        "text/raptorfec";
        {
            "source";
            "iana";
        }
        "text/red";
        {
            "source";
            "iana";
        }
        "text/rfc822-headers";
        {
            "source";
            "iana";
        }
        "text/richtext";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rtx"];
        }
        "text/rtf";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["rtf"];
        }
        "text/rtp-enc-aescm128";
        {
            "source";
            "iana";
        }
        "text/rtploopback";
        {
            "source";
            "iana";
        }
        "text/rtx";
        {
            "source";
            "iana";
        }
        "text/sgml";
        {
            "source";
            "iana",
                "extensions";
            ["sgml", "sgm"];
        }
        "text/shex";
        {
            "extensions";
            ["shex"];
        }
        "text/slim";
        {
            "extensions";
            ["slim", "slm"];
        }
        "text/strings";
        {
            "source";
            "iana";
        }
        "text/stylus";
        {
            "extensions";
            ["stylus", "styl"];
        }
        "text/t140";
        {
            "source";
            "iana";
        }
        "text/tab-separated-values";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["tsv"];
        }
        "text/troff";
        {
            "source";
            "iana",
                "extensions";
            ["t", "tr", "roff", "man", "me", "ms"];
        }
        "text/turtle";
        {
            "source";
            "iana",
                "charset";
            "UTF-8",
                "extensions";
            ["ttl"];
        }
        "text/ulpfec";
        {
            "source";
            "iana";
        }
        "text/uri-list";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["uri", "uris", "urls"];
        }
        "text/vcard";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["vcard"];
        }
        "text/vnd.a";
        {
            "source";
            "iana";
        }
        "text/vnd.abc";
        {
            "source";
            "iana";
        }
        "text/vnd.ascii-art";
        {
            "source";
            "iana";
        }
        "text/vnd.curl";
        {
            "source";
            "iana",
                "extensions";
            ["curl"];
        }
        "text/vnd.curl.dcurl";
        {
            "source";
            "apache",
                "extensions";
            ["dcurl"];
        }
        "text/vnd.curl.mcurl";
        {
            "source";
            "apache",
                "extensions";
            ["mcurl"];
        }
        "text/vnd.curl.scurl";
        {
            "source";
            "apache",
                "extensions";
            ["scurl"];
        }
        "text/vnd.debian.copyright";
        {
            "source";
            "iana";
        }
        "text/vnd.dmclientscript";
        {
            "source";
            "iana";
        }
        "text/vnd.dvb.subtitle";
        {
            "source";
            "iana",
                "extensions";
            ["sub"];
        }
        "text/vnd.esmertec.theme-descriptor";
        {
            "source";
            "iana";
        }
        "text/vnd.fly";
        {
            "source";
            "iana",
                "extensions";
            ["fly"];
        }
        "text/vnd.fmi.flexstor";
        {
            "source";
            "iana",
                "extensions";
            ["flx"];
        }
        "text/vnd.gml";
        {
            "source";
            "iana";
        }
        "text/vnd.graphviz";
        {
            "source";
            "iana",
                "extensions";
            ["gv"];
        }
        "text/vnd.hgl";
        {
            "source";
            "iana";
        }
        "text/vnd.in3d.3dml";
        {
            "source";
            "iana",
                "extensions";
            ["3dml"];
        }
        "text/vnd.in3d.spot";
        {
            "source";
            "iana",
                "extensions";
            ["spot"];
        }
        "text/vnd.iptc.newsml";
        {
            "source";
            "iana";
        }
        "text/vnd.iptc.nitf";
        {
            "source";
            "iana";
        }
        "text/vnd.latex-z";
        {
            "source";
            "iana";
        }
        "text/vnd.motorola.reflex";
        {
            "source";
            "iana";
        }
        "text/vnd.ms-mediapackage";
        {
            "source";
            "iana";
        }
        "text/vnd.net2phone.commcenter.command";
        {
            "source";
            "iana";
        }
        "text/vnd.radisys.msml-basic-layout";
        {
            "source";
            "iana";
        }
        "text/vnd.si.uricatalogue";
        {
            "source";
            "iana";
        }
        "text/vnd.sun.j2me.app-descriptor";
        {
            "source";
            "iana",
                "extensions";
            ["jad"];
        }
        "text/vnd.trolltech.linguist";
        {
            "source";
            "iana";
        }
        "text/vnd.wap.si";
        {
            "source";
            "iana";
        }
        "text/vnd.wap.sl";
        {
            "source";
            "iana";
        }
        "text/vnd.wap.wml";
        {
            "source";
            "iana",
                "extensions";
            ["wml"];
        }
        "text/vnd.wap.wmlscript";
        {
            "source";
            "iana",
                "extensions";
            ["wmls"];
        }
        "text/vtt";
        {
            "charset";
            "UTF-8",
                "compressible";
            true,
                "extensions";
            ["vtt"];
        }
        "text/x-asm";
        {
            "source";
            "apache",
                "extensions";
            ["s", "asm"];
        }
        "text/x-c";
        {
            "source";
            "apache",
                "extensions";
            ["c", "cc", "cxx", "cpp", "h", "hh", "dic"];
        }
        "text/x-component";
        {
            "source";
            "nginx",
                "extensions";
            ["htc"];
        }
        "text/x-fortran";
        {
            "source";
            "apache",
                "extensions";
            ["f", "for", "f77", "f90"];
        }
        "text/x-gwt-rpc";
        {
            "compressible";
            true;
        }
        "text/x-handlebars-template";
        {
            "extensions";
            ["hbs"];
        }
        "text/x-java-source";
        {
            "source";
            "apache",
                "extensions";
            ["java"];
        }
        "text/x-jquery-tmpl";
        {
            "compressible";
            true;
        }
        "text/x-lua";
        {
            "extensions";
            ["lua"];
        }
        "text/x-markdown";
        {
            "compressible";
            true,
                "extensions";
            ["mkd"];
        }
        "text/x-nfo";
        {
            "source";
            "apache",
                "extensions";
            ["nfo"];
        }
        "text/x-opml";
        {
            "source";
            "apache",
                "extensions";
            ["opml"];
        }
        "text/x-org";
        {
            "compressible";
            true,
                "extensions";
            ["org"];
        }
        "text/x-pascal";
        {
            "source";
            "apache",
                "extensions";
            ["p", "pas"];
        }
        "text/x-processing";
        {
            "compressible";
            true,
                "extensions";
            ["pde"];
        }
        "text/x-sass";
        {
            "extensions";
            ["sass"];
        }
        "text/x-scss";
        {
            "extensions";
            ["scss"];
        }
        "text/x-setext";
        {
            "source";
            "apache",
                "extensions";
            ["etx"];
        }
        "text/x-sfv";
        {
            "source";
            "apache",
                "extensions";
            ["sfv"];
        }
        "text/x-suse-ymp";
        {
            "compressible";
            true,
                "extensions";
            ["ymp"];
        }
        "text/x-uuencode";
        {
            "source";
            "apache",
                "extensions";
            ["uu"];
        }
        "text/x-vcalendar";
        {
            "source";
            "apache",
                "extensions";
            ["vcs"];
        }
        "text/x-vcard";
        {
            "source";
            "apache",
                "extensions";
            ["vcf"];
        }
        "text/xml";
        {
            "source";
            "iana",
                "compressible";
            true,
                "extensions";
            ["xml"];
        }
        "text/xml-external-parsed-entity";
        {
            "source";
            "iana";
        }
        "text/yaml";
        {
            "extensions";
            ["yaml", "yml"];
        }
        "video/1d-interleaved-parityfec";
        {
            "source";
            "iana";
        }
        "video/3gpp";
        {
            "source";
            "iana",
                "extensions";
            ["3gp", "3gpp"];
        }
        "video/3gpp-tt";
        {
            "source";
            "iana";
        }
        "video/3gpp2";
        {
            "source";
            "iana",
                "extensions";
            ["3g2"];
        }
        "video/bmpeg";
        {
            "source";
            "iana";
        }
        "video/bt656";
        {
            "source";
            "iana";
        }
        "video/celb";
        {
            "source";
            "iana";
        }
        "video/dv";
        {
            "source";
            "iana";
        }
        "video/encaprtp";
        {
            "source";
            "iana";
        }
        "video/h261";
        {
            "source";
            "iana",
                "extensions";
            ["h261"];
        }
        "video/h263";
        {
            "source";
            "iana",
                "extensions";
            ["h263"];
        }
        "video/h263-1998";
        {
            "source";
            "iana";
        }
        "video/h263-2000";
        {
            "source";
            "iana";
        }
        "video/h264";
        {
            "source";
            "iana",
                "extensions";
            ["h264"];
        }
        "video/h264-rcdo";
        {
            "source";
            "iana";
        }
        "video/h264-svc";
        {
            "source";
            "iana";
        }
        "video/h265";
        {
            "source";
            "iana";
        }
        "video/iso.segment";
        {
            "source";
            "iana";
        }
        "video/jpeg";
        {
            "source";
            "iana",
                "extensions";
            ["jpgv"];
        }
        "video/jpeg2000";
        {
            "source";
            "iana";
        }
        "video/jpm";
        {
            "source";
            "apache",
                "extensions";
            ["jpm", "jpgm"];
        }
        "video/mj2";
        {
            "source";
            "iana",
                "extensions";
            ["mj2", "mjp2"];
        }
        "video/mp1s";
        {
            "source";
            "iana";
        }
        "video/mp2p";
        {
            "source";
            "iana";
        }
        "video/mp2t";
        {
            "source";
            "iana",
                "extensions";
            ["ts"];
        }
        "video/mp4";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["mp4", "mp4v", "mpg4"];
        }
        "video/mp4v-es";
        {
            "source";
            "iana";
        }
        "video/mpeg";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["mpeg", "mpg", "mpe", "m1v", "m2v"];
        }
        "video/mpeg4-generic";
        {
            "source";
            "iana";
        }
        "video/mpv";
        {
            "source";
            "iana";
        }
        "video/nv";
        {
            "source";
            "iana";
        }
        "video/ogg";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["ogv"];
        }
        "video/parityfec";
        {
            "source";
            "iana";
        }
        "video/pointer";
        {
            "source";
            "iana";
        }
        "video/quicktime";
        {
            "source";
            "iana",
                "compressible";
            false,
                "extensions";
            ["qt", "mov"];
        }
        "video/raptorfec";
        {
            "source";
            "iana";
        }
        "video/raw";
        {
            "source";
            "iana";
        }
        "video/rtp-enc-aescm128";
        {
            "source";
            "iana";
        }
        "video/rtploopback";
        {
            "source";
            "iana";
        }
        "video/rtx";
        {
            "source";
            "iana";
        }
        "video/smpte291";
        {
            "source";
            "iana";
        }
        "video/smpte292m";
        {
            "source";
            "iana";
        }
        "video/ulpfec";
        {
            "source";
            "iana";
        }
        "video/vc1";
        {
            "source";
            "iana";
        }
        "video/vnd.cctv";
        {
            "source";
            "iana";
        }
        "video/vnd.dece.hd";
        {
            "source";
            "iana",
                "extensions";
            ["uvh", "uvvh"];
        }
        "video/vnd.dece.mobile";
        {
            "source";
            "iana",
                "extensions";
            ["uvm", "uvvm"];
        }
        "video/vnd.dece.mp4";
        {
            "source";
            "iana";
        }
        "video/vnd.dece.pd";
        {
            "source";
            "iana",
                "extensions";
            ["uvp", "uvvp"];
        }
        "video/vnd.dece.sd";
        {
            "source";
            "iana",
                "extensions";
            ["uvs", "uvvs"];
        }
        "video/vnd.dece.video";
        {
            "source";
            "iana",
                "extensions";
            ["uvv", "uvvv"];
        }
        "video/vnd.directv.mpeg";
        {
            "source";
            "iana";
        }
        "video/vnd.directv.mpeg-tts";
        {
            "source";
            "iana";
        }
        "video/vnd.dlna.mpeg-tts";
        {
            "source";
            "iana";
        }
        "video/vnd.dvb.file";
        {
            "source";
            "iana",
                "extensions";
            ["dvb"];
        }
        "video/vnd.fvt";
        {
            "source";
            "iana",
                "extensions";
            ["fvt"];
        }
        "video/vnd.hns.video";
        {
            "source";
            "iana";
        }
        "video/vnd.iptvforum.1dparityfec-1010";
        {
            "source";
            "iana";
        }
        "video/vnd.iptvforum.1dparityfec-2005";
        {
            "source";
            "iana";
        }
        "video/vnd.iptvforum.2dparityfec-1010";
        {
            "source";
            "iana";
        }
        "video/vnd.iptvforum.2dparityfec-2005";
        {
            "source";
            "iana";
        }
        "video/vnd.iptvforum.ttsavc";
        {
            "source";
            "iana";
        }
        "video/vnd.iptvforum.ttsmpeg2";
        {
            "source";
            "iana";
        }
        "video/vnd.motorola.video";
        {
            "source";
            "iana";
        }
        "video/vnd.motorola.videop";
        {
            "source";
            "iana";
        }
        "video/vnd.mpegurl";
        {
            "source";
            "iana",
                "extensions";
            ["mxu", "m4u"];
        }
        "video/vnd.ms-playready.media.pyv";
        {
            "source";
            "iana",
                "extensions";
            ["pyv"];
        }
        "video/vnd.nokia.interleaved-multimedia";
        {
            "source";
            "iana";
        }
        "video/vnd.nokia.mp4vr";
        {
            "source";
            "iana";
        }
        "video/vnd.nokia.videovoip";
        {
            "source";
            "iana";
        }
        "video/vnd.objectvideo";
        {
            "source";
            "iana";
        }
        "video/vnd.radgamettools.bink";
        {
            "source";
            "iana";
        }
        "video/vnd.radgamettools.smacker";
        {
            "source";
            "iana";
        }
        "video/vnd.sealed.mpeg1";
        {
            "source";
            "iana";
        }
        "video/vnd.sealed.mpeg4";
        {
            "source";
            "iana";
        }
        "video/vnd.sealed.swf";
        {
            "source";
            "iana";
        }
        "video/vnd.sealedmedia.softseal.mov";
        {
            "source";
            "iana";
        }
        "video/vnd.uvvu.mp4";
        {
            "source";
            "iana",
                "extensions";
            ["uvu", "uvvu"];
        }
        "video/vnd.vivo";
        {
            "source";
            "iana",
                "extensions";
            ["viv"];
        }
        "video/vp8";
        {
            "source";
            "iana";
        }
        "video/webm";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["webm"];
        }
        "video/x-f4v";
        {
            "source";
            "apache",
                "extensions";
            ["f4v"];
        }
        "video/x-fli";
        {
            "source";
            "apache",
                "extensions";
            ["fli"];
        }
        "video/x-flv";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["flv"];
        }
        "video/x-m4v";
        {
            "source";
            "apache",
                "extensions";
            ["m4v"];
        }
        "video/x-matroska";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["mkv", "mk3d", "mks"];
        }
        "video/x-mng";
        {
            "source";
            "apache",
                "extensions";
            ["mng"];
        }
        "video/x-ms-asf";
        {
            "source";
            "apache",
                "extensions";
            ["asf", "asx"];
        }
        "video/x-ms-vob";
        {
            "source";
            "apache",
                "extensions";
            ["vob"];
        }
        "video/x-ms-wm";
        {
            "source";
            "apache",
                "extensions";
            ["wm"];
        }
        "video/x-ms-wmv";
        {
            "source";
            "apache",
                "compressible";
            false,
                "extensions";
            ["wmv"];
        }
        "video/x-ms-wmx";
        {
            "source";
            "apache",
                "extensions";
            ["wmx"];
        }
        "video/x-ms-wvx";
        {
            "source";
            "apache",
                "extensions";
            ["wvx"];
        }
        "video/x-msvideo";
        {
            "source";
            "apache",
                "extensions";
            ["avi"];
        }
        "video/x-sgi-movie";
        {
            "source";
            "apache",
                "extensions";
            ["movie"];
        }
        "video/x-smv";
        {
            "source";
            "apache",
                "extensions";
            ["smv"];
        }
        "x-conference/x-cooltalk";
        {
            "source";
            "apache",
                "extensions";
            ["ice"];
        }
        "x-shader/x-fragment";
        {
            "compressible";
            true;
        }
        "x-shader/x-vertex";
        {
            "compressible";
            true;
        }
    }
}
,
/* mime-db/index */ function _(require, module, exports) {
    /*!
     * mime-db
     * Copyright(c) 2014 Jonathan Ong
     * MIT Licensed
     */
    /**
     * Module exports.
     */
    module.exports = require(263) /* ./db.json */;
}
,
/* mime-types/index */ function _(require, module, exports) {
    /**
     * Module dependencies.
     * @private
     */
    var db = require(264) /* mime-db */;
    var extname = require('path').extname;
    /**
     * Module variables.
     * @private
     */
    var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
    var TEXT_TYPE_REGEXP = /^text\//i;
    /**
     * Module exports.
     * @public
     */
    exports.charset = charset;
    exports.charsets = { lookup: charset };
    exports.contentType = contentType;
    exports.extension = extension;
    exports.extensions = Object.create(null);
    exports.lookup = lookup;
    exports.types = Object.create(null);
    // Populate the extensions/types maps
    populateMaps(exports.extensions, exports.types);
    /**
     * Get the default charset for a MIME type.
     *
     * @param {string} type
     * @return {boolean|string}
     */
    function charset(type) {
        if (!type || typeof type !== 'string') {
            return false;
        }
        // TODO: use media-typer
        var match = EXTRACT_TYPE_REGEXP.exec(type);
        var mime = match && db[match[1].toLowerCase()];
        if (mime && mime.charset) {
            return mime.charset;
        }
        // default text/* to utf-8
        if (match && TEXT_TYPE_REGEXP.test(match[1])) {
            return 'UTF-8';
        }
        return false;
    }
    /**
     * Create a full Content-Type header given a MIME type or extension.
     *
     * @param {string} str
     * @return {boolean|string}
     */
    function contentType(str) {
        // TODO: should this even be in this module?
        if (!str || typeof str !== 'string') {
            return false;
        }
        var mime = str.indexOf('/') === -1
            ? exports.lookup(str)
            : str;
        if (!mime) {
            return false;
        }
        // TODO: use content-type or other module
        if (mime.indexOf('charset') === -1) {
            var charset = exports.charset(mime);
            if (charset)
                mime += '; charset=' + charset.toLowerCase();
        }
        return mime;
    }
    /**
     * Get the default extension for a MIME type.
     *
     * @param {string} type
     * @return {boolean|string}
     */
    function extension(type) {
        if (!type || typeof type !== 'string') {
            return false;
        }
        // TODO: use media-typer
        var match = EXTRACT_TYPE_REGEXP.exec(type);
        // get extensions
        var exts = match && exports.extensions[match[1].toLowerCase()];
        if (!exts || !exts.length) {
            return false;
        }
        return exts[0];
    }
    /**
     * Lookup the MIME type for a file path/extension.
     *
     * @param {string} path
     * @return {boolean|string}
     */
    function lookup(path) {
        if (!path || typeof path !== 'string') {
            return false;
        }
        // get the extension ("ext" or ".ext" or full path)
        var extension = extname('x.' + path)
            .toLowerCase()
            .substr(1);
        if (!extension) {
            return false;
        }
        return exports.types[extension] || false;
    }
    /**
     * Populate the extensions and types maps.
     * @private
     */
    function populateMaps(extensions, types) {
        // source preference (least -> most)
        var preference = ['nginx', 'apache', undefined, 'iana'];
        Object.keys(db).forEach(function forEachMimeType(type) {
            var mime = db[type];
            var exts = mime.extensions;
            if (!exts || !exts.length) {
                return;
            }
            // mime -> extensions
            extensions[type] = exts;
            // extension -> mime
            for (var i = 0; i < exts.length; i++) {
                var extension = exts[i];
                if (types[extension]) {
                    var from = preference.indexOf(db[types[extension]].source);
                    var to = preference.indexOf(mime.source);
                    if (types[extension] !== 'application/octet-stream' &&
                        (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
                        // skip the remapping
                        continue;
                    }
                }
                // set the extension -> mime
                types[extension] = type;
            }
        });
    }
}
,
/* mime/mime */ function _(require, module, exports) {
    var path = require('path');
    var fs = require('fs');
    function Mime() {
        // Map of extension -> mime type
        this.types = Object.create(null);
        // Map of mime type -> extension
        this.extensions = Object.create(null);
    }
    /**
     * Define mimetype -> extension mappings.  Each key is a mime-type that maps
     * to an array of extensions associated with the type.  The first extension is
     * used as the default extension for the type.
     *
     * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
     *
     * @param map (Object) type definitions
     */
    Mime.prototype.define = function (map) {
        for (var type in map) {
            var exts = map[type];
            for (var i = 0; i < exts.length; i++) {
                if (process.env.DEBUG_MIME && this.types[exts[i]]) {
                    console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
                        this.types[exts[i]] + ' to ' + type);
                }
                this.types[exts[i]] = type;
            }
            // Default extension is the first one we encounter
            if (!this.extensions[type]) {
                this.extensions[type] = exts[0];
            }
        }
    };
    /**
     * Load an Apache2-style ".types" file
     *
     * This may be called multiple times (it's expected).  Where files declare
     * overlapping types/extensions, the last file wins.
     *
     * @param file (String) path of file to load.
     */
    Mime.prototype.load = function (file) {
        this._loading = file;
        // Read file and split into lines
        var map = {}, content = fs.readFileSync(file, 'ascii'), lines = content.split(/[\r\n]+/);
        lines.forEach(function (line) {
            // Clean up whitespace/comments, and split into fields
            var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
            map[fields.shift()] = fields;
        });
        this.define(map);
        this._loading = null;
    };
    /**
     * Lookup a mime type based on extension
     */
    Mime.prototype.lookup = function (path, fallback) {
        var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase();
        return this.types[ext] || fallback || this.default_type;
    };
    /**
     * Return file extension associated with a mime type
     */
    Mime.prototype.extension = function (mimeType) {
        var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
        return this.extensions[type];
    };
    // Default instance
    var mime = new Mime();
    // Define built-in types
    mime.define(require(267) /* ./types.json */);
    // Default type
    mime.default_type = mime.lookup('bin');
    //
    // Additional API specific to the default instance
    //
    mime.Mime = Mime;
    /**
     * Lookup a charset based on mime type.
     */
    mime.charsets = {
        lookup: function (mimeType, fallback) {
            // Assume text types are utf8
            return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback;
        }
    };
    module.exports = mime;
}
,
/* mime/types.json */ function _(require, module, exports) {
    {
        "application/andrew-inset";
        ["ez"], "application/applixware";
        ["aw"], "application/atom+xml";
        ["atom"], "application/atomcat+xml";
        ["atomcat"], "application/atomsvc+xml";
        ["atomsvc"], "application/bdoc";
        ["bdoc"], "application/ccxml+xml";
        ["ccxml"], "application/cdmi-capability";
        ["cdmia"], "application/cdmi-container";
        ["cdmic"], "application/cdmi-domain";
        ["cdmid"], "application/cdmi-object";
        ["cdmio"], "application/cdmi-queue";
        ["cdmiq"], "application/cu-seeme";
        ["cu"], "application/dash+xml";
        ["mpd"], "application/davmount+xml";
        ["davmount"], "application/docbook+xml";
        ["dbk"], "application/dssc+der";
        ["dssc"], "application/dssc+xml";
        ["xdssc"], "application/ecmascript";
        ["ecma"], "application/emma+xml";
        ["emma"], "application/epub+zip";
        ["epub"], "application/exi";
        ["exi"], "application/font-tdpfr";
        ["pfr"], "application/font-woff";
        [], "application/font-woff2";
        [], "application/geo+json";
        ["geojson"], "application/gml+xml";
        ["gml"], "application/gpx+xml";
        ["gpx"], "application/gxf";
        ["gxf"], "application/gzip";
        ["gz"], "application/hyperstudio";
        ["stk"], "application/inkml+xml";
        ["ink", "inkml"], "application/ipfix";
        ["ipfix"], "application/java-archive";
        ["jar", "war", "ear"], "application/java-serialized-object";
        ["ser"], "application/java-vm";
        ["class"], "application/javascript";
        ["js", "mjs"], "application/json";
        ["json", "map"], "application/json5";
        ["json5"], "application/jsonml+json";
        ["jsonml"], "application/ld+json";
        ["jsonld"], "application/lost+xml";
        ["lostxml"], "application/mac-binhex40";
        ["hqx"], "application/mac-compactpro";
        ["cpt"], "application/mads+xml";
        ["mads"], "application/manifest+json";
        ["webmanifest"], "application/marc";
        ["mrc"], "application/marcxml+xml";
        ["mrcx"], "application/mathematica";
        ["ma", "nb", "mb"], "application/mathml+xml";
        ["mathml"], "application/mbox";
        ["mbox"], "application/mediaservercontrol+xml";
        ["mscml"], "application/metalink+xml";
        ["metalink"], "application/metalink4+xml";
        ["meta4"], "application/mets+xml";
        ["mets"], "application/mods+xml";
        ["mods"], "application/mp21";
        ["m21", "mp21"], "application/mp4";
        ["mp4s", "m4p"], "application/msword";
        ["doc", "dot"], "application/mxf";
        ["mxf"], "application/octet-stream";
        ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda";
        ["oda"], "application/oebps-package+xml";
        ["opf"], "application/ogg";
        ["ogx"], "application/omdoc+xml";
        ["omdoc"], "application/onenote";
        ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps";
        ["oxps"], "application/patch-ops-error+xml";
        ["xer"], "application/pdf";
        ["pdf"], "application/pgp-encrypted";
        ["pgp"], "application/pgp-signature";
        ["asc", "sig"], "application/pics-rules";
        ["prf"], "application/pkcs10";
        ["p10"], "application/pkcs7-mime";
        ["p7m", "p7c"], "application/pkcs7-signature";
        ["p7s"], "application/pkcs8";
        ["p8"], "application/pkix-attr-cert";
        ["ac"], "application/pkix-cert";
        ["cer"], "application/pkix-crl";
        ["crl"], "application/pkix-pkipath";
        ["pkipath"], "application/pkixcmp";
        ["pki"], "application/pls+xml";
        ["pls"], "application/postscript";
        ["ai", "eps", "ps"], "application/prs.cww";
        ["cww"], "application/pskc+xml";
        ["pskcxml"], "application/raml+yaml";
        ["raml"], "application/rdf+xml";
        ["rdf"], "application/reginfo+xml";
        ["rif"], "application/relax-ng-compact-syntax";
        ["rnc"], "application/resource-lists+xml";
        ["rl"], "application/resource-lists-diff+xml";
        ["rld"], "application/rls-services+xml";
        ["rs"], "application/rpki-ghostbusters";
        ["gbr"], "application/rpki-manifest";
        ["mft"], "application/rpki-roa";
        ["roa"], "application/rsd+xml";
        ["rsd"], "application/rss+xml";
        ["rss"], "application/rtf";
        ["rtf"], "application/sbml+xml";
        ["sbml"], "application/scvp-cv-request";
        ["scq"], "application/scvp-cv-response";
        ["scs"], "application/scvp-vp-request";
        ["spq"], "application/scvp-vp-response";
        ["spp"], "application/sdp";
        ["sdp"], "application/set-payment-initiation";
        ["setpay"], "application/set-registration-initiation";
        ["setreg"], "application/shf+xml";
        ["shf"], "application/smil+xml";
        ["smi", "smil"], "application/sparql-query";
        ["rq"], "application/sparql-results+xml";
        ["srx"], "application/srgs";
        ["gram"], "application/srgs+xml";
        ["grxml"], "application/sru+xml";
        ["sru"], "application/ssdl+xml";
        ["ssdl"], "application/ssml+xml";
        ["ssml"], "application/tei+xml";
        ["tei", "teicorpus"], "application/thraud+xml";
        ["tfi"], "application/timestamped-data";
        ["tsd"], "application/vnd.3gpp.pic-bw-large";
        ["plb"], "application/vnd.3gpp.pic-bw-small";
        ["psb"], "application/vnd.3gpp.pic-bw-var";
        ["pvb"], "application/vnd.3gpp2.tcap";
        ["tcap"], "application/vnd.3m.post-it-notes";
        ["pwn"], "application/vnd.accpac.simply.aso";
        ["aso"], "application/vnd.accpac.simply.imp";
        ["imp"], "application/vnd.acucobol";
        ["acu"], "application/vnd.acucorp";
        ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip";
        ["air"], "application/vnd.adobe.formscentral.fcdt";
        ["fcdt"], "application/vnd.adobe.fxp";
        ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml";
        ["xdp"], "application/vnd.adobe.xfdf";
        ["xfdf"], "application/vnd.ahead.space";
        ["ahead"], "application/vnd.airzip.filesecure.azf";
        ["azf"], "application/vnd.airzip.filesecure.azs";
        ["azs"], "application/vnd.amazon.ebook";
        ["azw"], "application/vnd.americandynamics.acc";
        ["acc"], "application/vnd.amiga.ami";
        ["ami"], "application/vnd.android.package-archive";
        ["apk"], "application/vnd.anser-web-certificate-issue-initiation";
        ["cii"], "application/vnd.anser-web-funds-transfer-initiation";
        ["fti"], "application/vnd.antix.game-component";
        ["atx"], "application/vnd.apple.installer+xml";
        ["mpkg"], "application/vnd.apple.mpegurl";
        ["m3u8"], "application/vnd.apple.pkpass";
        ["pkpass"], "application/vnd.aristanetworks.swi";
        ["swi"], "application/vnd.astraea-software.iota";
        ["iota"], "application/vnd.audiograph";
        ["aep"], "application/vnd.blueice.multipass";
        ["mpm"], "application/vnd.bmi";
        ["bmi"], "application/vnd.businessobjects";
        ["rep"], "application/vnd.chemdraw+xml";
        ["cdxml"], "application/vnd.chipnuts.karaoke-mmd";
        ["mmd"], "application/vnd.cinderella";
        ["cdy"], "application/vnd.claymore";
        ["cla"], "application/vnd.cloanto.rp9";
        ["rp9"], "application/vnd.clonk.c4group";
        ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config";
        ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg";
        ["c11amz"], "application/vnd.commonspace";
        ["csp"], "application/vnd.contact.cmsg";
        ["cdbcmsg"], "application/vnd.cosmocaller";
        ["cmc"], "application/vnd.crick.clicker";
        ["clkx"], "application/vnd.crick.clicker.keyboard";
        ["clkk"], "application/vnd.crick.clicker.palette";
        ["clkp"], "application/vnd.crick.clicker.template";
        ["clkt"], "application/vnd.crick.clicker.wordbank";
        ["clkw"], "application/vnd.criticaltools.wbs+xml";
        ["wbs"], "application/vnd.ctc-posml";
        ["pml"], "application/vnd.cups-ppd";
        ["ppd"], "application/vnd.curl.car";
        ["car"], "application/vnd.curl.pcurl";
        ["pcurl"], "application/vnd.dart";
        ["dart"], "application/vnd.data-vision.rdz";
        ["rdz"], "application/vnd.dece.data";
        ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml";
        ["uvt", "uvvt"], "application/vnd.dece.unspecified";
        ["uvx", "uvvx"], "application/vnd.dece.zip";
        ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link";
        ["fe_launch"], "application/vnd.dna";
        ["dna"], "application/vnd.dolby.mlp";
        ["mlp"], "application/vnd.dpgraph";
        ["dpg"], "application/vnd.dreamfactory";
        ["dfac"], "application/vnd.ds-keypoint";
        ["kpxx"], "application/vnd.dvb.ait";
        ["ait"], "application/vnd.dvb.service";
        ["svc"], "application/vnd.dynageo";
        ["geo"], "application/vnd.ecowin.chart";
        ["mag"], "application/vnd.enliven";
        ["nml"], "application/vnd.epson.esf";
        ["esf"], "application/vnd.epson.msf";
        ["msf"], "application/vnd.epson.quickanime";
        ["qam"], "application/vnd.epson.salt";
        ["slt"], "application/vnd.epson.ssf";
        ["ssf"], "application/vnd.eszigno3+xml";
        ["es3", "et3"], "application/vnd.ezpix-album";
        ["ez2"], "application/vnd.ezpix-package";
        ["ez3"], "application/vnd.fdf";
        ["fdf"], "application/vnd.fdsn.mseed";
        ["mseed"], "application/vnd.fdsn.seed";
        ["seed", "dataless"], "application/vnd.flographit";
        ["gph"], "application/vnd.fluxtime.clip";
        ["ftc"], "application/vnd.framemaker";
        ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc";
        ["fnc"], "application/vnd.frogans.ltf";
        ["ltf"], "application/vnd.fsc.weblaunch";
        ["fsc"], "application/vnd.fujitsu.oasys";
        ["oas"], "application/vnd.fujitsu.oasys2";
        ["oa2"], "application/vnd.fujitsu.oasys3";
        ["oa3"], "application/vnd.fujitsu.oasysgp";
        ["fg5"], "application/vnd.fujitsu.oasysprs";
        ["bh2"], "application/vnd.fujixerox.ddd";
        ["ddd"], "application/vnd.fujixerox.docuworks";
        ["xdw"], "application/vnd.fujixerox.docuworks.binder";
        ["xbd"], "application/vnd.fuzzysheet";
        ["fzs"], "application/vnd.genomatix.tuxedo";
        ["txd"], "application/vnd.geogebra.file";
        ["ggb"], "application/vnd.geogebra.tool";
        ["ggt"], "application/vnd.geometry-explorer";
        ["gex", "gre"], "application/vnd.geonext";
        ["gxt"], "application/vnd.geoplan";
        ["g2w"], "application/vnd.geospace";
        ["g3w"], "application/vnd.gmx";
        ["gmx"], "application/vnd.google-apps.document";
        ["gdoc"], "application/vnd.google-apps.presentation";
        ["gslides"], "application/vnd.google-apps.spreadsheet";
        ["gsheet"], "application/vnd.google-earth.kml+xml";
        ["kml"], "application/vnd.google-earth.kmz";
        ["kmz"], "application/vnd.grafeq";
        ["gqf", "gqs"], "application/vnd.groove-account";
        ["gac"], "application/vnd.groove-help";
        ["ghf"], "application/vnd.groove-identity-message";
        ["gim"], "application/vnd.groove-injector";
        ["grv"], "application/vnd.groove-tool-message";
        ["gtm"], "application/vnd.groove-tool-template";
        ["tpl"], "application/vnd.groove-vcard";
        ["vcg"], "application/vnd.hal+xml";
        ["hal"], "application/vnd.handheld-entertainment+xml";
        ["zmm"], "application/vnd.hbci";
        ["hbci"], "application/vnd.hhe.lesson-player";
        ["les"], "application/vnd.hp-hpgl";
        ["hpgl"], "application/vnd.hp-hpid";
        ["hpid"], "application/vnd.hp-hps";
        ["hps"], "application/vnd.hp-jlyt";
        ["jlt"], "application/vnd.hp-pcl";
        ["pcl"], "application/vnd.hp-pclxl";
        ["pclxl"], "application/vnd.hydrostatix.sof-data";
        ["sfd-hdstx"], "application/vnd.ibm.minipay";
        ["mpy"], "application/vnd.ibm.modcap";
        ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management";
        ["irm"], "application/vnd.ibm.secure-container";
        ["sc"], "application/vnd.iccprofile";
        ["icc", "icm"], "application/vnd.igloader";
        ["igl"], "application/vnd.immervision-ivp";
        ["ivp"], "application/vnd.immervision-ivu";
        ["ivu"], "application/vnd.insors.igm";
        ["igm"], "application/vnd.intercon.formnet";
        ["xpw", "xpx"], "application/vnd.intergeo";
        ["i2g"], "application/vnd.intu.qbo";
        ["qbo"], "application/vnd.intu.qfx";
        ["qfx"], "application/vnd.ipunplugged.rcprofile";
        ["rcprofile"], "application/vnd.irepository.package+xml";
        ["irp"], "application/vnd.is-xpr";
        ["xpr"], "application/vnd.isac.fcs";
        ["fcs"], "application/vnd.jam";
        ["jam"], "application/vnd.jcp.javame.midlet-rms";
        ["rms"], "application/vnd.jisp";
        ["jisp"], "application/vnd.joost.joda-archive";
        ["joda"], "application/vnd.kahootz";
        ["ktz", "ktr"], "application/vnd.kde.karbon";
        ["karbon"], "application/vnd.kde.kchart";
        ["chrt"], "application/vnd.kde.kformula";
        ["kfo"], "application/vnd.kde.kivio";
        ["flw"], "application/vnd.kde.kontour";
        ["kon"], "application/vnd.kde.kpresenter";
        ["kpr", "kpt"], "application/vnd.kde.kspread";
        ["ksp"], "application/vnd.kde.kword";
        ["kwd", "kwt"], "application/vnd.kenameaapp";
        ["htke"], "application/vnd.kidspiration";
        ["kia"], "application/vnd.kinar";
        ["kne", "knp"], "application/vnd.koan";
        ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor";
        ["sse"], "application/vnd.las.las+xml";
        ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop";
        ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml";
        ["lbe"], "application/vnd.lotus-1-2-3";
        ["123"], "application/vnd.lotus-approach";
        ["apr"], "application/vnd.lotus-freelance";
        ["pre"], "application/vnd.lotus-notes";
        ["nsf"], "application/vnd.lotus-organizer";
        ["org"], "application/vnd.lotus-screencam";
        ["scm"], "application/vnd.lotus-wordpro";
        ["lwp"], "application/vnd.macports.portpkg";
        ["portpkg"], "application/vnd.mcd";
        ["mcd"], "application/vnd.medcalcdata";
        ["mc1"], "application/vnd.mediastation.cdkey";
        ["cdkey"], "application/vnd.mfer";
        ["mwf"], "application/vnd.mfmp";
        ["mfm"], "application/vnd.micrografx.flo";
        ["flo"], "application/vnd.micrografx.igx";
        ["igx"], "application/vnd.mif";
        ["mif"], "application/vnd.mobius.daf";
        ["daf"], "application/vnd.mobius.dis";
        ["dis"], "application/vnd.mobius.mbk";
        ["mbk"], "application/vnd.mobius.mqy";
        ["mqy"], "application/vnd.mobius.msl";
        ["msl"], "application/vnd.mobius.plc";
        ["plc"], "application/vnd.mobius.txf";
        ["txf"], "application/vnd.mophun.application";
        ["mpn"], "application/vnd.mophun.certificate";
        ["mpc"], "application/vnd.mozilla.xul+xml";
        ["xul"], "application/vnd.ms-artgalry";
        ["cil"], "application/vnd.ms-cab-compressed";
        ["cab"], "application/vnd.ms-excel";
        ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12";
        ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12";
        ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12";
        ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12";
        ["xltm"], "application/vnd.ms-fontobject";
        ["eot"], "application/vnd.ms-htmlhelp";
        ["chm"], "application/vnd.ms-ims";
        ["ims"], "application/vnd.ms-lrm";
        ["lrm"], "application/vnd.ms-officetheme";
        ["thmx"], "application/vnd.ms-outlook";
        ["msg"], "application/vnd.ms-pki.seccat";
        ["cat"], "application/vnd.ms-pki.stl";
        ["stl"], "application/vnd.ms-powerpoint";
        ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12";
        ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12";
        ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12";
        ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12";
        ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12";
        ["potm"], "application/vnd.ms-project";
        ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12";
        ["docm"], "application/vnd.ms-word.template.macroenabled.12";
        ["dotm"], "application/vnd.ms-works";
        ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl";
        ["wpl"], "application/vnd.ms-xpsdocument";
        ["xps"], "application/vnd.mseq";
        ["mseq"], "application/vnd.musician";
        ["mus"], "application/vnd.muvee.style";
        ["msty"], "application/vnd.mynfc";
        ["taglet"], "application/vnd.neurolanguage.nlu";
        ["nlu"], "application/vnd.nitf";
        ["ntf", "nitf"], "application/vnd.noblenet-directory";
        ["nnd"], "application/vnd.noblenet-sealer";
        ["nns"], "application/vnd.noblenet-web";
        ["nnw"], "application/vnd.nokia.n-gage.data";
        ["ngdat"], "application/vnd.nokia.n-gage.symbian.install";
        ["n-gage"], "application/vnd.nokia.radio-preset";
        ["rpst"], "application/vnd.nokia.radio-presets";
        ["rpss"], "application/vnd.novadigm.edm";
        ["edm"], "application/vnd.novadigm.edx";
        ["edx"], "application/vnd.novadigm.ext";
        ["ext"], "application/vnd.oasis.opendocument.chart";
        ["odc"], "application/vnd.oasis.opendocument.chart-template";
        ["otc"], "application/vnd.oasis.opendocument.database";
        ["odb"], "application/vnd.oasis.opendocument.formula";
        ["odf"], "application/vnd.oasis.opendocument.formula-template";
        ["odft"], "application/vnd.oasis.opendocument.graphics";
        ["odg"], "application/vnd.oasis.opendocument.graphics-template";
        ["otg"], "application/vnd.oasis.opendocument.image";
        ["odi"], "application/vnd.oasis.opendocument.image-template";
        ["oti"], "application/vnd.oasis.opendocument.presentation";
        ["odp"], "application/vnd.oasis.opendocument.presentation-template";
        ["otp"], "application/vnd.oasis.opendocument.spreadsheet";
        ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template";
        ["ots"], "application/vnd.oasis.opendocument.text";
        ["odt"], "application/vnd.oasis.opendocument.text-master";
        ["odm"], "application/vnd.oasis.opendocument.text-template";
        ["ott"], "application/vnd.oasis.opendocument.text-web";
        ["oth"], "application/vnd.olpc-sugar";
        ["xo"], "application/vnd.oma.dd2+xml";
        ["dd2"], "application/vnd.openofficeorg.extension";
        ["oxt"], "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide";
        ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
        ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template";
        ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
        ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
        ["dotx"], "application/vnd.osgeo.mapguide.package";
        ["mgp"], "application/vnd.osgi.dp";
        ["dp"], "application/vnd.osgi.subsystem";
        ["esa"], "application/vnd.palm";
        ["pdb", "pqa", "oprc"], "application/vnd.pawaafile";
        ["paw"], "application/vnd.pg.format";
        ["str"], "application/vnd.pg.osasli";
        ["ei6"], "application/vnd.picsel";
        ["efif"], "application/vnd.pmi.widget";
        ["wg"], "application/vnd.pocketlearn";
        ["plf"], "application/vnd.powerbuilder6";
        ["pbd"], "application/vnd.previewsystems.box";
        ["box"], "application/vnd.proteus.magazine";
        ["mgz"], "application/vnd.publishare-delta-tree";
        ["qps"], "application/vnd.pvi.ptid1";
        ["ptid"], "application/vnd.quark.quarkxpress";
        ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.realvnc.bed";
        ["bed"], "application/vnd.recordare.musicxml";
        ["mxl"], "application/vnd.recordare.musicxml+xml";
        ["musicxml"], "application/vnd.rig.cryptonote";
        ["cryptonote"], "application/vnd.rim.cod";
        ["cod"], "application/vnd.rn-realmedia";
        ["rm"], "application/vnd.rn-realmedia-vbr";
        ["rmvb"], "application/vnd.route66.link66+xml";
        ["link66"], "application/vnd.sailingtracker.track";
        ["st"], "application/vnd.seemail";
        ["see"], "application/vnd.sema";
        ["sema"], "application/vnd.semd";
        ["semd"], "application/vnd.semf";
        ["semf"], "application/vnd.shana.informed.formdata";
        ["ifm"], "application/vnd.shana.informed.formtemplate";
        ["itp"], "application/vnd.shana.informed.interchange";
        ["iif"], "application/vnd.shana.informed.package";
        ["ipk"], "application/vnd.simtech-mindmapper";
        ["twd", "twds"], "application/vnd.smaf";
        ["mmf"], "application/vnd.smart.teacher";
        ["teacher"], "application/vnd.solent.sdkm+xml";
        ["sdkm", "sdkd"], "application/vnd.spotfire.dxp";
        ["dxp"], "application/vnd.spotfire.sfs";
        ["sfs"], "application/vnd.stardivision.calc";
        ["sdc"], "application/vnd.stardivision.draw";
        ["sda"], "application/vnd.stardivision.impress";
        ["sdd"], "application/vnd.stardivision.math";
        ["smf"], "application/vnd.stardivision.writer";
        ["sdw", "vor"], "application/vnd.stardivision.writer-global";
        ["sgl"], "application/vnd.stepmania.package";
        ["smzip"], "application/vnd.stepmania.stepchart";
        ["sm"], "application/vnd.sun.wadl+xml";
        ["wadl"], "application/vnd.sun.xml.calc";
        ["sxc"], "application/vnd.sun.xml.calc.template";
        ["stc"], "application/vnd.sun.xml.draw";
        ["sxd"], "application/vnd.sun.xml.draw.template";
        ["std"], "application/vnd.sun.xml.impress";
        ["sxi"], "application/vnd.sun.xml.impress.template";
        ["sti"], "application/vnd.sun.xml.math";
        ["sxm"], "application/vnd.sun.xml.writer";
        ["sxw"], "application/vnd.sun.xml.writer.global";
        ["sxg"], "application/vnd.sun.xml.writer.template";
        ["stw"], "application/vnd.sus-calendar";
        ["sus", "susp"], "application/vnd.svd";
        ["svd"], "application/vnd.symbian.install";
        ["sis", "sisx"], "application/vnd.syncml+xml";
        ["xsm"], "application/vnd.syncml.dm+wbxml";
        ["bdm"], "application/vnd.syncml.dm+xml";
        ["xdm"], "application/vnd.tao.intent-module-archive";
        ["tao"], "application/vnd.tcpdump.pcap";
        ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv";
        ["tmo"], "application/vnd.trid.tpt";
        ["tpt"], "application/vnd.triscape.mxs";
        ["mxs"], "application/vnd.trueapp";
        ["tra"], "application/vnd.ufdl";
        ["ufd", "ufdl"], "application/vnd.uiq.theme";
        ["utz"], "application/vnd.umajin";
        ["umj"], "application/vnd.unity";
        ["unityweb"], "application/vnd.uoml+xml";
        ["uoml"], "application/vnd.vcx";
        ["vcx"], "application/vnd.visio";
        ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary";
        ["vis"], "application/vnd.vsf";
        ["vsf"], "application/vnd.wap.wbxml";
        ["wbxml"], "application/vnd.wap.wmlc";
        ["wmlc"], "application/vnd.wap.wmlscriptc";
        ["wmlsc"], "application/vnd.webturbo";
        ["wtb"], "application/vnd.wolfram.player";
        ["nbp"], "application/vnd.wordperfect";
        ["wpd"], "application/vnd.wqd";
        ["wqd"], "application/vnd.wt.stf";
        ["stf"], "application/vnd.xara";
        ["xar"], "application/vnd.xfdl";
        ["xfdl"], "application/vnd.yamaha.hv-dic";
        ["hvd"], "application/vnd.yamaha.hv-script";
        ["hvs"], "application/vnd.yamaha.hv-voice";
        ["hvp"], "application/vnd.yamaha.openscoreformat";
        ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml";
        ["osfpvg"], "application/vnd.yamaha.smaf-audio";
        ["saf"], "application/vnd.yamaha.smaf-phrase";
        ["spf"], "application/vnd.yellowriver-custom-menu";
        ["cmp"], "application/vnd.zul";
        ["zir", "zirz"], "application/vnd.zzazz.deck+xml";
        ["zaz"], "application/voicexml+xml";
        ["vxml"], "application/wasm";
        ["wasm"], "application/widget";
        ["wgt"], "application/winhlp";
        ["hlp"], "application/wsdl+xml";
        ["wsdl"], "application/wspolicy+xml";
        ["wspolicy"], "application/x-7z-compressed";
        ["7z"], "application/x-abiword";
        ["abw"], "application/x-ace-compressed";
        ["ace"], "application/x-apple-diskimage";
        [], "application/x-arj";
        ["arj"], "application/x-authorware-bin";
        ["aab", "x32", "u32", "vox"], "application/x-authorware-map";
        ["aam"], "application/x-authorware-seg";
        ["aas"], "application/x-bcpio";
        ["bcpio"], "application/x-bdoc";
        [], "application/x-bittorrent";
        ["torrent"], "application/x-blorb";
        ["blb", "blorb"], "application/x-bzip";
        ["bz"], "application/x-bzip2";
        ["bz2", "boz"], "application/x-cbr";
        ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink";
        ["vcd"], "application/x-cfs-compressed";
        ["cfs"], "application/x-chat";
        ["chat"], "application/x-chess-pgn";
        ["pgn"], "application/x-chrome-extension";
        ["crx"], "application/x-cocoa";
        ["cco"], "application/x-conference";
        ["nsc"], "application/x-cpio";
        ["cpio"], "application/x-csh";
        ["csh"], "application/x-debian-package";
        ["udeb"], "application/x-dgc-compressed";
        ["dgc"], "application/x-director";
        ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom";
        ["wad"], "application/x-dtbncx+xml";
        ["ncx"], "application/x-dtbook+xml";
        ["dtb"], "application/x-dtbresource+xml";
        ["res"], "application/x-dvi";
        ["dvi"], "application/x-envoy";
        ["evy"], "application/x-eva";
        ["eva"], "application/x-font-bdf";
        ["bdf"], "application/x-font-ghostscript";
        ["gsf"], "application/x-font-linux-psf";
        ["psf"], "application/x-font-pcf";
        ["pcf"], "application/x-font-snf";
        ["snf"], "application/x-font-type1";
        ["pfa", "pfb", "pfm", "afm"], "application/x-freearc";
        ["arc"], "application/x-futuresplash";
        ["spl"], "application/x-gca-compressed";
        ["gca"], "application/x-glulx";
        ["ulx"], "application/x-gnumeric";
        ["gnumeric"], "application/x-gramps-xml";
        ["gramps"], "application/x-gtar";
        ["gtar"], "application/x-hdf";
        ["hdf"], "application/x-httpd-php";
        ["php"], "application/x-install-instructions";
        ["install"], "application/x-iso9660-image";
        [], "application/x-java-archive-diff";
        ["jardiff"], "application/x-java-jnlp-file";
        ["jnlp"], "application/x-latex";
        ["latex"], "application/x-lua-bytecode";
        ["luac"], "application/x-lzh-compressed";
        ["lzh", "lha"], "application/x-makeself";
        ["run"], "application/x-mie";
        ["mie"], "application/x-mobipocket-ebook";
        ["prc", "mobi"], "application/x-ms-application";
        ["application"], "application/x-ms-shortcut";
        ["lnk"], "application/x-ms-wmd";
        ["wmd"], "application/x-ms-wmz";
        ["wmz"], "application/x-ms-xbap";
        ["xbap"], "application/x-msaccess";
        ["mdb"], "application/x-msbinder";
        ["obd"], "application/x-mscardfile";
        ["crd"], "application/x-msclip";
        ["clp"], "application/x-msdos-program";
        [], "application/x-msdownload";
        ["com", "bat"], "application/x-msmediaview";
        ["mvb", "m13", "m14"], "application/x-msmetafile";
        ["wmf", "emf", "emz"], "application/x-msmoney";
        ["mny"], "application/x-mspublisher";
        ["pub"], "application/x-msschedule";
        ["scd"], "application/x-msterminal";
        ["trm"], "application/x-mswrite";
        ["wri"], "application/x-netcdf";
        ["nc", "cdf"], "application/x-ns-proxy-autoconfig";
        ["pac"], "application/x-nzb";
        ["nzb"], "application/x-perl";
        ["pl", "pm"], "application/x-pilot";
        [], "application/x-pkcs12";
        ["p12", "pfx"], "application/x-pkcs7-certificates";
        ["p7b", "spc"], "application/x-pkcs7-certreqresp";
        ["p7r"], "application/x-rar-compressed";
        ["rar"], "application/x-redhat-package-manager";
        ["rpm"], "application/x-research-info-systems";
        ["ris"], "application/x-sea";
        ["sea"], "application/x-sh";
        ["sh"], "application/x-shar";
        ["shar"], "application/x-shockwave-flash";
        ["swf"], "application/x-silverlight-app";
        ["xap"], "application/x-sql";
        ["sql"], "application/x-stuffit";
        ["sit"], "application/x-stuffitx";
        ["sitx"], "application/x-subrip";
        ["srt"], "application/x-sv4cpio";
        ["sv4cpio"], "application/x-sv4crc";
        ["sv4crc"], "application/x-t3vm-image";
        ["t3"], "application/x-tads";
        ["gam"], "application/x-tar";
        ["tar"], "application/x-tcl";
        ["tcl", "tk"], "application/x-tex";
        ["tex"], "application/x-tex-tfm";
        ["tfm"], "application/x-texinfo";
        ["texinfo", "texi"], "application/x-tgif";
        ["obj"], "application/x-ustar";
        ["ustar"], "application/x-virtualbox-hdd";
        ["hdd"], "application/x-virtualbox-ova";
        ["ova"], "application/x-virtualbox-ovf";
        ["ovf"], "application/x-virtualbox-vbox";
        ["vbox"], "application/x-virtualbox-vbox-extpack";
        ["vbox-extpack"], "application/x-virtualbox-vdi";
        ["vdi"], "application/x-virtualbox-vhd";
        ["vhd"], "application/x-virtualbox-vmdk";
        ["vmdk"], "application/x-wais-source";
        ["src"], "application/x-web-app-manifest+json";
        ["webapp"], "application/x-x509-ca-cert";
        ["der", "crt", "pem"], "application/x-xfig";
        ["fig"], "application/x-xliff+xml";
        ["xlf"], "application/x-xpinstall";
        ["xpi"], "application/x-xz";
        ["xz"], "application/x-zmachine";
        ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "application/xaml+xml";
        ["xaml"], "application/xcap-diff+xml";
        ["xdf"], "application/xenc+xml";
        ["xenc"], "application/xhtml+xml";
        ["xhtml", "xht"], "application/xml";
        ["xml", "xsl", "xsd", "rng"], "application/xml-dtd";
        ["dtd"], "application/xop+xml";
        ["xop"], "application/xproc+xml";
        ["xpl"], "application/xslt+xml";
        ["xslt"], "application/xspf+xml";
        ["xspf"], "application/xv+xml";
        ["mxml", "xhvml", "xvml", "xvm"], "application/yang";
        ["yang"], "application/yin+xml";
        ["yin"], "application/zip";
        ["zip"], "audio/3gpp";
        [], "audio/adpcm";
        ["adp"], "audio/basic";
        ["au", "snd"], "audio/midi";
        ["mid", "midi", "kar", "rmi"], "audio/mp3";
        [], "audio/mp4";
        ["m4a", "mp4a"], "audio/mpeg";
        ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg";
        ["oga", "ogg", "spx"], "audio/s3m";
        ["s3m"], "audio/silk";
        ["sil"], "audio/vnd.dece.audio";
        ["uva", "uvva"], "audio/vnd.digital-winds";
        ["eol"], "audio/vnd.dra";
        ["dra"], "audio/vnd.dts";
        ["dts"], "audio/vnd.dts.hd";
        ["dtshd"], "audio/vnd.lucent.voice";
        ["lvp"], "audio/vnd.ms-playready.media.pya";
        ["pya"], "audio/vnd.nuera.ecelp4800";
        ["ecelp4800"], "audio/vnd.nuera.ecelp7470";
        ["ecelp7470"], "audio/vnd.nuera.ecelp9600";
        ["ecelp9600"], "audio/vnd.rip";
        ["rip"], "audio/wav";
        ["wav"], "audio/wave";
        [], "audio/webm";
        ["weba"], "audio/x-aac";
        ["aac"], "audio/x-aiff";
        ["aif", "aiff", "aifc"], "audio/x-caf";
        ["caf"], "audio/x-flac";
        ["flac"], "audio/x-m4a";
        [], "audio/x-matroska";
        ["mka"], "audio/x-mpegurl";
        ["m3u"], "audio/x-ms-wax";
        ["wax"], "audio/x-ms-wma";
        ["wma"], "audio/x-pn-realaudio";
        ["ram", "ra"], "audio/x-pn-realaudio-plugin";
        ["rmp"], "audio/x-realaudio";
        [], "audio/x-wav";
        [], "audio/xm";
        ["xm"], "chemical/x-cdx";
        ["cdx"], "chemical/x-cif";
        ["cif"], "chemical/x-cmdf";
        ["cmdf"], "chemical/x-cml";
        ["cml"], "chemical/x-csml";
        ["csml"], "chemical/x-xyz";
        ["xyz"], "font/collection";
        ["ttc"], "font/otf";
        ["otf"], "font/ttf";
        ["ttf"], "font/woff";
        ["woff"], "font/woff2";
        ["woff2"], "image/apng";
        ["apng"], "image/bmp";
        ["bmp"], "image/cgm";
        ["cgm"], "image/g3fax";
        ["g3"], "image/gif";
        ["gif"], "image/ief";
        ["ief"], "image/jp2";
        ["jp2", "jpg2"], "image/jpeg";
        ["jpeg", "jpg", "jpe"], "image/jpm";
        ["jpm"], "image/jpx";
        ["jpx", "jpf"], "image/ktx";
        ["ktx"], "image/png";
        ["png"], "image/prs.btif";
        ["btif"], "image/sgi";
        ["sgi"], "image/svg+xml";
        ["svg", "svgz"], "image/tiff";
        ["tiff", "tif"], "image/vnd.adobe.photoshop";
        ["psd"], "image/vnd.dece.graphic";
        ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu";
        ["djvu", "djv"], "image/vnd.dvb.subtitle";
        [], "image/vnd.dwg";
        ["dwg"], "image/vnd.dxf";
        ["dxf"], "image/vnd.fastbidsheet";
        ["fbs"], "image/vnd.fpx";
        ["fpx"], "image/vnd.fst";
        ["fst"], "image/vnd.fujixerox.edmics-mmr";
        ["mmr"], "image/vnd.fujixerox.edmics-rlc";
        ["rlc"], "image/vnd.ms-modi";
        ["mdi"], "image/vnd.ms-photo";
        ["wdp"], "image/vnd.net-fpx";
        ["npx"], "image/vnd.wap.wbmp";
        ["wbmp"], "image/vnd.xiff";
        ["xif"], "image/webp";
        ["webp"], "image/x-3ds";
        ["3ds"], "image/x-cmu-raster";
        ["ras"], "image/x-cmx";
        ["cmx"], "image/x-freehand";
        ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon";
        ["ico"], "image/x-jng";
        ["jng"], "image/x-mrsid-image";
        ["sid"], "image/x-ms-bmp";
        [], "image/x-pcx";
        ["pcx"], "image/x-pict";
        ["pic", "pct"], "image/x-portable-anymap";
        ["pnm"], "image/x-portable-bitmap";
        ["pbm"], "image/x-portable-graymap";
        ["pgm"], "image/x-portable-pixmap";
        ["ppm"], "image/x-rgb";
        ["rgb"], "image/x-tga";
        ["tga"], "image/x-xbitmap";
        ["xbm"], "image/x-xpixmap";
        ["xpm"], "image/x-xwindowdump";
        ["xwd"], "message/rfc822";
        ["eml", "mime"], "model/gltf+json";
        ["gltf"], "model/gltf-binary";
        ["glb"], "model/iges";
        ["igs", "iges"], "model/mesh";
        ["msh", "mesh", "silo"], "model/vnd.collada+xml";
        ["dae"], "model/vnd.dwf";
        ["dwf"], "model/vnd.gdl";
        ["gdl"], "model/vnd.gtw";
        ["gtw"], "model/vnd.mts";
        ["mts"], "model/vnd.vtu";
        ["vtu"], "model/vrml";
        ["wrl", "vrml"], "model/x3d+binary";
        ["x3db", "x3dbz"], "model/x3d+vrml";
        ["x3dv", "x3dvz"], "model/x3d+xml";
        ["x3d", "x3dz"], "text/cache-manifest";
        ["appcache", "manifest"], "text/calendar";
        ["ics", "ifb"], "text/coffeescript";
        ["coffee", "litcoffee"], "text/css";
        ["css"], "text/csv";
        ["csv"], "text/hjson";
        ["hjson"], "text/html";
        ["html", "htm", "shtml"], "text/jade";
        ["jade"], "text/jsx";
        ["jsx"], "text/less";
        ["less"], "text/markdown";
        ["markdown", "md"], "text/mathml";
        ["mml"], "text/n3";
        ["n3"], "text/plain";
        ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/prs.lines.tag";
        ["dsc"], "text/richtext";
        ["rtx"], "text/rtf";
        [], "text/sgml";
        ["sgml", "sgm"], "text/slim";
        ["slim", "slm"], "text/stylus";
        ["stylus", "styl"], "text/tab-separated-values";
        ["tsv"], "text/troff";
        ["t", "tr", "roff", "man", "me", "ms"], "text/turtle";
        ["ttl"], "text/uri-list";
        ["uri", "uris", "urls"], "text/vcard";
        ["vcard"], "text/vnd.curl";
        ["curl"], "text/vnd.curl.dcurl";
        ["dcurl"], "text/vnd.curl.mcurl";
        ["mcurl"], "text/vnd.curl.scurl";
        ["scurl"], "text/vnd.dvb.subtitle";
        ["sub"], "text/vnd.fly";
        ["fly"], "text/vnd.fmi.flexstor";
        ["flx"], "text/vnd.graphviz";
        ["gv"], "text/vnd.in3d.3dml";
        ["3dml"], "text/vnd.in3d.spot";
        ["spot"], "text/vnd.sun.j2me.app-descriptor";
        ["jad"], "text/vnd.wap.wml";
        ["wml"], "text/vnd.wap.wmlscript";
        ["wmls"], "text/vtt";
        ["vtt"], "text/x-asm";
        ["s", "asm"], "text/x-c";
        ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component";
        ["htc"], "text/x-fortran";
        ["f", "for", "f77", "f90"], "text/x-handlebars-template";
        ["hbs"], "text/x-java-source";
        ["java"], "text/x-lua";
        ["lua"], "text/x-markdown";
        ["mkd"], "text/x-nfo";
        ["nfo"], "text/x-opml";
        ["opml"], "text/x-org";
        [], "text/x-pascal";
        ["p", "pas"], "text/x-processing";
        ["pde"], "text/x-sass";
        ["sass"], "text/x-scss";
        ["scss"], "text/x-setext";
        ["etx"], "text/x-sfv";
        ["sfv"], "text/x-suse-ymp";
        ["ymp"], "text/x-uuencode";
        ["uu"], "text/x-vcalendar";
        ["vcs"], "text/x-vcard";
        ["vcf"], "text/xml";
        [], "text/yaml";
        ["yaml", "yml"], "video/3gpp";
        ["3gp", "3gpp"], "video/3gpp2";
        ["3g2"], "video/h261";
        ["h261"], "video/h263";
        ["h263"], "video/h264";
        ["h264"], "video/jpeg";
        ["jpgv"], "video/jpm";
        ["jpgm"], "video/mj2";
        ["mj2", "mjp2"], "video/mp2t";
        ["ts"], "video/mp4";
        ["mp4", "mp4v", "mpg4"], "video/mpeg";
        ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg";
        ["ogv"], "video/quicktime";
        ["qt", "mov"], "video/vnd.dece.hd";
        ["uvh", "uvvh"], "video/vnd.dece.mobile";
        ["uvm", "uvvm"], "video/vnd.dece.pd";
        ["uvp", "uvvp"], "video/vnd.dece.sd";
        ["uvs", "uvvs"], "video/vnd.dece.video";
        ["uvv", "uvvv"], "video/vnd.dvb.file";
        ["dvb"], "video/vnd.fvt";
        ["fvt"], "video/vnd.mpegurl";
        ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv";
        ["pyv"], "video/vnd.uvvu.mp4";
        ["uvu", "uvvu"], "video/vnd.vivo";
        ["viv"], "video/webm";
        ["webm"], "video/x-f4v";
        ["f4v"], "video/x-fli";
        ["fli"], "video/x-flv";
        ["flv"], "video/x-m4v";
        ["m4v"], "video/x-matroska";
        ["mkv", "mk3d", "mks"], "video/x-mng";
        ["mng"], "video/x-ms-asf";
        ["asf", "asx"], "video/x-ms-vob";
        ["vob"], "video/x-ms-wm";
        ["wm"], "video/x-ms-wmv";
        ["wmv"], "video/x-ms-wmx";
        ["wmx"], "video/x-ms-wvx";
        ["wvx"], "video/x-msvideo";
        ["avi"], "video/x-sgi-movie";
        ["movie"], "video/x-smv";
        ["smv"], "x-conference/x-cooltalk";
        ["ice"];
    }
}
,
/* mimic-fn/index */ function _(require, module, exports) {
    module.exports = (to, from) => {
        // TODO: use `Reflect.ownKeys()` when targeting Node.js 6
        for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) {
            Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
        }
        return to;
    };
}
,
/* npm-run-path/index */ function _(require, module, exports) {
    const path = require('path');
    const pathKey = require(277) /* path-key */;
    module.exports = opts => {
        opts = Object.assign({
            cwd: process.cwd(),
            path: process.env[pathKey()]
        }, opts);
        let prev;
        let pth = path.resolve(opts.cwd);
        const ret = [];
        while (prev !== pth) {
            ret.push(path.join(pth, 'node_modules/.bin'));
            prev = pth;
            pth = path.resolve(pth, '..');
        }
        // ensure the running `node` binary is used
        ret.push(path.dirname(process.execPath));
        return ret.concat(opts.path).join(path.delimiter);
    };
    module.exports.env = opts => {
        opts = Object.assign({
            env: process.env
        }, opts);
        const env = Object.assign({}, opts.env);
        const path = pathKey({ env });
        opts.path = env[path];
        env[path] = module.exports(opts);
        return env;
    };
}
,
/* oauth-sign/index */ function _(require, module, exports) {
    var crypto = require('crypto');
    function sha(key, body, algorithm) {
        return crypto.createHmac(algorithm, key).update(body).digest('base64');
    }
    function rsa(key, body) {
        return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64');
    }
    function rfc3986(str) {
        return encodeURIComponent(str)
            .replace(/!/g, '%21')
            .replace(/\*/g, '%2A')
            .replace(/\(/g, '%28')
            .replace(/\)/g, '%29')
            .replace(/'/g, '%27');
    }
    // Maps object to bi-dimensional array
    // Converts { foo: 'A', bar: [ 'b', 'B' ]} to
    // [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ]
    function map(obj) {
        var key, val, arr = [];
        for (key in obj) {
            val = obj[key];
            if (Array.isArray(val))
                for (var i = 0; i < val.length; i++)
                    arr.push([key, val[i]]);
            else if (typeof val === 'object')
                for (var prop in val)
                    arr.push([key + '[' + prop + ']', val[prop]]);
            else
                arr.push([key, val]);
        }
        return arr;
    }
    // Compare function for sort
    function compare(a, b) {
        return a > b ? 1 : a < b ? -1 : 0;
    }
    function generateBase(httpMethod, base_uri, params) {
        // adapted from https://dev.twitter.com/docs/auth/oauth and 
        // https://dev.twitter.com/docs/auth/creating-signature
        // Parameter normalization
        // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
        var normalized = map(params)
            // 1.  First, the name and value of each parameter are encoded
            .map(function (p) {
            return [rfc3986(p[0]), rfc3986(p[1] || '')];
        })
            // 2.  The parameters are sorted by name, using ascending byte value
            //     ordering.  If two or more parameters share the same name, they
            //     are sorted by their value.
            .sort(function (a, b) {
            return compare(a[0], b[0]) || compare(a[1], b[1]);
        })
            // 3.  The name of each parameter is concatenated to its corresponding
            //     value using an "=" character (ASCII code 61) as a separator, even
            //     if the value is empty.
            .map(function (p) { return p.join('='); })
            // 4.  The sorted name/value pairs are concatenated together into a
            //     single string by using an "&" character (ASCII code 38) as
            //     separator.
            .join('&');
        var base = [
            rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'),
            rfc3986(base_uri),
            rfc3986(normalized)
        ].join('&');
        return base;
    }
    function hmacsign(httpMethod, base_uri, params, consumer_secret, token_secret) {
        var base = generateBase(httpMethod, base_uri, params);
        var key = [
            consumer_secret || '',
            token_secret || ''
        ].map(rfc3986).join('&');
        return sha(key, base, 'sha1');
    }
    function hmacsign256(httpMethod, base_uri, params, consumer_secret, token_secret) {
        var base = generateBase(httpMethod, base_uri, params);
        var key = [
            consumer_secret || '',
            token_secret || ''
        ].map(rfc3986).join('&');
        return sha(key, base, 'sha256');
    }
    function rsasign(httpMethod, base_uri, params, private_key, token_secret) {
        var base = generateBase(httpMethod, base_uri, params);
        var key = private_key || '';
        return rsa(key, base);
    }
    function plaintext(consumer_secret, token_secret) {
        var key = [
            consumer_secret || '',
            token_secret || ''
        ].map(rfc3986).join('&');
        return key;
    }
    function sign(signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
        var method;
        var skipArgs = 1;
        switch (signMethod) {
            case 'RSA-SHA1':
                method = rsasign;
                break;
            case 'HMAC-SHA1':
                method = hmacsign;
                break;
            case 'HMAC-SHA256':
                method = hmacsign256;
                break;
            case 'PLAINTEXT':
                method = plaintext;
                skipArgs = 4;
                break;
            default:
                throw new Error('Signature method not supported: ' + signMethod);
        }
        return method.apply(null, [].slice.call(arguments, skipArgs));
    }
    exports.hmacsign = hmacsign;
    exports.hmacsign256 = hmacsign256;
    exports.rsasign = rsasign;
    exports.plaintext = plaintext;
    exports.sign = sign;
    exports.rfc3986 = rfc3986;
    exports.generateBase = generateBase;
}
,
/* os-locale/index */ function _(require, module, exports) {
    const execa = require(103) /* execa */;
    const lcid = require(162) /* lcid */;
    const mem = require(262) /* mem */;
    const defaultOpts = { spawn: true };
    const defaultLocale = 'en_US';
    function getEnvLocale(env) {
        env = env || process.env;
        return env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE;
    }
    function parseLocale(x) {
        const env = x.split('\n').reduce((env, def) => {
            def = def.split('=');
            env[def[0]] = def[1].replace(/^"|"$/g, '');
            return env;
        }, {});
        return getEnvLocale(env);
    }
    function getLocale(str) {
        return (str && str.replace(/[.:].*/, ''));
    }
    function getAppleLocale() {
        return execa.stdout('defaults', ['read', '-g', 'AppleLocale']);
    }
    function getAppleLocaleSync() {
        return execa.sync('defaults', ['read', '-g', 'AppleLocale']).stdout;
    }
    function getUnixLocale() {
        if (process.platform === 'darwin') {
            return getAppleLocale();
        }
        return execa.stdout('locale')
            .then(stdout => getLocale(parseLocale(stdout)));
    }
    function getUnixLocaleSync() {
        if (process.platform === 'darwin') {
            return getAppleLocaleSync();
        }
        return getLocale(parseLocale(execa.sync('locale').stdout));
    }
    function getWinLocale() {
        return execa.stdout('wmic', ['os', 'get', 'locale'])
            .then(stdout => {
            const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
            return lcid.from(lcidCode);
        });
    }
    function getWinLocaleSync() {
        const stdout = execa.sync('wmic', ['os', 'get', 'locale']).stdout;
        const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
        return lcid.from(lcidCode);
    }
    module.exports = mem(opts => {
        opts = opts || defaultOpts;
        const envLocale = getEnvLocale();
        let thenable;
        if (envLocale || opts.spawn === false) {
            thenable = Promise.resolve(getLocale(envLocale));
        }
        else if (process.platform === 'win32') {
            thenable = getWinLocale();
        }
        else {
            thenable = getUnixLocale();
        }
        return thenable.then(locale => locale || defaultLocale)
            .catch(() => defaultLocale);
    });
    module.exports.sync = mem(opts => {
        opts = opts || defaultOpts;
        const envLocale = getEnvLocale();
        let res;
        if (envLocale || opts.spawn === false) {
            res = getLocale(envLocale);
        }
        else {
            try {
                if (process.platform === 'win32') {
                    res = getWinLocaleSync();
                }
                else {
                    res = getUnixLocaleSync();
                }
            }
            catch (err) { }
        }
        return res || defaultLocale;
    });
}
,
/* p-finally/index */ function _(require, module, exports) {
    module.exports = (promise, onFinally) => {
        onFinally = onFinally || (() => { });
        return promise.then(val => new Promise(resolve => {
            resolve(onFinally());
        }).then(() => val), err => new Promise(resolve => {
            resolve(onFinally());
        }).then(() => {
            throw err;
        }));
    };
}
,
/* p-limit/index */ function _(require, module, exports) {
    const pTry = require(275) /* p-try */;
    module.exports = concurrency => {
        if (concurrency < 1) {
            throw new TypeError('Expected `concurrency` to be a number from 1 and up');
        }
        const queue = [];
        let activeCount = 0;
        const next = () => {
            activeCount--;
            if (queue.length > 0) {
                queue.shift()();
            }
        };
        return fn => new Promise((resolve, reject) => {
            const run = () => {
                activeCount++;
                pTry(() => fn()).then(val => {
                    resolve(val);
                    next();
                }, err => {
                    reject(err);
                    next();
                });
            };
            if (activeCount < concurrency) {
                run();
            }
            else {
                queue.push(run);
            }
        });
    };
}
,
/* p-locate/index */ function _(require, module, exports) {
    const pLimit = require(273) /* p-limit */;
    class EndError extends Error {
        constructor(value) {
            super();
            this.value = value;
        }
    }
    // the input can also be a promise, so we `Promise.all()` them both
    const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));
    module.exports = (iterable, tester, opts) => {
        opts = Object.assign({
            concurrency: Infinity,
            preserveOrder: true
        }, opts);
        const limit = pLimit(opts.concurrency);
        // start all the promises concurrently with optional limit
        const items = Array.from(iterable).map(el => [el, limit(() => Promise.resolve(el).then(tester))]);
        // check the promises either serially or concurrently
        const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
        return Promise.all(items.map(el => checkLimit(() => finder(el))))
            .then(() => { })
            .catch(err => err instanceof EndError ? err.value : Promise.reject(err));
    };
}
,
/* p-try/index */ function _(require, module, exports) {
    module.exports = cb => new Promise(resolve => {
        resolve(cb());
    });
}
,
/* path-exists/index */ function _(require, module, exports) {
    const fs = require('fs');
    module.exports = fp => new Promise(resolve => {
        fs.access(fp, err => {
            resolve(!err);
        });
    });
    module.exports.sync = fp => {
        try {
            fs.accessSync(fp);
            return true;
        }
        catch (err) {
            return false;
        }
    };
}
,
/* path-key/index */ function _(require, module, exports) {
    module.exports = opts => {
        opts = opts || {};
        const env = opts.env || process.env;
        const platform = opts.platform || process.platform;
        if (platform !== 'win32') {
            return 'PATH';
        }
        return Object.keys(env).find(x => x.toUpperCase() === 'PATH') || 'Path';
    };
}
,
/* performance-now/lib/performance-now */ function _(require, module, exports) {
    // Generated by CoffeeScript 1.12.2
    (function () {
        var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
        if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
            module.exports = function () {
                return performance.now();
            };
        }
        else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
            module.exports = function () {
                return (getNanoSeconds() - nodeLoadTime) / 1e6;
            };
            hrtime = process.hrtime;
            getNanoSeconds = function () {
                var hr;
                hr = hrtime();
                return hr[0] * 1e9 + hr[1];
            };
            moduleLoadTime = getNanoSeconds();
            upTime = process.uptime() * 1e9;
            nodeLoadTime = moduleLoadTime - upTime;
        }
        else if (Date.now) {
            module.exports = function () {
                return Date.now() - loadTime;
            };
            loadTime = Date.now();
        }
        else {
            module.exports = function () {
                return new Date().getTime() - loadTime;
            };
            loadTime = new Date().getTime();
        }
    }).call(this);
}
,
/* promise/index */ function _(require, module, exports) {
    module.exports = require(284) /* ./lib */;
}
,
/* promise/lib/core */ function _(require, module, exports) {
    var asap = require(46) /* asap/raw */;
    function noop() { }
    // States:
    //
    // 0 - pending
    // 1 - fulfilled with _value
    // 2 - rejected with _value
    // 3 - adopted the state of another promise, _value
    //
    // once the state is no longer pending (0) it is immutable
    // All `_` prefixed properties will be reduced to `_{random number}`
    // at build time to obfuscate them and discourage their use.
    // We don't use symbols or Object.defineProperty to fully hide them
    // because the performance isn't good enough.
    // to avoid using try/catch inside critical functions, we
    // extract them to here.
    var LAST_ERROR = null;
    var IS_ERROR = {};
    function getThen(obj) {
        try {
            return obj.then;
        }
        catch (ex) {
            LAST_ERROR = ex;
            return IS_ERROR;
        }
    }
    function tryCallOne(fn, a) {
        try {
            return fn(a);
        }
        catch (ex) {
            LAST_ERROR = ex;
            return IS_ERROR;
        }
    }
    function tryCallTwo(fn, a, b) {
        try {
            fn(a, b);
        }
        catch (ex) {
            LAST_ERROR = ex;
            return IS_ERROR;
        }
    }
    module.exports = Promise;
    function Promise(fn) {
        if (typeof this !== 'object') {
            throw new TypeError('Promises must be constructed via new');
        }
        if (typeof fn !== 'function') {
            throw new TypeError('Promise constructor\'s argument is not a function');
        }
        this._40 = 0;
        this._65 = 0;
        this._55 = null;
        this._72 = null;
        if (fn === noop)
            return;
        doResolve(fn, this);
    }
    Promise._37 = null;
    Promise._87 = null;
    Promise._61 = noop;
    Promise.prototype.then = function (onFulfilled, onRejected) {
        if (this.constructor !== Promise) {
            return safeThen(this, onFulfilled, onRejected);
        }
        var res = new Promise(noop);
        handle(this, new Handler(onFulfilled, onRejected, res));
        return res;
    };
    function safeThen(self, onFulfilled, onRejected) {
        return new self.constructor(function (resolve, reject) {
            var res = new Promise(noop);
            res.then(resolve, reject);
            handle(self, new Handler(onFulfilled, onRejected, res));
        });
    }
    function handle(self, deferred) {
        while (self._65 === 3) {
            self = self._55;
        }
        if (Promise._37) {
            Promise._37(self);
        }
        if (self._65 === 0) {
            if (self._40 === 0) {
                self._40 = 1;
                self._72 = deferred;
                return;
            }
            if (self._40 === 1) {
                self._40 = 2;
                self._72 = [self._72, deferred];
                return;
            }
            self._72.push(deferred);
            return;
        }
        handleResolved(self, deferred);
    }
    function handleResolved(self, deferred) {
        asap(function () {
            var cb = self._65 === 1 ? deferred.onFulfilled : deferred.onRejected;
            if (cb === null) {
                if (self._65 === 1) {
                    resolve(deferred.promise, self._55);
                }
                else {
                    reject(deferred.promise, self._55);
                }
                return;
            }
            var ret = tryCallOne(cb, self._55);
            if (ret === IS_ERROR) {
                reject(deferred.promise, LAST_ERROR);
            }
            else {
                resolve(deferred.promise, ret);
            }
        });
    }
    function resolve(self, newValue) {
        // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
        if (newValue === self) {
            return reject(self, new TypeError('A promise cannot be resolved with itself.'));
        }
        if (newValue &&
            (typeof newValue === 'object' || typeof newValue === 'function')) {
            var then = getThen(newValue);
            if (then === IS_ERROR) {
                return reject(self, LAST_ERROR);
            }
            if (then === self.then &&
                newValue instanceof Promise) {
                self._65 = 3;
                self._55 = newValue;
                finale(self);
                return;
            }
            else if (typeof then === 'function') {
                doResolve(then.bind(newValue), self);
                return;
            }
        }
        self._65 = 1;
        self._55 = newValue;
        finale(self);
    }
    function reject(self, newValue) {
        self._65 = 2;
        self._55 = newValue;
        if (Promise._87) {
            Promise._87(self, newValue);
        }
        finale(self);
    }
    function finale(self) {
        if (self._40 === 1) {
            handle(self, self._72);
            self._72 = null;
        }
        if (self._40 === 2) {
            for (var i = 0; i < self._72.length; i++) {
                handle(self, self._72[i]);
            }
            self._72 = null;
        }
    }
    function Handler(onFulfilled, onRejected, promise) {
        this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
        this.onRejected = typeof onRejected === 'function' ? onRejected : null;
        this.promise = promise;
    }
    /**
     * Take a potentially misbehaving resolver function and make sure
     * onFulfilled and onRejected are only called once.
     *
     * Makes no guarantees about asynchrony.
     */
    function doResolve(fn, promise) {
        var done = false;
        var res = tryCallTwo(fn, function (value) {
            if (done)
                return;
            done = true;
            resolve(promise, value);
        }, function (reason) {
            if (done)
                return;
            done = true;
            reject(promise, reason);
        });
        if (!done && res === IS_ERROR) {
            done = true;
            reject(promise, LAST_ERROR);
        }
    }
}
,
/* promise/lib/done */ function _(require, module, exports) {
    var Promise = require(280) /* ./core.js */;
    module.exports = Promise;
    Promise.prototype.done = function (onFulfilled, onRejected) {
        var self = arguments.length ? this.then.apply(this, arguments) : this;
        self.then(null, function (err) {
            setTimeout(function () {
                throw err;
            }, 0);
        });
    };
}
,
/* promise/lib/es6-extensions */ function _(require, module, exports) {
    //This file contains the ES6 extensions to the core Promises/A+ API
    var Promise = require(280) /* ./core.js */;
    module.exports = Promise;
    /* Static Functions */
    var TRUE = valuePromise(true);
    var FALSE = valuePromise(false);
    var NULL = valuePromise(null);
    var UNDEFINED = valuePromise(undefined);
    var ZERO = valuePromise(0);
    var EMPTYSTRING = valuePromise('');
    function valuePromise(value) {
        var p = new Promise(Promise._61);
        p._65 = 1;
        p._55 = value;
        return p;
    }
    Promise.resolve = function (value) {
        if (value instanceof Promise)
            return value;
        if (value === null)
            return NULL;
        if (value === undefined)
            return UNDEFINED;
        if (value === true)
            return TRUE;
        if (value === false)
            return FALSE;
        if (value === 0)
            return ZERO;
        if (value === '')
            return EMPTYSTRING;
        if (typeof value === 'object' || typeof value === 'function') {
            try {
                var then = value.then;
                if (typeof then === 'function') {
                    return new Promise(then.bind(value));
                }
            }
            catch (ex) {
                return new Promise(function (resolve, reject) {
                    reject(ex);
                });
            }
        }
        return valuePromise(value);
    };
    Promise.all = function (arr) {
        var args = Array.prototype.slice.call(arr);
        return new Promise(function (resolve, reject) {
            if (args.length === 0)
                return resolve([]);
            var remaining = args.length;
            function res(i, val) {
                if (val && (typeof val === 'object' || typeof val === 'function')) {
                    if (val instanceof Promise && val.then === Promise.prototype.then) {
                        while (val._65 === 3) {
                            val = val._55;
                        }
                        if (val._65 === 1)
                            return res(i, val._55);
                        if (val._65 === 2)
                            reject(val._55);
                        val.then(function (val) {
                            res(i, val);
                        }, reject);
                        return;
                    }
                    else {
                        var then = val.then;
                        if (typeof then === 'function') {
                            var p = new Promise(then.bind(val));
                            p.then(function (val) {
                                res(i, val);
                            }, reject);
                            return;
                        }
                    }
                }
                args[i] = val;
                if (--remaining === 0) {
                    resolve(args);
                }
            }
            for (var i = 0; i < args.length; i++) {
                res(i, args[i]);
            }
        });
    };
    Promise.reject = function (value) {
        return new Promise(function (resolve, reject) {
            reject(value);
        });
    };
    Promise.race = function (values) {
        return new Promise(function (resolve, reject) {
            values.forEach(function (value) {
                Promise.resolve(value).then(resolve, reject);
            });
        });
    };
    /* Prototype Methods */
    Promise.prototype['catch'] = function (onRejected) {
        return this.then(null, onRejected);
    };
}
,
/* promise/lib/finally */ function _(require, module, exports) {
    var Promise = require(280) /* ./core.js */;
    module.exports = Promise;
    Promise.prototype['finally'] = function (f) {
        return this.then(function (value) {
            return Promise.resolve(f()).then(function () {
                return value;
            });
        }, function (err) {
            return Promise.resolve(f()).then(function () {
                throw err;
            });
        });
    };
}
,
/* promise/lib/index */ function _(require, module, exports) {
    module.exports = require(280) /* ./core.js */;
    require(281) /* ./done.js */;
    require(283) /* ./finally.js */;
    require(282) /* ./es6-extensions.js */;
    require(285) /* ./node-extensions.js */;
    require(286) /* ./synchronous.js */;
}
,
/* promise/lib/node-extensions */ function _(require, module, exports) {
    // This file contains then/promise specific extensions that are only useful
    // for node.js interop
    var Promise = require(280) /* ./core.js */;
    var asap = require(45) /* asap */;
    module.exports = Promise;
    /* Static Functions */
    Promise.denodeify = function (fn, argumentCount) {
        if (typeof argumentCount === 'number' && argumentCount !== Infinity) {
            return denodeifyWithCount(fn, argumentCount);
        }
        else {
            return denodeifyWithoutCount(fn);
        }
    };
    var callbackFn = ('function (err, res) {' +
        'if (err) { rj(err); } else { rs(res); }' +
        '}');
    function denodeifyWithCount(fn, argumentCount) {
        var args = [];
        for (var i = 0; i < argumentCount; i++) {
            args.push('a' + i);
        }
        var body = [
            'return function (' + args.join(',') + ') {',
            'var self = this;',
            'return new Promise(function (rs, rj) {',
            'var res = fn.call(',
            ['self'].concat(args).concat([callbackFn]).join(','),
            ');',
            'if (res &&',
            '(typeof res === "object" || typeof res === "function") &&',
            'typeof res.then === "function"',
            ') {rs(res);}',
            '});',
            '};'
        ].join('');
        return Function(['Promise', 'fn'], body)(Promise, fn);
    }
    function denodeifyWithoutCount(fn) {
        var fnLength = Math.max(fn.length - 1, 3);
        var args = [];
        for (var i = 0; i < fnLength; i++) {
            args.push('a' + i);
        }
        var body = [
            'return function (' + args.join(',') + ') {',
            'var self = this;',
            'var args;',
            'var argLength = arguments.length;',
            'if (arguments.length > ' + fnLength + ') {',
            'args = new Array(arguments.length + 1);',
            'for (var i = 0; i < arguments.length; i++) {',
            'args[i] = arguments[i];',
            '}',
            '}',
            'return new Promise(function (rs, rj) {',
            'var cb = ' + callbackFn + ';',
            'var res;',
            'switch (argLength) {',
            args.concat(['extra']).map(function (_, index) {
                return ('case ' + (index) + ':' +
                    'res = fn.call(' + ['self'].concat(args.slice(0, index)).concat('cb').join(',') + ');' +
                    'break;');
            }).join(''),
            'default:',
            'args[argLength] = cb;',
            'res = fn.apply(self, args);',
            '}',
            'if (res &&',
            '(typeof res === "object" || typeof res === "function") &&',
            'typeof res.then === "function"',
            ') {rs(res);}',
            '});',
            '};'
        ].join('');
        return Function(['Promise', 'fn'], body)(Promise, fn);
    }
    Promise.nodeify = function (fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null;
            var ctx = this;
            try {
                return fn.apply(this, arguments).nodeify(callback, ctx);
            }
            catch (ex) {
                if (callback === null || typeof callback == 'undefined') {
                    return new Promise(function (resolve, reject) {
                        reject(ex);
                    });
                }
                else {
                    asap(function () {
                        callback.call(ctx, ex);
                    });
                }
            }
        };
    };
    Promise.prototype.nodeify = function (callback, ctx) {
        if (typeof callback != 'function')
            return this;
        this.then(function (value) {
            asap(function () {
                callback.call(ctx, null, value);
            });
        }, function (err) {
            asap(function () {
                callback.call(ctx, err);
            });
        });
    };
}
,
/* promise/lib/synchronous */ function _(require, module, exports) {
    var Promise = require(280) /* ./core.js */;
    module.exports = Promise;
    Promise.enableSynchronous = function () {
        Promise.prototype.isPending = function () {
            return this.getState() == 0;
        };
        Promise.prototype.isFulfilled = function () {
            return this.getState() == 1;
        };
        Promise.prototype.isRejected = function () {
            return this.getState() == 2;
        };
        Promise.prototype.getValue = function () {
            if (this._65 === 3) {
                return this._55.getValue();
            }
            if (!this.isFulfilled()) {
                throw new Error('Cannot get a value of an unfulfilled promise.');
            }
            return this._55;
        };
        Promise.prototype.getReason = function () {
            if (this._65 === 3) {
                return this._55.getReason();
            }
            if (!this.isRejected()) {
                throw new Error('Cannot get a rejection reason of a non-rejected promise.');
            }
            return this._55;
        };
        Promise.prototype.getState = function () {
            if (this._65 === 3) {
                return this._55.getState();
            }
            if (this._65 === -1 || this._65 === -2) {
                return 0;
            }
            return this._65;
        };
    };
    Promise.disableSynchronous = function () {
        Promise.prototype.isPending = undefined;
        Promise.prototype.isFulfilled = undefined;
        Promise.prototype.isRejected = undefined;
        Promise.prototype.getValue = undefined;
        Promise.prototype.getReason = undefined;
        Promise.prototype.getState = undefined;
    };
}
,
/* pseudomap/map */ function _(require, module, exports) {
    if (process.env.npm_package_name === 'pseudomap' &&
        process.env.npm_lifecycle_script === 'test')
        process.env.TEST_PSEUDOMAP = 'true';
    if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
        module.exports = Map;
    }
    else {
        module.exports = require(288) /* ./pseudomap */;
    }
}
,
/* pseudomap/pseudomap */ function _(require, module, exports) {
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    module.exports = PseudoMap;
    function PseudoMap(set) {
        if (!(this instanceof PseudoMap)) // whyyyyyyy
            throw new TypeError("Constructor PseudoMap requires 'new'");
        this.clear();
        if (set) {
            if ((set instanceof PseudoMap) ||
                (typeof Map === 'function' && set instanceof Map))
                set.forEach(function (value, key) {
                    this.set(key, value);
                }, this);
            else if (Array.isArray(set))
                set.forEach(function (kv) {
                    this.set(kv[0], kv[1]);
                }, this);
            else
                throw new TypeError('invalid argument');
        }
    }
    PseudoMap.prototype.forEach = function (fn, thisp) {
        thisp = thisp || this;
        Object.keys(this._data).forEach(function (k) {
            if (k !== 'size')
                fn.call(thisp, this._data[k].value, this._data[k].key);
        }, this);
    };
    PseudoMap.prototype.has = function (k) {
        return !!find(this._data, k);
    };
    PseudoMap.prototype.get = function (k) {
        var res = find(this._data, k);
        return res && res.value;
    };
    PseudoMap.prototype.set = function (k, v) {
        set(this._data, k, v);
    };
    PseudoMap.prototype.delete = function (k) {
        var res = find(this._data, k);
        if (res) {
            delete this._data[res._index];
            this._data.size--;
        }
    };
    PseudoMap.prototype.clear = function () {
        var data = Object.create(null);
        data.size = 0;
        Object.defineProperty(this, '_data', {
            value: data,
            enumerable: false,
            configurable: true,
            writable: false
        });
    };
    Object.defineProperty(PseudoMap.prototype, 'size', {
        get: function () {
            return this._data.size;
        },
        set: function (n) { },
        enumerable: true,
        configurable: true
    });
    PseudoMap.prototype.values =
        PseudoMap.prototype.keys =
            PseudoMap.prototype.entries = function () {
                throw new Error('iterators are not implemented in this version');
            };
    // Either identical, or both NaN
    function same(a, b) {
        return a === b || a !== a && b !== b;
    }
    function Entry(k, v, i) {
        this.key = k;
        this.value = v;
        this._index = i;
    }
    function find(data, k) {
        for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
            if (same(data[key].key, k))
                return data[key];
        }
    }
    function set(data, k, v) {
        for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
            if (same(data[key].key, k)) {
                data[key].value = v;
                return;
            }
        }
        data.size++;
        data[key] = new Entry(k, v, key);
    }
}
,
/* qs/lib/formats */ function _(require, module, exports) {
    var replace = String.prototype.replace;
    var percentTwenties = /%20/g;
    module.exports = {
        'default': 'RFC3986',
        formatters: {
            RFC1738: function (value) {
                return replace.call(value, percentTwenties, '+');
            },
            RFC3986: function (value) {
                return value;
            }
        },
        RFC1738: 'RFC1738',
        RFC3986: 'RFC3986'
    };
}
,
/* qs/lib/index */ function _(require, module, exports) {
    var stringify = require(292) /* ./stringify */;
    var parse = require(291) /* ./parse */;
    var formats = require(289) /* ./formats */;
    module.exports = {
        formats: formats,
        parse: parse,
        stringify: stringify
    };
}
,
/* qs/lib/parse */ function _(require, module, exports) {
    var utils = require(293) /* ./utils */;
    var has = Object.prototype.hasOwnProperty;
    var defaults = {
        allowDots: false,
        allowPrototypes: false,
        arrayLimit: 20,
        decoder: utils.decode,
        delimiter: '&',
        depth: 5,
        parameterLimit: 1000,
        plainObjects: false,
        strictNullHandling: false
    };
    var parseValues = function parseQueryStringValues(str, options) {
        var obj = {};
        var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
        var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
        var parts = cleanStr.split(options.delimiter, limit);
        for (var i = 0; i < parts.length; ++i) {
            var part = parts[i];
            var bracketEqualsPos = part.indexOf(']=');
            var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
            var key, val;
            if (pos === -1) {
                key = options.decoder(part, defaults.decoder);
                val = options.strictNullHandling ? null : '';
            }
            else {
                key = options.decoder(part.slice(0, pos), defaults.decoder);
                val = options.decoder(part.slice(pos + 1), defaults.decoder);
            }
            if (has.call(obj, key)) {
                obj[key] = [].concat(obj[key]).concat(val);
            }
            else {
                obj[key] = val;
            }
        }
        return obj;
    };
    var parseObject = function (chain, val, options) {
        var leaf = val;
        for (var i = chain.length - 1; i >= 0; --i) {
            var obj;
            var root = chain[i];
            if (root === '[]') {
                obj = [];
                obj = obj.concat(leaf);
            }
            else {
                obj = options.plainObjects ? Object.create(null) : {};
                var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
                var index = parseInt(cleanRoot, 10);
                if (!isNaN(index)
                    && root !== cleanRoot
                    && String(index) === cleanRoot
                    && index >= 0
                    && (options.parseArrays && index <= options.arrayLimit)) {
                    obj = [];
                    obj[index] = leaf;
                }
                else {
                    obj[cleanRoot] = leaf;
                }
            }
            leaf = obj;
        }
        return leaf;
    };
    var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
        if (!givenKey) {
            return;
        }
        // Transform dot notation to bracket notation
        var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
        // The regex chunks
        var brackets = /(\[[^[\]]*])/;
        var child = /(\[[^[\]]*])/g;
        // Get the parent
        var segment = brackets.exec(key);
        var parent = segment ? key.slice(0, segment.index) : key;
        // Stash the parent if it exists
        var keys = [];
        if (parent) {
            // If we aren't using plain objects, optionally prefix keys
            // that would overwrite object prototype properties
            if (!options.plainObjects && has.call(Object.prototype, parent)) {
                if (!options.allowPrototypes) {
                    return;
                }
            }
            keys.push(parent);
        }
        // Loop through children appending to the array until we hit depth
        var i = 0;
        while ((segment = child.exec(key)) !== null && i < options.depth) {
            i += 1;
            if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
                if (!options.allowPrototypes) {
                    return;
                }
            }
            keys.push(segment[1]);
        }
        // If there's a remainder, just add whatever is left
        if (segment) {
            keys.push('[' + key.slice(segment.index) + ']');
        }
        return parseObject(keys, val, options);
    };
    module.exports = function (str, opts) {
        var options = opts ? utils.assign({}, opts) : {};
        if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
            throw new TypeError('Decoder has to be a function.');
        }
        options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
        options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
        options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
        options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
        options.parseArrays = options.parseArrays !== false;
        options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
        options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
        options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
        options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
        options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
        options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
        if (str === '' || str === null || typeof str === 'undefined') {
            return options.plainObjects ? Object.create(null) : {};
        }
        var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
        var obj = options.plainObjects ? Object.create(null) : {};
        // Iterate over the keys and setup the new object
        var keys = Object.keys(tempObj);
        for (var i = 0; i < keys.length; ++i) {
            var key = keys[i];
            var newObj = parseKeys(key, tempObj[key], options);
            obj = utils.merge(obj, newObj, options);
        }
        return utils.compact(obj);
    };
}
,
/* qs/lib/stringify */ function _(require, module, exports) {
    var utils = require(293) /* ./utils */;
    var formats = require(289) /* ./formats */;
    var arrayPrefixGenerators = {
        brackets: function brackets(prefix) {
            return prefix + '[]';
        },
        indices: function indices(prefix, key) {
            return prefix + '[' + key + ']';
        },
        repeat: function repeat(prefix) {
            return prefix;
        }
    };
    var toISO = Date.prototype.toISOString;
    var defaults = {
        delimiter: '&',
        encode: true,
        encoder: utils.encode,
        encodeValuesOnly: false,
        serializeDate: function serializeDate(date) {
            return toISO.call(date);
        },
        skipNulls: false,
        strictNullHandling: false
    };
    var stringify = function stringify(// eslint-disable-line func-name-matching
    object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly) {
        var obj = object;
        if (typeof filter === 'function') {
            obj = filter(prefix, obj);
        }
        else if (obj instanceof Date) {
            obj = serializeDate(obj);
        }
        else if (obj === null) {
            if (strictNullHandling) {
                return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix;
            }
            obj = '';
        }
        if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
            if (encoder) {
                var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder);
                return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))];
            }
            return [formatter(prefix) + '=' + formatter(String(obj))];
        }
        var values = [];
        if (typeof obj === 'undefined') {
            return values;
        }
        var objKeys;
        if (Array.isArray(filter)) {
            objKeys = filter;
        }
        else {
            var keys = Object.keys(obj);
            objKeys = sort ? keys.sort(sort) : keys;
        }
        for (var i = 0; i < objKeys.length; ++i) {
            var key = objKeys[i];
            if (skipNulls && obj[key] === null) {
                continue;
            }
            if (Array.isArray(obj)) {
                values = values.concat(stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly));
            }
            else {
                values = values.concat(stringify(obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly));
            }
        }
        return values;
    };
    module.exports = function (object, opts) {
        var obj = object;
        var options = opts ? utils.assign({}, opts) : {};
        if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
            throw new TypeError('Encoder has to be a function.');
        }
        var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
        var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
        var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
        var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
        var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder;
        var sort = typeof options.sort === 'function' ? options.sort : null;
        var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
        var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
        var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
        if (typeof options.format === 'undefined') {
            options.format = formats['default'];
        }
        else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
            throw new TypeError('Unknown format option provided.');
        }
        var formatter = formats.formatters[options.format];
        var objKeys;
        var filter;
        if (typeof options.filter === 'function') {
            filter = options.filter;
            obj = filter('', obj);
        }
        else if (Array.isArray(options.filter)) {
            filter = options.filter;
            objKeys = filter;
        }
        var keys = [];
        if (typeof obj !== 'object' || obj === null) {
            return '';
        }
        var arrayFormat;
        if (options.arrayFormat in arrayPrefixGenerators) {
            arrayFormat = options.arrayFormat;
        }
        else if ('indices' in options) {
            arrayFormat = options.indices ? 'indices' : 'repeat';
        }
        else {
            arrayFormat = 'indices';
        }
        var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
        if (!objKeys) {
            objKeys = Object.keys(obj);
        }
        if (sort) {
            objKeys.sort(sort);
        }
        for (var i = 0; i < objKeys.length; ++i) {
            var key = objKeys[i];
            if (skipNulls && obj[key] === null) {
                continue;
            }
            keys = keys.concat(stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly));
        }
        var joined = keys.join(delimiter);
        var prefix = options.addQueryPrefix === true ? '?' : '';
        return joined.length > 0 ? prefix + joined : '';
    };
}
,
/* qs/lib/utils */ function _(require, module, exports) {
    var has = Object.prototype.hasOwnProperty;
    var hexTable = (function () {
        var array = [];
        for (var i = 0; i < 256; ++i) {
            array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
        }
        return array;
    }());
    var compactQueue = function compactQueue(queue) {
        var obj;
        while (queue.length) {
            var item = queue.pop();
            obj = item.obj[item.prop];
            if (Array.isArray(obj)) {
                var compacted = [];
                for (var j = 0; j < obj.length; ++j) {
                    if (typeof obj[j] !== 'undefined') {
                        compacted.push(obj[j]);
                    }
                }
                item.obj[item.prop] = compacted;
            }
        }
        return obj;
    };
    var arrayToObject = function arrayToObject(source, options) {
        var obj = options && options.plainObjects ? Object.create(null) : {};
        for (var i = 0; i < source.length; ++i) {
            if (typeof source[i] !== 'undefined') {
                obj[i] = source[i];
            }
        }
        return obj;
    };
    var merge = function merge(target, source, options) {
        if (!source) {
            return target;
        }
        if (typeof source !== 'object') {
            if (Array.isArray(target)) {
                target.push(source);
            }
            else if (typeof target === 'object') {
                if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
                    target[source] = true;
                }
            }
            else {
                return [target, source];
            }
            return target;
        }
        if (typeof target !== 'object') {
            return [target].concat(source);
        }
        var mergeTarget = target;
        if (Array.isArray(target) && !Array.isArray(source)) {
            mergeTarget = arrayToObject(target, options);
        }
        if (Array.isArray(target) && Array.isArray(source)) {
            source.forEach(function (item, i) {
                if (has.call(target, i)) {
                    if (target[i] && typeof target[i] === 'object') {
                        target[i] = merge(target[i], item, options);
                    }
                    else {
                        target.push(item);
                    }
                }
                else {
                    target[i] = item;
                }
            });
            return target;
        }
        return Object.keys(source).reduce(function (acc, key) {
            var value = source[key];
            if (has.call(acc, key)) {
                acc[key] = merge(acc[key], value, options);
            }
            else {
                acc[key] = value;
            }
            return acc;
        }, mergeTarget);
    };
    var assign = function assignSingleSource(target, source) {
        return Object.keys(source).reduce(function (acc, key) {
            acc[key] = source[key];
            return acc;
        }, target);
    };
    var decode = function (str) {
        try {
            return decodeURIComponent(str.replace(/\+/g, ' '));
        }
        catch (e) {
            return str;
        }
    };
    var encode = function encode(str) {
        // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
        // It has been adapted here for stricter adherence to RFC 3986
        if (str.length === 0) {
            return str;
        }
        var string = typeof str === 'string' ? str : String(str);
        var out = '';
        for (var i = 0; i < string.length; ++i) {
            var c = string.charCodeAt(i);
            if (c === 0x2D // -
                || c === 0x2E // .
                || c === 0x5F // _
                || c === 0x7E // ~
                || (c >= 0x30 && c <= 0x39) // 0-9
                || (c >= 0x41 && c <= 0x5A) // a-z
                || (c >= 0x61 && c <= 0x7A) // A-Z
            ) {
                out += string.charAt(i);
                continue;
            }
            if (c < 0x80) {
                out = out + hexTable[c];
                continue;
            }
            if (c < 0x800) {
                out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
                continue;
            }
            if (c < 0xD800 || c >= 0xE000) {
                out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
                continue;
            }
            i += 1;
            c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
            out += hexTable[0xF0 | (c >> 18)]
                + hexTable[0x80 | ((c >> 12) & 0x3F)]
                + hexTable[0x80 | ((c >> 6) & 0x3F)]
                + hexTable[0x80 | (c & 0x3F)];
        }
        return out;
    };
    var compact = function compact(value) {
        var queue = [{ obj: { o: value }, prop: 'o' }];
        var refs = [];
        for (var i = 0; i < queue.length; ++i) {
            var item = queue[i];
            var obj = item.obj[item.prop];
            var keys = Object.keys(obj);
            for (var j = 0; j < keys.length; ++j) {
                var key = keys[j];
                var val = obj[key];
                if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
                    queue.push({ obj: obj, prop: key });
                    refs.push(val);
                }
            }
        }
        return compactQueue(queue);
    };
    var isRegExp = function isRegExp(obj) {
        return Object.prototype.toString.call(obj) === '[object RegExp]';
    };
    var isBuffer = function isBuffer(obj) {
        if (obj === null || typeof obj === 'undefined') {
            return false;
        }
        return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
    };
    module.exports = {
        arrayToObject: arrayToObject,
        assign: assign,
        compact: compact,
        decode: decode,
        encode: encode,
        isBuffer: isBuffer,
        isRegExp: isRegExp,
        merge: merge
    };
}
,
/* repeat-string/index */ function _(require, module, exports) {
    /**
     * Results cache
     */
    var res = '';
    var cache;
    /**
     * Expose `repeat`
     */
    module.exports = repeat;
    /**
     * Repeat the given `string` the specified `number`
     * of times.
     *
     * **Example:**
     *
     * ```js
     * var repeat = require('repeat-string');
     * repeat('A', 5);
     * //=> AAAAA
     * ```
     *
     * @param {String} `string` The string to repeat
     * @param {Number} `number` The number of times to repeat the string
     * @return {String} Repeated string
     * @api public
     */
    function repeat(str, num) {
        if (typeof str !== 'string') {
            throw new TypeError('expected a string');
        }
        // cover common, quick use cases
        if (num === 1)
            return str;
        if (num === 2)
            return str + str;
        var max = str.length * num;
        if (cache !== str || typeof cache === 'undefined') {
            cache = str;
            res = '';
        }
        else if (res.length >= max) {
            return res.substr(0, max);
        }
        while (max > res.length && num > 1) {
            if (num & 1) {
                res += str;
            }
            num >>= 1;
            str += str;
        }
        res += str;
        res = res.substr(0, max);
        return res;
    }
}
,
/* request/index */ function _(require, module, exports) {
    var extend = require(106) /* extend */;
    var cookies = require(297) /* ./lib/cookies */;
    var helpers = require(301) /* ./lib/helpers */;
    var paramsHaveRequestBody = helpers.paramsHaveRequestBody;
    // organize params for patch, post, put, head, del
    function initParams(uri, options, callback) {
        if (typeof options === 'function') {
            callback = options;
        }
        var params = {};
        if (typeof options === 'object') {
            extend(params, options, { uri: uri });
        }
        else if (typeof uri === 'string') {
            extend(params, { uri: uri });
        }
        else {
            extend(params, uri);
        }
        params.callback = callback || params.callback;
        return params;
    }
    function request(uri, options, callback) {
        if (typeof uri === 'undefined') {
            throw new Error('undefined is not a valid uri or options object.');
        }
        var params = initParams(uri, options, callback);
        if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
            throw new Error('HTTP HEAD requests MUST NOT include a request body.');
        }
        return new request.Request(params);
    }
    function verbFunc(verb) {
        var method = verb.toUpperCase();
        return function (uri, options, callback) {
            var params = initParams(uri, options, callback);
            params.method = method;
            return request(params, params.callback);
        };
    }
    // define like this to please codeintel/intellisense IDEs
    request.get = verbFunc('get');
    request.head = verbFunc('head');
    request.options = verbFunc('options');
    request.post = verbFunc('post');
    request.put = verbFunc('put');
    request.patch = verbFunc('patch');
    request.del = verbFunc('delete');
    request['delete'] = verbFunc('delete');
    request.jar = function (store) {
        return cookies.jar(store);
    };
    request.cookie = function (str) {
        return cookies.parse(str);
    };
    function wrapRequestMethod(method, options, requester, verb) {
        return function (uri, opts, callback) {
            var params = initParams(uri, opts, callback);
            var target = {};
            extend(true, target, options, params);
            target.pool = params.pool || options.pool;
            if (verb) {
                target.method = verb.toUpperCase();
            }
            if (typeof requester === 'function') {
                method = requester;
            }
            return method(target, target.callback);
        };
    }
    request.defaults = function (options, requester) {
        var self = this;
        options = options || {};
        if (typeof options === 'function') {
            requester = options;
            options = {};
        }
        var defaults = wrapRequestMethod(self, options, requester);
        var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete'];
        verbs.forEach(function (verb) {
            defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb);
        });
        defaults.cookie = wrapRequestMethod(self.cookie, options, requester);
        defaults.jar = self.jar;
        defaults.defaults = self.defaults;
        return defaults;
    };
    request.forever = function (agentOptions, optionsArg) {
        var options = {};
        if (optionsArg) {
            extend(options, optionsArg);
        }
        if (agentOptions) {
            options.agentOptions = agentOptions;
        }
        options.forever = true;
        return request.defaults(options);
    };
    // Exports
    module.exports = request;
    request.Request = require(307) /* ./request */;
    request.initParams = initParams;
    // Backwards compatibility for request.debug
    Object.defineProperty(request, 'debug', {
        enumerable: true,
        get: function () {
            return request.Request.debug;
        },
        set: function (debug) {
            request.Request.debug = debug;
        }
    });
}
,
/* request/lib/auth */ function _(require, module, exports) {
    var caseless = require(70) /* caseless */;
    var uuid = require(370) /* uuid/v4 */;
    var helpers = require(301) /* ./helpers */;
    var md5 = helpers.md5;
    var toBase64 = helpers.toBase64;
    function Auth(request) {
        // define all public properties here
        this.request = request;
        this.hasAuth = false;
        this.sentAuth = false;
        this.bearerToken = null;
        this.user = null;
        this.pass = null;
    }
    Auth.prototype.basic = function (user, pass, sendImmediately) {
        var self = this;
        if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
            self.request.emit('error', new Error('auth() received invalid user or password'));
        }
        self.user = user;
        self.pass = pass;
        self.hasAuth = true;
        var header = user + ':' + (pass || '');
        if (sendImmediately || typeof sendImmediately === 'undefined') {
            var authHeader = 'Basic ' + toBase64(header);
            self.sentAuth = true;
            return authHeader;
        }
    };
    Auth.prototype.bearer = function (bearer, sendImmediately) {
        var self = this;
        self.bearerToken = bearer;
        self.hasAuth = true;
        if (sendImmediately || typeof sendImmediately === 'undefined') {
            if (typeof bearer === 'function') {
                bearer = bearer();
            }
            var authHeader = 'Bearer ' + (bearer || '');
            self.sentAuth = true;
            return authHeader;
        }
    };
    Auth.prototype.digest = function (method, path, authHeader) {
        // TODO: More complete implementation of RFC 2617.
        //   - handle challenge.domain
        //   - support qop="auth-int" only
        //   - handle Authentication-Info (not necessarily?)
        //   - check challenge.stale (not necessarily?)
        //   - increase nc (not necessarily?)
        // For reference:
        // http://tools.ietf.org/html/rfc2617#section-3
        // https://github.com/bagder/curl/blob/master/lib/http_digest.c
        var self = this;
        var challenge = {};
        var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi;
        for (;;) {
            var match = re.exec(authHeader);
            if (!match) {
                break;
            }
            challenge[match[1]] = match[2] || match[3];
        }
        /**
         * RFC 2617: handle both MD5 and MD5-sess algorithms.
         *
         * If the algorithm directive's value is "MD5" or unspecified, then HA1 is
         *   HA1=MD5(username:realm:password)
         * If the algorithm directive's value is "MD5-sess", then HA1 is
         *   HA1=MD5(MD5(username:realm:password):nonce:cnonce)
         */
        var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
            var ha1 = md5(user + ':' + realm + ':' + pass);
            if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
                return md5(ha1 + ':' + nonce + ':' + cnonce);
            }
            else {
                return ha1;
            }
        };
        var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth';
        var nc = qop && '00000001';
        var cnonce = qop && uuid().replace(/-/g, '');
        var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce);
        var ha2 = md5(method + ':' + path);
        var digestResponse = qop
            ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
            : md5(ha1 + ':' + challenge.nonce + ':' + ha2);
        var authValues = {
            username: self.user,
            realm: challenge.realm,
            nonce: challenge.nonce,
            uri: path,
            qop: qop,
            response: digestResponse,
            nc: nc,
            cnonce: cnonce,
            algorithm: challenge.algorithm,
            opaque: challenge.opaque
        };
        authHeader = [];
        for (var k in authValues) {
            if (authValues[k]) {
                if (k === 'qop' || k === 'nc' || k === 'algorithm') {
                    authHeader.push(k + '=' + authValues[k]);
                }
                else {
                    authHeader.push(k + '="' + authValues[k] + '"');
                }
            }
        }
        authHeader = 'Digest ' + authHeader.join(', ');
        self.sentAuth = true;
        return authHeader;
    };
    Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
        var self = this;
        var request = self.request;
        var authHeader;
        if (bearer === undefined && user === undefined) {
            self.request.emit('error', new Error('no auth mechanism defined'));
        }
        else if (bearer !== undefined) {
            authHeader = self.bearer(bearer, sendImmediately);
        }
        else {
            authHeader = self.basic(user, pass, sendImmediately);
        }
        if (authHeader) {
            request.setHeader('authorization', authHeader);
        }
    };
    Auth.prototype.onResponse = function (response) {
        var self = this;
        var request = self.request;
        if (!self.hasAuth || self.sentAuth) {
            return null;
        }
        var c = caseless(response.headers);
        var authHeader = c.get('www-authenticate');
        var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase();
        request.debug('reauth', authVerb);
        switch (authVerb) {
            case 'basic':
                return self.basic(self.user, self.pass, true);
            case 'bearer':
                return self.bearer(self.bearerToken, true);
            case 'digest':
                return self.digest(request.method, request.path, authHeader);
        }
    };
    exports.Auth = Auth;
}
,
/* request/lib/cookies */ function _(require, module, exports) {
    var tough = require(358) /* tough-cookie */;
    var Cookie = tough.Cookie;
    var CookieJar = tough.CookieJar;
    exports.parse = function (str) {
        if (str && str.uri) {
            str = str.uri;
        }
        if (typeof str !== 'string') {
            throw new Error('The cookie function only accepts STRING as param');
        }
        return Cookie.parse(str, { loose: true });
    };
    // Adapt the sometimes-Async api of tough.CookieJar to our requirements
    function RequestJar(store) {
        var self = this;
        self._jar = new CookieJar(store, { looseMode: true });
    }
    RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
        var self = this;
        return self._jar.setCookieSync(cookieOrStr, uri, options || {});
    };
    RequestJar.prototype.getCookieString = function (uri) {
        var self = this;
        return self._jar.getCookieStringSync(uri);
    };
    RequestJar.prototype.getCookies = function (uri) {
        var self = this;
        return self._jar.getCookiesSync(uri);
    };
    exports.jar = function (store) {
        return new RequestJar(store);
    };
}
,
/* request/lib/getProxyFromURI */ function _(require, module, exports) {
    function formatHostname(hostname) {
        // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
        return hostname.replace(/^\.*/, '.').toLowerCase();
    }
    function parseNoProxyZone(zone) {
        zone = zone.trim().toLowerCase();
        var zoneParts = zone.split(':', 2);
        var zoneHost = formatHostname(zoneParts[0]);
        var zonePort = zoneParts[1];
        var hasPort = zone.indexOf(':') > -1;
        return { hostname: zoneHost, port: zonePort, hasPort: hasPort };
    }
    function uriInNoProxy(uri, noProxy) {
        var port = uri.port || (uri.protocol === 'https:' ? '443' : '80');
        var hostname = formatHostname(uri.hostname);
        var noProxyList = noProxy.split(',');
        // iterate through the noProxyList until it finds a match.
        return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
            var isMatchedAt = hostname.indexOf(noProxyZone.hostname);
            var hostnameMatched = (isMatchedAt > -1 &&
                (isMatchedAt === hostname.length - noProxyZone.hostname.length));
            if (noProxyZone.hasPort) {
                return (port === noProxyZone.port) && hostnameMatched;
            }
            return hostnameMatched;
        });
    }
    function getProxyFromURI(uri) {
        // Decide the proper request proxy to use based on the request URI object and the
        // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
        // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
        var noProxy = process.env.NO_PROXY || process.env.no_proxy || '';
        // if the noProxy is a wildcard then return null
        if (noProxy === '*') {
            return null;
        }
        // if the noProxy is not empty and the uri is found return null
        if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
            return null;
        }
        // Check for HTTP or HTTPS Proxy in environment Else default to null
        if (uri.protocol === 'http:') {
            return process.env.HTTP_PROXY ||
                process.env.http_proxy || null;
        }
        if (uri.protocol === 'https:') {
            return process.env.HTTPS_PROXY ||
                process.env.https_proxy ||
                process.env.HTTP_PROXY ||
                process.env.http_proxy || null;
        }
        // if none of that works, return null
        // (What uri protocol are you using then?)
        return null;
    }
    module.exports = getProxyFromURI;
}
,
/* request/lib/har */ function _(require, module, exports) {
    var fs = require('fs');
    var qs = require('querystring');
    var validate = require(137) /* har-validator */;
    var extend = require(106) /* extend */;
    function Har(request) {
        this.request = request;
    }
    Har.prototype.reducer = function (obj, pair) {
        // new property ?
        if (obj[pair.name] === undefined) {
            obj[pair.name] = pair.value;
            return obj;
        }
        // existing? convert to array
        var arr = [
            obj[pair.name],
            pair.value
        ];
        obj[pair.name] = arr;
        return obj;
    };
    Har.prototype.prep = function (data) {
        // construct utility properties
        data.queryObj = {};
        data.headersObj = {};
        data.postData.jsonObj = false;
        data.postData.paramsObj = false;
        // construct query objects
        if (data.queryString && data.queryString.length) {
            data.queryObj = data.queryString.reduce(this.reducer, {});
        }
        // construct headers objects
        if (data.headers && data.headers.length) {
            // loweCase header keys
            data.headersObj = data.headers.reduceRight(function (headers, header) {
                headers[header.name] = header.value;
                return headers;
            }, {});
        }
        // construct Cookie header
        if (data.cookies && data.cookies.length) {
            var cookies = data.cookies.map(function (cookie) {
                return cookie.name + '=' + cookie.value;
            });
            if (cookies.length) {
                data.headersObj.cookie = cookies.join('; ');
            }
        }
        // prep body
        function some(arr) {
            return arr.some(function (type) {
                return data.postData.mimeType.indexOf(type) === 0;
            });
        }
        if (some([
            'multipart/mixed',
            'multipart/related',
            'multipart/form-data',
            'multipart/alternative'
        ])) {
            // reset values
            data.postData.mimeType = 'multipart/form-data';
        }
        else if (some([
            'application/x-www-form-urlencoded'
        ])) {
            if (!data.postData.params) {
                data.postData.text = '';
            }
            else {
                data.postData.paramsObj = data.postData.params.reduce(this.reducer, {});
                // always overwrite
                data.postData.text = qs.stringify(data.postData.paramsObj);
            }
        }
        else if (some([
            'text/json',
            'text/x-json',
            'application/json',
            'application/x-json'
        ])) {
            data.postData.mimeType = 'application/json';
            if (data.postData.text) {
                try {
                    data.postData.jsonObj = JSON.parse(data.postData.text);
                }
                catch (e) {
                    this.request.debug(e);
                    // force back to text/plain
                    data.postData.mimeType = 'text/plain';
                }
            }
        }
        return data;
    };
    Har.prototype.options = function (options) {
        // skip if no har property defined
        if (!options.har) {
            return options;
        }
        var har = {};
        extend(har, options.har);
        // only process the first entry
        if (har.log && har.log.entries) {
            har = har.log.entries[0];
        }
        // add optional properties to make validation successful
        har.url = har.url || options.url || options.uri || options.baseUrl || '/';
        har.httpVersion = har.httpVersion || 'HTTP/1.1';
        har.queryString = har.queryString || [];
        har.headers = har.headers || [];
        har.cookies = har.cookies || [];
        har.postData = har.postData || {};
        har.postData.mimeType = har.postData.mimeType || 'application/octet-stream';
        har.bodySize = 0;
        har.headersSize = 0;
        har.postData.size = 0;
        if (!validate.request(har)) {
            return options;
        }
        // clean up and get some utility properties
        var req = this.prep(har);
        // construct new options
        if (req.url) {
            options.url = req.url;
        }
        if (req.method) {
            options.method = req.method;
        }
        if (Object.keys(req.queryObj).length) {
            options.qs = req.queryObj;
        }
        if (Object.keys(req.headersObj).length) {
            options.headers = req.headersObj;
        }
        function test(type) {
            return req.postData.mimeType.indexOf(type) === 0;
        }
        if (test('application/x-www-form-urlencoded')) {
            options.form = req.postData.paramsObj;
        }
        else if (test('application/json')) {
            if (req.postData.jsonObj) {
                options.body = req.postData.jsonObj;
                options.json = true;
            }
        }
        else if (test('multipart/form-data')) {
            options.formData = {};
            req.postData.params.forEach(function (param) {
                var attachment = {};
                if (!param.fileName && !param.fileName && !param.contentType) {
                    options.formData[param.name] = param.value;
                    return;
                }
                // attempt to read from disk!
                if (param.fileName && !param.value) {
                    attachment.value = fs.createReadStream(param.fileName);
                }
                else if (param.value) {
                    attachment.value = param.value;
                }
                if (param.fileName) {
                    attachment.options = {
                        filename: param.fileName,
                        contentType: param.contentType ? param.contentType : null
                    };
                }
                options.formData[param.name] = attachment;
            });
        }
        else {
            if (req.postData.text) {
                options.body = req.postData.text;
            }
        }
        return options;
    };
    exports.Har = Har;
}
,
/* request/lib/hawk */ function _(require, module, exports) {
    var crypto = require('crypto');
    function randomString(size) {
        var bits = (size + 1) * 6;
        var buffer = crypto.randomBytes(Math.ceil(bits / 8));
        var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
        return string.slice(0, size);
    }
    function calculatePayloadHash(payload, algorithm, contentType) {
        var hash = crypto.createHash(algorithm);
        hash.update('hawk.1.payload\n');
        hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n');
        hash.update(payload || '');
        hash.update('\n');
        return hash.digest('base64');
    }
    exports.calculateMac = function (credentials, opts) {
        var normalized = 'hawk.1.header\n' +
            opts.ts + '\n' +
            opts.nonce + '\n' +
            (opts.method || '').toUpperCase() + '\n' +
            opts.resource + '\n' +
            opts.host.toLowerCase() + '\n' +
            opts.port + '\n' +
            (opts.hash || '') + '\n';
        if (opts.ext) {
            normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n');
        }
        normalized = normalized + '\n';
        if (opts.app) {
            normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n';
        }
        var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized);
        var digest = hmac.digest('base64');
        return digest;
    };
    exports.header = function (uri, method, opts) {
        var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000);
        var credentials = opts.credentials;
        if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
            return '';
        }
        if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) {
            return '';
        }
        var artifacts = {
            ts: timestamp,
            nonce: opts.nonce || randomString(6),
            method: method,
            resource: uri.pathname + (uri.search || ''),
            host: uri.hostname,
            port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
            hash: opts.hash,
            ext: opts.ext,
            app: opts.app,
            dlg: opts.dlg
        };
        if (!artifacts.hash && (opts.payload || opts.payload === '')) {
            artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType);
        }
        var mac = exports.calculateMac(credentials, artifacts);
        var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '';
        var header = 'Hawk id="' + credentials.id +
            '", ts="' + artifacts.ts +
            '", nonce="' + artifacts.nonce +
            (artifacts.hash ? '", hash="' + artifacts.hash : '') +
            (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') +
            '", mac="' + mac + '"';
        if (artifacts.app) {
            header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
        }
        return header;
    };
}
,
/* request/lib/helpers */ function _(require, module, exports) {
    var jsonSafeStringify = require(158) /* json-stringify-safe */;
    var crypto = require('crypto');
    var Buffer = require(311) /* safe-buffer */.Buffer;
    var defer = typeof setImmediate === 'undefined'
        ? process.nextTick
        : setImmediate;
    function paramsHaveRequestBody(params) {
        return (params.body ||
            params.requestBodyStream ||
            (params.json && typeof params.json !== 'boolean') ||
            params.multipart);
    }
    function safeStringify(obj, replacer) {
        var ret;
        try {
            ret = JSON.stringify(obj, replacer);
        }
        catch (e) {
            ret = jsonSafeStringify(obj, replacer);
        }
        return ret;
    }
    function md5(str) {
        return crypto.createHash('md5').update(str).digest('hex');
    }
    function isReadStream(rs) {
        return rs.readable && rs.path && rs.mode;
    }
    function toBase64(str) {
        return Buffer.from(str || '', 'utf8').toString('base64');
    }
    function copy(obj) {
        var o = {};
        Object.keys(obj).forEach(function (i) {
            o[i] = obj[i];
        });
        return o;
    }
    function version() {
        var numbers = process.version.replace('v', '').split('.');
        return {
            major: parseInt(numbers[0], 10),
            minor: parseInt(numbers[1], 10),
            patch: parseInt(numbers[2], 10)
        };
    }
    exports.paramsHaveRequestBody = paramsHaveRequestBody;
    exports.safeStringify = safeStringify;
    exports.md5 = md5;
    exports.isReadStream = isReadStream;
    exports.toBase64 = toBase64;
    exports.copy = copy;
    exports.version = version;
    exports.defer = defer;
}
,
/* request/lib/multipart */ function _(require, module, exports) {
    var uuid = require(370) /* uuid/v4 */;
    var CombinedStream = require(86) /* combined-stream */;
    var isstream = require(154) /* isstream */;
    var Buffer = require(311) /* safe-buffer */.Buffer;
    function Multipart(request) {
        this.request = request;
        this.boundary = uuid();
        this.chunked = false;
        this.body = null;
    }
    Multipart.prototype.isChunked = function (options) {
        var self = this;
        var chunked = false;
        var parts = options.data || options;
        if (!parts.forEach) {
            self.request.emit('error', new Error('Argument error, options.multipart.'));
        }
        if (options.chunked !== undefined) {
            chunked = options.chunked;
        }
        if (self.request.getHeader('transfer-encoding') === 'chunked') {
            chunked = true;
        }
        if (!chunked) {
            parts.forEach(function (part) {
                if (typeof part.body === 'undefined') {
                    self.request.emit('error', new Error('Body attribute missing in multipart.'));
                }
                if (isstream(part.body)) {
                    chunked = true;
                }
            });
        }
        return chunked;
    };
    Multipart.prototype.setHeaders = function (chunked) {
        var self = this;
        if (chunked && !self.request.hasHeader('transfer-encoding')) {
            self.request.setHeader('transfer-encoding', 'chunked');
        }
        var header = self.request.getHeader('content-type');
        if (!header || header.indexOf('multipart') === -1) {
            self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary);
        }
        else {
            if (header.indexOf('boundary') !== -1) {
                self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1');
            }
            else {
                self.request.setHeader('content-type', header + '; boundary=' + self.boundary);
            }
        }
    };
    Multipart.prototype.build = function (parts, chunked) {
        var self = this;
        var body = chunked ? new CombinedStream() : [];
        function add(part) {
            if (typeof part === 'number') {
                part = part.toString();
            }
            return chunked ? body.append(part) : body.push(Buffer.from(part));
        }
        if (self.request.preambleCRLF) {
            add('\r\n');
        }
        parts.forEach(function (part) {
            var preamble = '--' + self.boundary + '\r\n';
            Object.keys(part).forEach(function (key) {
                if (key === 'body') {
                    return;
                }
                preamble += key + ': ' + part[key] + '\r\n';
            });
            preamble += '\r\n';
            add(preamble);
            add(part.body);
            add('\r\n');
        });
        add('--' + self.boundary + '--');
        if (self.request.postambleCRLF) {
            add('\r\n');
        }
        return body;
    };
    Multipart.prototype.onRequest = function (options) {
        var self = this;
        var chunked = self.isChunked(options);
        var parts = options.data || options;
        self.setHeaders(chunked);
        self.chunked = chunked;
        self.body = self.build(parts, chunked);
    };
    exports.Multipart = Multipart;
}
,
/* request/lib/oauth */ function _(require, module, exports) {
    var url = require('url');
    var qs = require(290) /* qs */;
    var caseless = require(70) /* caseless */;
    var uuid = require(370) /* uuid/v4 */;
    var oauth = require(270) /* oauth-sign */;
    var crypto = require('crypto');
    var Buffer = require(311) /* safe-buffer */.Buffer;
    function OAuth(request) {
        this.request = request;
        this.params = null;
    }
    OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
        var oa = {};
        for (var i in _oauth) {
            oa['oauth_' + i] = _oauth[i];
        }
        if (!oa.oauth_version) {
            oa.oauth_version = '1.0';
        }
        if (!oa.oauth_timestamp) {
            oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString();
        }
        if (!oa.oauth_nonce) {
            oa.oauth_nonce = uuid().replace(/-/g, '');
        }
        if (!oa.oauth_signature_method) {
            oa.oauth_signature_method = 'HMAC-SHA1';
        }
        var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key; // eslint-disable-line camelcase
        delete oa.oauth_consumer_secret;
        delete oa.oauth_private_key;
        var token_secret = oa.oauth_token_secret; // eslint-disable-line camelcase
        delete oa.oauth_token_secret;
        var realm = oa.oauth_realm;
        delete oa.oauth_realm;
        delete oa.oauth_transport_method;
        var baseurl = uri.protocol + '//' + uri.host + uri.pathname;
        var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'));
        oa.oauth_signature = oauth.sign(oa.oauth_signature_method, method, baseurl, params, consumer_secret_or_private_key, // eslint-disable-line camelcase
        token_secret // eslint-disable-line camelcase
        );
        if (realm) {
            oa.realm = realm;
        }
        return oa;
    };
    OAuth.prototype.buildBodyHash = function (_oauth, body) {
        if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
            this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
                ' signature_method not supported with body_hash signing.'));
        }
        var shasum = crypto.createHash('sha1');
        shasum.update(body || '');
        var sha1 = shasum.digest('hex');
        return Buffer.from(sha1, 'hex').toString('base64');
    };
    OAuth.prototype.concatParams = function (oa, sep, wrap) {
        wrap = wrap || '';
        var params = Object.keys(oa).filter(function (i) {
            return i !== 'realm' && i !== 'oauth_signature';
        }).sort();
        if (oa.realm) {
            params.splice(0, 0, 'realm');
        }
        params.push('oauth_signature');
        return params.map(function (i) {
            return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap;
        }).join(sep);
    };
    OAuth.prototype.onRequest = function (_oauth) {
        var self = this;
        self.params = _oauth;
        var uri = self.request.uri || {};
        var method = self.request.method || '';
        var headers = caseless(self.request.headers);
        var body = self.request.body || '';
        var qsLib = self.request.qsLib || qs;
        var form;
        var query;
        var contentType = headers.get('content-type') || '';
        var formContentType = 'application/x-www-form-urlencoded';
        var transport = _oauth.transport_method || 'header';
        if (contentType.slice(0, formContentType.length) === formContentType) {
            contentType = formContentType;
            form = body;
        }
        if (uri.query) {
            query = uri.query;
        }
        if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
            self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
                'and content-type ' + formContentType));
        }
        if (!form && typeof _oauth.body_hash === 'boolean') {
            _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString());
        }
        var oa = self.buildParams(_oauth, uri, method, query, form, qsLib);
        switch (transport) {
            case 'header':
                self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'));
                break;
            case 'query':
                var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&');
                self.request.uri = url.parse(href);
                self.request.path = self.request.uri.path;
                break;
            case 'body':
                self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&');
                break;
            default:
                self.request.emit('error', new Error('oauth: transport_method invalid'));
        }
    };
    exports.OAuth = OAuth;
}
,
/* request/lib/querystring */ function _(require, module, exports) {
    var qs = require(290) /* qs */;
    var querystring = require('querystring');
    function Querystring(request) {
        this.request = request;
        this.lib = null;
        this.useQuerystring = null;
        this.parseOptions = null;
        this.stringifyOptions = null;
    }
    Querystring.prototype.init = function (options) {
        if (this.lib) {
            return;
        }
        this.useQuerystring = options.useQuerystring;
        this.lib = (this.useQuerystring ? querystring : qs);
        this.parseOptions = options.qsParseOptions || {};
        this.stringifyOptions = options.qsStringifyOptions || {};
    };
    Querystring.prototype.stringify = function (obj) {
        return (this.useQuerystring)
            ? this.rfc3986(this.lib.stringify(obj, this.stringifyOptions.sep || null, this.stringifyOptions.eq || null, this.stringifyOptions))
            : this.lib.stringify(obj, this.stringifyOptions);
    };
    Querystring.prototype.parse = function (str) {
        return (this.useQuerystring)
            ? this.lib.parse(str, this.parseOptions.sep || null, this.parseOptions.eq || null, this.parseOptions)
            : this.lib.parse(str, this.parseOptions);
    };
    Querystring.prototype.rfc3986 = function (str) {
        return str.replace(/[!'()*]/g, function (c) {
            return '%' + c.charCodeAt(0).toString(16).toUpperCase();
        });
    };
    Querystring.prototype.unescape = querystring.unescape;
    exports.Querystring = Querystring;
}
,
/* request/lib/redirect */ function _(require, module, exports) {
    var url = require('url');
    var isUrl = /^https?:/;
    function Redirect(request) {
        this.request = request;
        this.followRedirect = true;
        this.followRedirects = true;
        this.followAllRedirects = false;
        this.followOriginalHttpMethod = false;
        this.allowRedirect = function () { return true; };
        this.maxRedirects = 10;
        this.redirects = [];
        this.redirectsFollowed = 0;
        this.removeRefererHeader = false;
    }
    Redirect.prototype.onRequest = function (options) {
        var self = this;
        if (options.maxRedirects !== undefined) {
            self.maxRedirects = options.maxRedirects;
        }
        if (typeof options.followRedirect === 'function') {
            self.allowRedirect = options.followRedirect;
        }
        if (options.followRedirect !== undefined) {
            self.followRedirects = !!options.followRedirect;
        }
        if (options.followAllRedirects !== undefined) {
            self.followAllRedirects = options.followAllRedirects;
        }
        if (self.followRedirects || self.followAllRedirects) {
            self.redirects = self.redirects || [];
        }
        if (options.removeRefererHeader !== undefined) {
            self.removeRefererHeader = options.removeRefererHeader;
        }
        if (options.followOriginalHttpMethod !== undefined) {
            self.followOriginalHttpMethod = options.followOriginalHttpMethod;
        }
    };
    Redirect.prototype.redirectTo = function (response) {
        var self = this;
        var request = self.request;
        var redirectTo = null;
        if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
            var location = response.caseless.get('location');
            request.debug('redirect', location);
            if (self.followAllRedirects) {
                redirectTo = location;
            }
            else if (self.followRedirects) {
                switch (request.method) {
                    case 'PATCH':
                    case 'PUT':
                    case 'POST':
                    case 'DELETE':
                        // Do not follow redirects
                        break;
                    default:
                        redirectTo = location;
                        break;
                }
            }
        }
        else if (response.statusCode === 401) {
            var authHeader = request._auth.onResponse(response);
            if (authHeader) {
                request.setHeader('authorization', authHeader);
                redirectTo = request.uri;
            }
        }
        return redirectTo;
    };
    Redirect.prototype.onResponse = function (response) {
        var self = this;
        var request = self.request;
        var redirectTo = self.redirectTo(response);
        if (!redirectTo || !self.allowRedirect.call(request, response)) {
            return false;
        }
        request.debug('redirect to', redirectTo);
        // ignore any potential response body.  it cannot possibly be useful
        // to us at this point.
        // response.resume should be defined, but check anyway before calling. Workaround for browserify.
        if (response.resume) {
            response.resume();
        }
        if (self.redirectsFollowed >= self.maxRedirects) {
            request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href));
            return false;
        }
        self.redirectsFollowed += 1;
        if (!isUrl.test(redirectTo)) {
            redirectTo = url.resolve(request.uri.href, redirectTo);
        }
        var uriPrev = request.uri;
        request.uri = url.parse(redirectTo);
        // handle the case where we change protocol from https to http or vice versa
        if (request.uri.protocol !== uriPrev.protocol) {
            delete request.agent;
        }
        self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo });
        if (self.followAllRedirects && request.method !== 'HEAD' &&
            response.statusCode !== 401 && response.statusCode !== 307) {
            request.method = self.followOriginalHttpMethod ? request.method : 'GET';
        }
        // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
        delete request.src;
        delete request.req;
        delete request._started;
        if (response.statusCode !== 401 && response.statusCode !== 307) {
            // Remove parameters from the previous response, unless this is the second request
            // for a server that requires digest authentication.
            delete request.body;
            delete request._form;
            if (request.headers) {
                request.removeHeader('host');
                request.removeHeader('content-type');
                request.removeHeader('content-length');
                if (request.uri.hostname !== request.originalHost.split(':')[0]) {
                    // Remove authorization if changing hostnames (but not if just
                    // changing ports or protocols).  This matches the behavior of curl:
                    // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
                    request.removeHeader('authorization');
                }
            }
        }
        if (!self.removeRefererHeader) {
            request.setHeader('referer', uriPrev.href);
        }
        request.emit('redirect');
        request.init();
        return true;
    };
    exports.Redirect = Redirect;
}
,
/* request/lib/tunnel */ function _(require, module, exports) {
    var url = require('url');
    var tunnel = require(365) /* tunnel-agent */;
    var defaultProxyHeaderWhiteList = [
        'accept',
        'accept-charset',
        'accept-encoding',
        'accept-language',
        'accept-ranges',
        'cache-control',
        'content-encoding',
        'content-language',
        'content-location',
        'content-md5',
        'content-range',
        'content-type',
        'connection',
        'date',
        'expect',
        'max-forwards',
        'pragma',
        'referer',
        'te',
        'user-agent',
        'via'
    ];
    var defaultProxyHeaderExclusiveList = [
        'proxy-authorization'
    ];
    function constructProxyHost(uriObject) {
        var port = uriObject.port;
        var protocol = uriObject.protocol;
        var proxyHost = uriObject.hostname + ':';
        if (port) {
            proxyHost += port;
        }
        else if (protocol === 'https:') {
            proxyHost += '443';
        }
        else {
            proxyHost += '80';
        }
        return proxyHost;
    }
    function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
        var whiteList = proxyHeaderWhiteList
            .reduce(function (set, header) {
            set[header.toLowerCase()] = true;
            return set;
        }, {});
        return Object.keys(headers)
            .filter(function (header) {
            return whiteList[header.toLowerCase()];
        })
            .reduce(function (set, header) {
            set[header] = headers[header];
            return set;
        }, {});
    }
    function constructTunnelOptions(request, proxyHeaders) {
        var proxy = request.proxy;
        var tunnelOptions = {
            proxy: {
                host: proxy.hostname,
                port: +proxy.port,
                proxyAuth: proxy.auth,
                headers: proxyHeaders
            },
            headers: request.headers,
            ca: request.ca,
            cert: request.cert,
            key: request.key,
            passphrase: request.passphrase,
            pfx: request.pfx,
            ciphers: request.ciphers,
            rejectUnauthorized: request.rejectUnauthorized,
            secureOptions: request.secureOptions,
            secureProtocol: request.secureProtocol
        };
        return tunnelOptions;
    }
    function constructTunnelFnName(uri, proxy) {
        var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http');
        var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http');
        return [uriProtocol, proxyProtocol].join('Over');
    }
    function getTunnelFn(request) {
        var uri = request.uri;
        var proxy = request.proxy;
        var tunnelFnName = constructTunnelFnName(uri, proxy);
        return tunnel[tunnelFnName];
    }
    function Tunnel(request) {
        this.request = request;
        this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList;
        this.proxyHeaderExclusiveList = [];
        if (typeof request.tunnel !== 'undefined') {
            this.tunnelOverride = request.tunnel;
        }
    }
    Tunnel.prototype.isEnabled = function () {
        var self = this;
        var request = self.request;
        // Tunnel HTTPS by default. Allow the user to override this setting.
        // If self.tunnelOverride is set (the user specified a value), use it.
        if (typeof self.tunnelOverride !== 'undefined') {
            return self.tunnelOverride;
        }
        // If the destination is HTTPS, tunnel.
        if (request.uri.protocol === 'https:') {
            return true;
        }
        // Otherwise, do not use tunnel.
        return false;
    };
    Tunnel.prototype.setup = function (options) {
        var self = this;
        var request = self.request;
        options = options || {};
        if (typeof request.proxy === 'string') {
            request.proxy = url.parse(request.proxy);
        }
        if (!request.proxy || !request.tunnel) {
            return false;
        }
        // Setup Proxy Header Exclusive List and White List
        if (options.proxyHeaderWhiteList) {
            self.proxyHeaderWhiteList = options.proxyHeaderWhiteList;
        }
        if (options.proxyHeaderExclusiveList) {
            self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList;
        }
        var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList);
        var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList);
        // Setup Proxy Headers and Proxy Headers Host
        // Only send the Proxy White Listed Header names
        var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList);
        proxyHeaders.host = constructProxyHost(request.uri);
        proxyHeaderExclusiveList.forEach(request.removeHeader, request);
        // Set Agent from Tunnel Data
        var tunnelFn = getTunnelFn(request);
        var tunnelOptions = constructTunnelOptions(request, proxyHeaders);
        request.agent = tunnelFn(tunnelOptions);
        return true;
    };
    Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList;
    Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList;
    exports.Tunnel = Tunnel;
}
,
/* request/request */ function _(require, module, exports) {
    var http = require('http');
    var https = require('https');
    var url = require('url');
    var util = require('util');
    var stream = require('stream');
    var zlib = require('zlib');
    var aws2 = require(64) /* aws-sign2 */;
    var aws4 = require(65) /* aws4 */;
    var httpSignature = require(138) /* http-signature */;
    var mime = require(265) /* mime-types */;
    var caseless = require(70) /* caseless */;
    var ForeverAgent = require(111) /* forever-agent */;
    var FormData = require(112) /* form-data */;
    var extend = require(106) /* extend */;
    var isstream = require(154) /* isstream */;
    var isTypedArray = require(150) /* is-typedarray */.strict;
    var helpers = require(301) /* ./lib/helpers */;
    var cookies = require(297) /* ./lib/cookies */;
    var getProxyFromURI = require(298) /* ./lib/getProxyFromURI */;
    var Querystring = require(304) /* ./lib/querystring */.Querystring;
    var Har = require(299) /* ./lib/har */.Har;
    var Auth = require(296) /* ./lib/auth */.Auth;
    var OAuth = require(303) /* ./lib/oauth */.OAuth;
    var hawk = require(300) /* ./lib/hawk */;
    var Multipart = require(302) /* ./lib/multipart */.Multipart;
    var Redirect = require(305) /* ./lib/redirect */.Redirect;
    var Tunnel = require(306) /* ./lib/tunnel */.Tunnel;
    var now = require(278) /* performance-now */;
    var Buffer = require(311) /* safe-buffer */.Buffer;
    var safeStringify = helpers.safeStringify;
    var isReadStream = helpers.isReadStream;
    var toBase64 = helpers.toBase64;
    var defer = helpers.defer;
    var copy = helpers.copy;
    var version = helpers.version;
    var globalCookieJar = cookies.jar();
    var globalPool = {};
    function filterForNonReserved(reserved, options) {
        // Filter out properties that are not reserved.
        // Reserved values are passed in at call site.
        var object = {};
        for (var i in options) {
            var notReserved = (reserved.indexOf(i) === -1);
            if (notReserved) {
                object[i] = options[i];
            }
        }
        return object;
    }
    function filterOutReservedFunctions(reserved, options) {
        // Filter out properties that are functions and are reserved.
        // Reserved values are passed in at call site.
        var object = {};
        for (var i in options) {
            var isReserved = !(reserved.indexOf(i) === -1);
            var isFunction = (typeof options[i] === 'function');
            if (!(isReserved && isFunction)) {
                object[i] = options[i];
            }
        }
        return object;
    }
    // Return a simpler request object to allow serialization
    function requestToJSON() {
        var self = this;
        return {
            uri: self.uri,
            method: self.method,
            headers: self.headers
        };
    }
    // Return a simpler response object to allow serialization
    function responseToJSON() {
        var self = this;
        return {
            statusCode: self.statusCode,
            body: self.body,
            headers: self.headers,
            request: requestToJSON.call(self.request)
        };
    }
    function Request(options) {
        // if given the method property in options, set property explicitMethod to true
        // extend the Request instance with any non-reserved properties
        // remove any reserved functions from the options object
        // set Request instance to be readable and writable
        // call init
        var self = this;
        // start with HAR, then override with additional options
        if (options.har) {
            self._har = new Har(self);
            options = self._har.options(options);
        }
        stream.Stream.call(self);
        var reserved = Object.keys(Request.prototype);
        var nonReserved = filterForNonReserved(reserved, options);
        extend(self, nonReserved);
        options = filterOutReservedFunctions(reserved, options);
        self.readable = true;
        self.writable = true;
        if (options.method) {
            self.explicitMethod = true;
        }
        self._qs = new Querystring(self);
        self._auth = new Auth(self);
        self._oauth = new OAuth(self);
        self._multipart = new Multipart(self);
        self._redirect = new Redirect(self);
        self._tunnel = new Tunnel(self);
        self.init(options);
    }
    util.inherits(Request, stream.Stream);
    // Debugging
    Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG);
    function debug() {
        if (Request.debug) {
            console.error('REQUEST %s', util.format.apply(util, arguments));
        }
    }
    Request.prototype.debug = debug;
    Request.prototype.init = function (options) {
        // init() contains all the code to setup the request object.
        // the actual outgoing request is not started until start() is called
        // this function is called from both the constructor and on redirect.
        var self = this;
        if (!options) {
            options = {};
        }
        self.headers = self.headers ? copy(self.headers) : {};
        // Delete headers with value undefined since they break
        // ClientRequest.OutgoingMessage.setHeader in node 0.12
        for (var headerName in self.headers) {
            if (typeof self.headers[headerName] === 'undefined') {
                delete self.headers[headerName];
            }
        }
        caseless.httpify(self, self.headers);
        if (!self.method) {
            self.method = options.method || 'GET';
        }
        if (!self.localAddress) {
            self.localAddress = options.localAddress;
        }
        self._qs.init(options);
        debug(options);
        if (!self.pool && self.pool !== false) {
            self.pool = globalPool;
        }
        self.dests = self.dests || [];
        self.__isRequestRequest = true;
        // Protect against double callback
        if (!self._callback && self.callback) {
            self._callback = self.callback;
            self.callback = function () {
                if (self._callbackCalled) {
                    return; // Print a warning maybe?
                }
                self._callbackCalled = true;
                self._callback.apply(self, arguments);
            };
            self.on('error', self.callback.bind());
            self.on('complete', self.callback.bind(self, null));
        }
        // People use this property instead all the time, so support it
        if (!self.uri && self.url) {
            self.uri = self.url;
            delete self.url;
        }
        // If there's a baseUrl, then use it as the base URL (i.e. uri must be
        // specified as a relative path and is appended to baseUrl).
        if (self.baseUrl) {
            if (typeof self.baseUrl !== 'string') {
                return self.emit('error', new Error('options.baseUrl must be a string'));
            }
            if (typeof self.uri !== 'string') {
                return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'));
            }
            if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
                return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'));
            }
            // Handle all cases to make sure that there's only one slash between
            // baseUrl and uri.
            var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1;
            var uriStartsWithSlash = self.uri.indexOf('/') === 0;
            if (baseUrlEndsWithSlash && uriStartsWithSlash) {
                self.uri = self.baseUrl + self.uri.slice(1);
            }
            else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
                self.uri = self.baseUrl + self.uri;
            }
            else if (self.uri === '') {
                self.uri = self.baseUrl;
            }
            else {
                self.uri = self.baseUrl + '/' + self.uri;
            }
            delete self.baseUrl;
        }
        // A URI is needed by this point, emit error if we haven't been able to get one
        if (!self.uri) {
            return self.emit('error', new Error('options.uri is a required argument'));
        }
        // If a string URI/URL was given, parse it into a URL object
        if (typeof self.uri === 'string') {
            self.uri = url.parse(self.uri);
        }
        // Some URL objects are not from a URL parsed string and need href added
        if (!self.uri.href) {
            self.uri.href = url.format(self.uri);
        }
        // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
        if (self.uri.protocol === 'unix:') {
            return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'));
        }
        // Support Unix Sockets
        if (self.uri.host === 'unix') {
            self.enableUnixSocket();
        }
        if (self.strictSSL === false) {
            self.rejectUnauthorized = false;
        }
        if (!self.uri.pathname) {
            self.uri.pathname = '/';
        }
        if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
            // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
            // Detect and reject it as soon as possible
            var faultyUri = url.format(self.uri);
            var message = 'Invalid URI "' + faultyUri + '"';
            if (Object.keys(options).length === 0) {
                // No option ? This can be the sign of a redirect
                // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
                // they should be warned that it can be caused by a redirection (can save some hair)
                message += '. This can be caused by a crappy redirection.';
            }
            // This error was fatal
            self.abort();
            return self.emit('error', new Error(message));
        }
        if (!self.hasOwnProperty('proxy')) {
            self.proxy = getProxyFromURI(self.uri);
        }
        self.tunnel = self._tunnel.isEnabled();
        if (self.proxy) {
            self._tunnel.setup(options);
        }
        self._redirect.onRequest(options);
        self.setHost = false;
        if (!self.hasHeader('host')) {
            var hostHeaderName = self.originalHostHeaderName || 'host';
            self.setHeader(hostHeaderName, self.uri.host);
            // Drop :port suffix from Host header if known protocol.
            if (self.uri.port) {
                if ((self.uri.port === '80' && self.uri.protocol === 'http:') ||
                    (self.uri.port === '443' && self.uri.protocol === 'https:')) {
                    self.setHeader(hostHeaderName, self.uri.hostname);
                }
            }
            self.setHost = true;
        }
        self.jar(self._jar || options.jar);
        if (!self.uri.port) {
            if (self.uri.protocol === 'http:') {
                self.uri.port = 80;
            }
            else if (self.uri.protocol === 'https:') {
                self.uri.port = 443;
            }
        }
        if (self.proxy && !self.tunnel) {
            self.port = self.proxy.port;
            self.host = self.proxy.hostname;
        }
        else {
            self.port = self.uri.port;
            self.host = self.uri.hostname;
        }
        if (options.form) {
            self.form(options.form);
        }
        if (options.formData) {
            var formData = options.formData;
            var requestForm = self.form();
            var appendFormValue = function (key, value) {
                if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
                    requestForm.append(key, value.value, value.options);
                }
                else {
                    requestForm.append(key, value);
                }
            };
            for (var formKey in formData) {
                if (formData.hasOwnProperty(formKey)) {
                    var formValue = formData[formKey];
                    if (formValue instanceof Array) {
                        for (var j = 0; j < formValue.length; j++) {
                            appendFormValue(formKey, formValue[j]);
                        }
                    }
                    else {
                        appendFormValue(formKey, formValue);
                    }
                }
            }
        }
        if (options.qs) {
            self.qs(options.qs);
        }
        if (self.uri.path) {
            self.path = self.uri.path;
        }
        else {
            self.path = self.uri.pathname + (self.uri.search || '');
        }
        if (self.path.length === 0) {
            self.path = '/';
        }
        // Auth must happen last in case signing is dependent on other headers
        if (options.aws) {
            self.aws(options.aws);
        }
        if (options.hawk) {
            self.hawk(options.hawk);
        }
        if (options.httpSignature) {
            self.httpSignature(options.httpSignature);
        }
        if (options.auth) {
            if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
                options.auth.user = options.auth.username;
            }
            if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
                options.auth.pass = options.auth.password;
            }
            self.auth(options.auth.user, options.auth.pass, options.auth.sendImmediately, options.auth.bearer);
        }
        if (self.gzip && !self.hasHeader('accept-encoding')) {
            self.setHeader('accept-encoding', 'gzip, deflate');
        }
        if (self.uri.auth && !self.hasHeader('authorization')) {
            var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item); });
            self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true);
        }
        if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
            var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item); });
            var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'));
            self.setHeader('proxy-authorization', authHeader);
        }
        if (self.proxy && !self.tunnel) {
            self.path = (self.uri.protocol + '//' + self.uri.host + self.path);
        }
        if (options.json) {
            self.json(options.json);
        }
        if (options.multipart) {
            self.multipart(options.multipart);
        }
        if (options.time) {
            self.timing = true;
            // NOTE: elapsedTime is deprecated in favor of .timings
            self.elapsedTime = self.elapsedTime || 0;
        }
        function setContentLength() {
            if (isTypedArray(self.body)) {
                self.body = Buffer.from(self.body);
            }
            if (!self.hasHeader('content-length')) {
                var length;
                if (typeof self.body === 'string') {
                    length = Buffer.byteLength(self.body);
                }
                else if (Array.isArray(self.body)) {
                    length = self.body.reduce(function (a, b) { return a + b.length; }, 0);
                }
                else {
                    length = self.body.length;
                }
                if (length) {
                    self.setHeader('content-length', length);
                }
                else {
                    self.emit('error', new Error('Argument error, options.body.'));
                }
            }
        }
        if (self.body && !isstream(self.body)) {
            setContentLength();
        }
        if (options.oauth) {
            self.oauth(options.oauth);
        }
        else if (self._oauth.params && self.hasHeader('authorization')) {
            self.oauth(self._oauth.params);
        }
        var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol;
        var defaultModules = { 'http:': http, 'https:': https };
        var httpModules = self.httpModules || {};
        self.httpModule = httpModules[protocol] || defaultModules[protocol];
        if (!self.httpModule) {
            return self.emit('error', new Error('Invalid protocol: ' + protocol));
        }
        if (options.ca) {
            self.ca = options.ca;
        }
        if (!self.agent) {
            if (options.agentOptions) {
                self.agentOptions = options.agentOptions;
            }
            if (options.agentClass) {
                self.agentClass = options.agentClass;
            }
            else if (options.forever) {
                var v = version();
                // use ForeverAgent in node 0.10- only
                if (v.major === 0 && v.minor <= 10) {
                    self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL;
                }
                else {
                    self.agentClass = self.httpModule.Agent;
                    self.agentOptions = self.agentOptions || {};
                    self.agentOptions.keepAlive = true;
                }
            }
            else {
                self.agentClass = self.httpModule.Agent;
            }
        }
        if (self.pool === false) {
            self.agent = false;
        }
        else {
            self.agent = self.agent || self.getNewAgent();
        }
        self.on('pipe', function (src) {
            if (self.ntick && self._started) {
                self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'));
            }
            self.src = src;
            if (isReadStream(src)) {
                if (!self.hasHeader('content-type')) {
                    self.setHeader('content-type', mime.lookup(src.path));
                }
            }
            else {
                if (src.headers) {
                    for (var i in src.headers) {
                        if (!self.hasHeader(i)) {
                            self.setHeader(i, src.headers[i]);
                        }
                    }
                }
                if (self._json && !self.hasHeader('content-type')) {
                    self.setHeader('content-type', 'application/json');
                }
                if (src.method && !self.explicitMethod) {
                    self.method = src.method;
                }
            }
            // self.on('pipe', function () {
            //   console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
            // })
        });
        defer(function () {
            if (self._aborted) {
                return;
            }
            var end = function () {
                if (self._form) {
                    if (!self._auth.hasAuth) {
                        self._form.pipe(self);
                    }
                    else if (self._auth.hasAuth && self._auth.sentAuth) {
                        self._form.pipe(self);
                    }
                }
                if (self._multipart && self._multipart.chunked) {
                    self._multipart.body.pipe(self);
                }
                if (self.body) {
                    if (isstream(self.body)) {
                        self.body.pipe(self);
                    }
                    else {
                        setContentLength();
                        if (Array.isArray(self.body)) {
                            self.body.forEach(function (part) {
                                self.write(part);
                            });
                        }
                        else {
                            self.write(self.body);
                        }
                        self.end();
                    }
                }
                else if (self.requestBodyStream) {
                    console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.');
                    self.requestBodyStream.pipe(self);
                }
                else if (!self.src) {
                    if (self._auth.hasAuth && !self._auth.sentAuth) {
                        self.end();
                        return;
                    }
                    if (self.method !== 'GET' && typeof self.method !== 'undefined') {
                        self.setHeader('content-length', 0);
                    }
                    self.end();
                }
            };
            if (self._form && !self.hasHeader('content-length')) {
                // Before ending the request, we had to compute the length of the whole form, asyncly
                self.setHeader(self._form.getHeaders(), true);
                self._form.getLength(function (err, length) {
                    if (!err && !isNaN(length)) {
                        self.setHeader('content-length', length);
                    }
                    end();
                });
            }
            else {
                end();
            }
            self.ntick = true;
        });
    };
    Request.prototype.getNewAgent = function () {
        var self = this;
        var Agent = self.agentClass;
        var options = {};
        if (self.agentOptions) {
            for (var i in self.agentOptions) {
                options[i] = self.agentOptions[i];
            }
        }
        if (self.ca) {
            options.ca = self.ca;
        }
        if (self.ciphers) {
            options.ciphers = self.ciphers;
        }
        if (self.secureProtocol) {
            options.secureProtocol = self.secureProtocol;
        }
        if (self.secureOptions) {
            options.secureOptions = self.secureOptions;
        }
        if (typeof self.rejectUnauthorized !== 'undefined') {
            options.rejectUnauthorized = self.rejectUnauthorized;
        }
        if (self.cert && self.key) {
            options.key = self.key;
            options.cert = self.cert;
        }
        if (self.pfx) {
            options.pfx = self.pfx;
        }
        if (self.passphrase) {
            options.passphrase = self.passphrase;
        }
        var poolKey = '';
        // different types of agents are in different pools
        if (Agent !== self.httpModule.Agent) {
            poolKey += Agent.name;
        }
        // ca option is only relevant if proxy or destination are https
        var proxy = self.proxy;
        if (typeof proxy === 'string') {
            proxy = url.parse(proxy);
        }
        var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:';
        if (isHttps) {
            if (options.ca) {
                if (poolKey) {
                    poolKey += ':';
                }
                poolKey += options.ca;
            }
            if (typeof options.rejectUnauthorized !== 'undefined') {
                if (poolKey) {
                    poolKey += ':';
                }
                poolKey += options.rejectUnauthorized;
            }
            if (options.cert) {
                if (poolKey) {
                    poolKey += ':';
                }
                poolKey += options.cert.toString('ascii') + options.key.toString('ascii');
            }
            if (options.pfx) {
                if (poolKey) {
                    poolKey += ':';
                }
                poolKey += options.pfx.toString('ascii');
            }
            if (options.ciphers) {
                if (poolKey) {
                    poolKey += ':';
                }
                poolKey += options.ciphers;
            }
            if (options.secureProtocol) {
                if (poolKey) {
                    poolKey += ':';
                }
                poolKey += options.secureProtocol;
            }
            if (options.secureOptions) {
                if (poolKey) {
                    poolKey += ':';
                }
                poolKey += options.secureOptions;
            }
        }
        if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
            // not doing anything special.  Use the globalAgent
            return self.httpModule.globalAgent;
        }
        // we're using a stored agent.  Make sure it's protocol-specific
        poolKey = self.uri.protocol + poolKey;
        // generate a new agent for this setting if none yet exists
        if (!self.pool[poolKey]) {
            self.pool[poolKey] = new Agent(options);
            // properly set maxSockets on new agents
            if (self.pool.maxSockets) {
                self.pool[poolKey].maxSockets = self.pool.maxSockets;
            }
        }
        return self.pool[poolKey];
    };
    Request.prototype.start = function () {
        // start() is called once we are ready to send the outgoing HTTP request.
        // this is usually called on the first write(), end() or on nextTick()
        var self = this;
        if (self.timing) {
            // All timings will be relative to this request's startTime.  In order to do this,
            // we need to capture the wall-clock start time (via Date), immediately followed
            // by the high-resolution timer (via now()).  While these two won't be set
            // at the _exact_ same time, they should be close enough to be able to calculate
            // high-resolution, monotonically non-decreasing timestamps relative to startTime.
            var startTime = new Date().getTime();
            var startTimeNow = now();
        }
        if (self._aborted) {
            return;
        }
        self._started = true;
        self.method = self.method || 'GET';
        self.href = self.uri.href;
        if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
            self.setHeader('content-length', self.src.stat.size);
        }
        if (self._aws) {
            self.aws(self._aws, true);
        }
        // We have a method named auth, which is completely different from the http.request
        // auth option.  If we don't remove it, we're gonna have a bad time.
        var reqOptions = copy(self);
        delete reqOptions.auth;
        debug('make request', self.uri.href);
        // node v6.8.0 now supports a `timeout` value in `http.request()`, but we
        // should delete it for now since we handle timeouts manually for better
        // consistency with node versions before v6.8.0
        delete reqOptions.timeout;
        try {
            self.req = self.httpModule.request(reqOptions);
        }
        catch (err) {
            self.emit('error', err);
            return;
        }
        if (self.timing) {
            self.startTime = startTime;
            self.startTimeNow = startTimeNow;
            // Timing values will all be relative to startTime (by comparing to startTimeNow
            // so we have an accurate clock)
            self.timings = {};
        }
        var timeout;
        if (self.timeout && !self.timeoutTimer) {
            if (self.timeout < 0) {
                timeout = 0;
            }
            else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
                timeout = self.timeout;
            }
        }
        self.req.on('response', self.onRequestResponse.bind(self));
        self.req.on('error', self.onRequestError.bind(self));
        self.req.on('drain', function () {
            self.emit('drain');
        });
        self.req.on('socket', function (socket) {
            // `._connecting` was the old property which was made public in node v6.1.0
            var isConnecting = socket._connecting || socket.connecting;
            if (self.timing) {
                self.timings.socket = now() - self.startTimeNow;
                if (isConnecting) {
                    var onLookupTiming = function () {
                        self.timings.lookup = now() - self.startTimeNow;
                    };
                    var onConnectTiming = function () {
                        self.timings.connect = now() - self.startTimeNow;
                    };
                    socket.once('lookup', onLookupTiming);
                    socket.once('connect', onConnectTiming);
                    // clean up timing event listeners if needed on error
                    self.req.once('error', function () {
                        socket.removeListener('lookup', onLookupTiming);
                        socket.removeListener('connect', onConnectTiming);
                    });
                }
            }
            var setReqTimeout = function () {
                // This timeout sets the amount of time to wait *between* bytes sent
                // from the server once connected.
                //
                // In particular, it's useful for erroring if the server fails to send
                // data halfway through streaming a response.
                self.req.setTimeout(timeout, function () {
                    if (self.req) {
                        self.abort();
                        var e = new Error('ESOCKETTIMEDOUT');
                        e.code = 'ESOCKETTIMEDOUT';
                        e.connect = false;
                        self.emit('error', e);
                    }
                });
            };
            if (timeout !== undefined) {
                // Only start the connection timer if we're actually connecting a new
                // socket, otherwise if we're already connected (because this is a
                // keep-alive connection) do not bother. This is important since we won't
                // get a 'connect' event for an already connected socket.
                if (isConnecting) {
                    var onReqSockConnect = function () {
                        socket.removeListener('connect', onReqSockConnect);
                        clearTimeout(self.timeoutTimer);
                        self.timeoutTimer = null;
                        setReqTimeout();
                    };
                    socket.on('connect', onReqSockConnect);
                    self.req.on('error', function (err) {
                        socket.removeListener('connect', onReqSockConnect);
                    });
                    // Set a timeout in memory - this block will throw if the server takes more
                    // than `timeout` to write the HTTP status and headers (corresponding to
                    // the on('response') event on the client). NB: this measures wall-clock
                    // time, not the time between bytes sent by the server.
                    self.timeoutTimer = setTimeout(function () {
                        socket.removeListener('connect', onReqSockConnect);
                        self.abort();
                        var e = new Error('ETIMEDOUT');
                        e.code = 'ETIMEDOUT';
                        e.connect = true;
                        self.emit('error', e);
                    }, timeout);
                }
                else {
                    // We're already connected
                    setReqTimeout();
                }
            }
            self.emit('socket', socket);
        });
        self.emit('request', self.req);
    };
    Request.prototype.onRequestError = function (error) {
        var self = this;
        if (self._aborted) {
            return;
        }
        if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
            self.agent.addRequestNoreuse) {
            self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) };
            self.start();
            self.req.end();
            return;
        }
        if (self.timeout && self.timeoutTimer) {
            clearTimeout(self.timeoutTimer);
            self.timeoutTimer = null;
        }
        self.emit('error', error);
    };
    Request.prototype.onRequestResponse = function (response) {
        var self = this;
        if (self.timing) {
            self.timings.response = now() - self.startTimeNow;
        }
        debug('onRequestResponse', self.uri.href, response.statusCode, response.headers);
        response.on('end', function () {
            if (self.timing) {
                self.timings.end = now() - self.startTimeNow;
                response.timingStart = self.startTime;
                // fill in the blanks for any periods that didn't trigger, such as
                // no lookup or connect due to keep alive
                if (!self.timings.socket) {
                    self.timings.socket = 0;
                }
                if (!self.timings.lookup) {
                    self.timings.lookup = self.timings.socket;
                }
                if (!self.timings.connect) {
                    self.timings.connect = self.timings.lookup;
                }
                if (!self.timings.response) {
                    self.timings.response = self.timings.connect;
                }
                debug('elapsed time', self.timings.end);
                // elapsedTime includes all redirects
                self.elapsedTime += Math.round(self.timings.end);
                // NOTE: elapsedTime is deprecated in favor of .timings
                response.elapsedTime = self.elapsedTime;
                // timings is just for the final fetch
                response.timings = self.timings;
                // pre-calculate phase timings as well
                response.timingPhases = {
                    wait: self.timings.socket,
                    dns: self.timings.lookup - self.timings.socket,
                    tcp: self.timings.connect - self.timings.lookup,
                    firstByte: self.timings.response - self.timings.connect,
                    download: self.timings.end - self.timings.response,
                    total: self.timings.end
                };
            }
            debug('response end', self.uri.href, response.statusCode, response.headers);
        });
        if (self._aborted) {
            debug('aborted', self.uri.href);
            response.resume();
            return;
        }
        self.response = response;
        response.request = self;
        response.toJSON = responseToJSON;
        // XXX This is different on 0.10, because SSL is strict by default
        if (self.httpModule === https &&
            self.strictSSL && (!response.hasOwnProperty('socket') ||
            !response.socket.authorized)) {
            debug('strict ssl error', self.uri.href);
            var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL';
            self.emit('error', new Error('SSL Error: ' + sslErr));
            return;
        }
        // Save the original host before any redirect (if it changes, we need to
        // remove any authorization headers).  Also remember the case of the header
        // name because lots of broken servers expect Host instead of host and we
        // want the caller to be able to specify this.
        self.originalHost = self.getHeader('host');
        if (!self.originalHostHeaderName) {
            self.originalHostHeaderName = self.hasHeader('host');
        }
        if (self.setHost) {
            self.removeHeader('host');
        }
        if (self.timeout && self.timeoutTimer) {
            clearTimeout(self.timeoutTimer);
            self.timeoutTimer = null;
        }
        var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar;
        var addCookie = function (cookie) {
            // set the cookie if it's domain in the href's domain.
            try {
                targetCookieJar.setCookie(cookie, self.uri.href, { ignoreError: true });
            }
            catch (e) {
                self.emit('error', e);
            }
        };
        response.caseless = caseless(response.headers);
        if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
            var headerName = response.caseless.has('set-cookie');
            if (Array.isArray(response.headers[headerName])) {
                response.headers[headerName].forEach(addCookie);
            }
            else {
                addCookie(response.headers[headerName]);
            }
        }
        if (self._redirect.onResponse(response)) {
            return; // Ignore the rest of the response
        }
        else {
            // Be a good stream and emit end when the response is finished.
            // Hack to emit end on close because of a core bug that never fires end
            response.on('close', function () {
                if (!self._ended) {
                    self.response.emit('end');
                }
            });
            response.once('end', function () {
                self._ended = true;
            });
            var noBody = function (code) {
                return (self.method === 'HEAD' ||
                    // Informational
                    (code >= 100 && code < 200) ||
                    // No Content
                    code === 204 ||
                    // Not Modified
                    code === 304);
            };
            var responseContent;
            if (self.gzip && !noBody(response.statusCode)) {
                var contentEncoding = response.headers['content-encoding'] || 'identity';
                contentEncoding = contentEncoding.trim().toLowerCase();
                // Be more lenient with decoding compressed responses, since (very rarely)
                // servers send slightly invalid gzip responses that are still accepted
                // by common browsers.
                // Always using Z_SYNC_FLUSH is what cURL does.
                var zlibOptions = {
                    flush: zlib.Z_SYNC_FLUSH,
                    finishFlush: zlib.Z_SYNC_FLUSH
                };
                if (contentEncoding === 'gzip') {
                    responseContent = zlib.createGunzip(zlibOptions);
                    response.pipe(responseContent);
                }
                else if (contentEncoding === 'deflate') {
                    responseContent = zlib.createInflate(zlibOptions);
                    response.pipe(responseContent);
                }
                else {
                    // Since previous versions didn't check for Content-Encoding header,
                    // ignore any invalid values to preserve backwards-compatibility
                    if (contentEncoding !== 'identity') {
                        debug('ignoring unrecognized Content-Encoding ' + contentEncoding);
                    }
                    responseContent = response;
                }
            }
            else {
                responseContent = response;
            }
            if (self.encoding) {
                if (self.dests.length !== 0) {
                    console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.');
                }
                else {
                    responseContent.setEncoding(self.encoding);
                }
            }
            if (self._paused) {
                responseContent.pause();
            }
            self.responseContent = responseContent;
            self.emit('response', response);
            self.dests.forEach(function (dest) {
                self.pipeDest(dest);
            });
            responseContent.on('data', function (chunk) {
                if (self.timing && !self.responseStarted) {
                    self.responseStartTime = (new Date()).getTime();
                    // NOTE: responseStartTime is deprecated in favor of .timings
                    response.responseStartTime = self.responseStartTime;
                }
                self._destdata = true;
                self.emit('data', chunk);
            });
            responseContent.once('end', function (chunk) {
                self.emit('end', chunk);
            });
            responseContent.on('error', function (error) {
                self.emit('error', error);
            });
            responseContent.on('close', function () { self.emit('close'); });
            if (self.callback) {
                self.readResponseBody(response);
            }
            else { // if no callback
                self.on('end', function () {
                    if (self._aborted) {
                        debug('aborted', self.uri.href);
                        return;
                    }
                    self.emit('complete', response);
                });
            }
        }
        debug('finish init function', self.uri.href);
    };
    Request.prototype.readResponseBody = function (response) {
        var self = this;
        debug("reading response's body");
        var buffers = [];
        var bufferLength = 0;
        var strings = [];
        self.on('data', function (chunk) {
            if (!Buffer.isBuffer(chunk)) {
                strings.push(chunk);
            }
            else if (chunk.length) {
                bufferLength += chunk.length;
                buffers.push(chunk);
            }
        });
        self.on('end', function () {
            debug('end event', self.uri.href);
            if (self._aborted) {
                debug('aborted', self.uri.href);
                // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
                // This can lead to leaky behavior if the user retains a reference to the request object.
                buffers = [];
                bufferLength = 0;
                return;
            }
            if (bufferLength) {
                debug('has body', self.uri.href, bufferLength);
                response.body = Buffer.concat(buffers, bufferLength);
                if (self.encoding !== null) {
                    response.body = response.body.toString(self.encoding);
                }
                // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
                // This can lead to leaky behavior if the user retains a reference to the request object.
                buffers = [];
                bufferLength = 0;
            }
            else if (strings.length) {
                // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
                // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
                if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
                    strings[0] = strings[0].substring(1);
                }
                response.body = strings.join('');
            }
            if (self._json) {
                try {
                    response.body = JSON.parse(response.body, self._jsonReviver);
                }
                catch (e) {
                    debug('invalid JSON received', self.uri.href);
                }
            }
            debug('emitting complete', self.uri.href);
            if (typeof response.body === 'undefined' && !self._json) {
                response.body = self.encoding === null ? Buffer.alloc(0) : '';
            }
            self.emit('complete', response, response.body);
        });
    };
    Request.prototype.abort = function () {
        var self = this;
        self._aborted = true;
        if (self.req) {
            self.req.abort();
        }
        else if (self.response) {
            self.response.destroy();
        }
        self.emit('abort');
    };
    Request.prototype.pipeDest = function (dest) {
        var self = this;
        var response = self.response;
        // Called after the response is received
        if (dest.headers && !dest.headersSent) {
            if (response.caseless.has('content-type')) {
                var ctname = response.caseless.has('content-type');
                if (dest.setHeader) {
                    dest.setHeader(ctname, response.headers[ctname]);
                }
                else {
                    dest.headers[ctname] = response.headers[ctname];
                }
            }
            if (response.caseless.has('content-length')) {
                var clname = response.caseless.has('content-length');
                if (dest.setHeader) {
                    dest.setHeader(clname, response.headers[clname]);
                }
                else {
                    dest.headers[clname] = response.headers[clname];
                }
            }
        }
        if (dest.setHeader && !dest.headersSent) {
            for (var i in response.headers) {
                // If the response content is being decoded, the Content-Encoding header
                // of the response doesn't represent the piped content, so don't pass it.
                if (!self.gzip || i !== 'content-encoding') {
                    dest.setHeader(i, response.headers[i]);
                }
            }
            dest.statusCode = response.statusCode;
        }
        if (self.pipefilter) {
            self.pipefilter(response, dest);
        }
    };
    Request.prototype.qs = function (q, clobber) {
        var self = this;
        var base;
        if (!clobber && self.uri.query) {
            base = self._qs.parse(self.uri.query);
        }
        else {
            base = {};
        }
        for (var i in q) {
            base[i] = q[i];
        }
        var qs = self._qs.stringify(base);
        if (qs === '') {
            return self;
        }
        self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs);
        self.url = self.uri;
        self.path = self.uri.path;
        if (self.uri.host === 'unix') {
            self.enableUnixSocket();
        }
        return self;
    };
    Request.prototype.form = function (form) {
        var self = this;
        if (form) {
            if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
                self.setHeader('content-type', 'application/x-www-form-urlencoded');
            }
            self.body = (typeof form === 'string')
                ? self._qs.rfc3986(form.toString('utf8'))
                : self._qs.stringify(form).toString('utf8');
            return self;
        }
        // create form-data object
        self._form = new FormData();
        self._form.on('error', function (err) {
            err.message = 'form-data: ' + err.message;
            self.emit('error', err);
            self.abort();
        });
        return self._form;
    };
    Request.prototype.multipart = function (multipart) {
        var self = this;
        self._multipart.onRequest(multipart);
        if (!self._multipart.chunked) {
            self.body = self._multipart.body;
        }
        return self;
    };
    Request.prototype.json = function (val) {
        var self = this;
        if (!self.hasHeader('accept')) {
            self.setHeader('accept', 'application/json');
        }
        if (typeof self.jsonReplacer === 'function') {
            self._jsonReplacer = self.jsonReplacer;
        }
        self._json = true;
        if (typeof val === 'boolean') {
            if (self.body !== undefined) {
                if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
                    self.body = safeStringify(self.body, self._jsonReplacer);
                }
                else {
                    self.body = self._qs.rfc3986(self.body);
                }
                if (!self.hasHeader('content-type')) {
                    self.setHeader('content-type', 'application/json');
                }
            }
        }
        else {
            self.body = safeStringify(val, self._jsonReplacer);
            if (!self.hasHeader('content-type')) {
                self.setHeader('content-type', 'application/json');
            }
        }
        if (typeof self.jsonReviver === 'function') {
            self._jsonReviver = self.jsonReviver;
        }
        return self;
    };
    Request.prototype.getHeader = function (name, headers) {
        var self = this;
        var result, re, match;
        if (!headers) {
            headers = self.headers;
        }
        Object.keys(headers).forEach(function (key) {
            if (key.length !== name.length) {
                return;
            }
            re = new RegExp(name, 'i');
            match = key.match(re);
            if (match) {
                result = headers[key];
            }
        });
        return result;
    };
    Request.prototype.enableUnixSocket = function () {
        // Get the socket & request paths from the URL
        var unixParts = this.uri.path.split(':');
        var host = unixParts[0];
        var path = unixParts[1];
        // Apply unix properties to request
        this.socketPath = host;
        this.uri.pathname = path;
        this.uri.path = path;
        this.uri.host = host;
        this.uri.hostname = host;
        this.uri.isUnix = true;
    };
    Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
        var self = this;
        self._auth.onRequest(user, pass, sendImmediately, bearer);
        return self;
    };
    Request.prototype.aws = function (opts, now) {
        var self = this;
        if (!now) {
            self._aws = opts;
            return self;
        }
        if (opts.sign_version === 4 || opts.sign_version === '4') {
            // use aws4
            var options = {
                host: self.uri.host,
                path: self.uri.path,
                method: self.method,
                headers: self.headers,
                body: self.body
            };
            if (opts.service) {
                options.service = opts.service;
            }
            var signRes = aws4.sign(options, {
                accessKeyId: opts.key,
                secretAccessKey: opts.secret,
                sessionToken: opts.session
            });
            self.setHeader('authorization', signRes.headers.Authorization);
            self.setHeader('x-amz-date', signRes.headers['X-Amz-Date']);
            if (signRes.headers['X-Amz-Security-Token']) {
                self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token']);
            }
        }
        else {
            // default: use aws-sign2
            var date = new Date();
            self.setHeader('date', date.toUTCString());
            var auth = {
                key: opts.key,
                secret: opts.secret,
                verb: self.method.toUpperCase(),
                date: date,
                contentType: self.getHeader('content-type') || '',
                md5: self.getHeader('content-md5') || '',
                amazonHeaders: aws2.canonicalizeHeaders(self.headers)
            };
            var path = self.uri.path;
            if (opts.bucket && path) {
                auth.resource = '/' + opts.bucket + path;
            }
            else if (opts.bucket && !path) {
                auth.resource = '/' + opts.bucket;
            }
            else if (!opts.bucket && path) {
                auth.resource = path;
            }
            else if (!opts.bucket && !path) {
                auth.resource = '/';
            }
            auth.resource = aws2.canonicalizeResource(auth.resource);
            self.setHeader('authorization', aws2.authorization(auth));
        }
        return self;
    };
    Request.prototype.httpSignature = function (opts) {
        var self = this;
        httpSignature.signRequest({
            getHeader: function (header) {
                return self.getHeader(header, self.headers);
            },
            setHeader: function (header, value) {
                self.setHeader(header, value);
            },
            method: self.method,
            path: self.path
        }, opts);
        debug('httpSignature authorization', self.getHeader('authorization'));
        return self;
    };
    Request.prototype.hawk = function (opts) {
        var self = this;
        self.setHeader('Authorization', hawk.header(self.uri, self.method, opts));
    };
    Request.prototype.oauth = function (_oauth) {
        var self = this;
        self._oauth.onRequest(_oauth);
        return self;
    };
    Request.prototype.jar = function (jar) {
        var self = this;
        var cookies;
        if (self._redirect.redirectsFollowed === 0) {
            self.originalCookieHeader = self.getHeader('cookie');
        }
        if (!jar) {
            // disable cookies
            cookies = false;
            self._disableCookies = true;
        }
        else {
            var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar;
            var urihref = self.uri.href;
            // fetch cookie in the Specified host
            if (targetCookieJar) {
                cookies = targetCookieJar.getCookieString(urihref);
            }
        }
        // if need cookie and cookie is not empty
        if (cookies && cookies.length) {
            if (self.originalCookieHeader) {
                // Don't overwrite existing Cookie header
                self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies);
            }
            else {
                self.setHeader('cookie', cookies);
            }
        }
        self._jar = jar;
        return self;
    };
    // Stream API
    Request.prototype.pipe = function (dest, opts) {
        var self = this;
        if (self.response) {
            if (self._destdata) {
                self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'));
            }
            else if (self._ended) {
                self.emit('error', new Error('You cannot pipe after the response has been ended.'));
            }
            else {
                stream.Stream.prototype.pipe.call(self, dest, opts);
                self.pipeDest(dest);
                return dest;
            }
        }
        else {
            self.dests.push(dest);
            stream.Stream.prototype.pipe.call(self, dest, opts);
            return dest;
        }
    };
    Request.prototype.write = function () {
        var self = this;
        if (self._aborted) {
            return;
        }
        if (!self._started) {
            self.start();
        }
        if (self.req) {
            return self.req.write.apply(self.req, arguments);
        }
    };
    Request.prototype.end = function (chunk) {
        var self = this;
        if (self._aborted) {
            return;
        }
        if (chunk) {
            self.write(chunk);
        }
        if (!self._started) {
            self.start();
        }
        if (self.req) {
            self.req.end();
        }
    };
    Request.prototype.pause = function () {
        var self = this;
        if (!self.responseContent) {
            self._paused = true;
        }
        else {
            self.responseContent.pause.apply(self.responseContent, arguments);
        }
    };
    Request.prototype.resume = function () {
        var self = this;
        if (!self.responseContent) {
            self._paused = false;
        }
        else {
            self.responseContent.resume.apply(self.responseContent, arguments);
        }
    };
    Request.prototype.destroy = function () {
        var self = this;
        if (!self._ended) {
            self.end();
        }
        else if (self.response) {
            self.response.destroy();
        }
    };
    Request.defaultProxyHeaderWhiteList =
        Tunnel.defaultProxyHeaderWhiteList.slice();
    Request.defaultProxyHeaderExclusiveList =
        Tunnel.defaultProxyHeaderExclusiveList.slice();
    // Exports
    Request.prototype.toJSON = requestToJSON;
    module.exports = Request;
}
,
/* require-directory/index */ function _(require, module, exports) {
    var fs = require('fs'), join = require('path').join, resolve = require('path').resolve, dirname = require('path').dirname, defaultOptions = {
        extensions: ['js', 'json', 'coffee'],
        recurse: true,
        rename: function (name) {
            return name;
        },
        visit: function (obj) {
            return obj;
        }
    };
    function checkFileInclusion(path, filename, options) {
        return (
        // verify file has valid extension
        (new RegExp('\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) &&
            // if options.include is a RegExp, evaluate it and make sure the path passes
            !(options.include && options.include instanceof RegExp && !options.include.test(path)) &&
            // if options.include is a function, evaluate it and make sure the path passes
            !(options.include && typeof options.include === 'function' && !options.include(path, filename)) &&
            // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass
            !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) &&
            // if options.exclude is a function, evaluate it and make sure the path doesn't pass
            !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename)));
    }
    function requireDirectory(m, path, options) {
        var retval = {};
        // path is optional
        if (path && !options && typeof path !== 'string') {
            options = path;
            path = null;
        }
        // default options
        options = options || {};
        for (var prop in defaultOptions) {
            if (typeof options[prop] === 'undefined') {
                options[prop] = defaultOptions[prop];
            }
        }
        // if no path was passed in, assume the equivelant of __dirname from caller
        // otherwise, resolve path relative to the equivalent of __dirname
        path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path);
        // get the path of each file in specified directory, append to current tree node, recurse
        fs.readdirSync(path).forEach(function (filename) {
            var joined = join(path, filename), files, key, obj;
            if (fs.statSync(joined).isDirectory() && options.recurse) {
                // this node is a directory; recurse
                files = requireDirectory(m, joined, options);
                // exclude empty directories
                if (Object.keys(files).length) {
                    retval[options.rename(filename, joined, filename)] = files;
                }
            }
            else {
                if (joined !== m.filename && checkFileInclusion(joined, filename, options)) {
                    // hash node key shouldn't include file extension
                    key = filename.substring(0, filename.lastIndexOf('.'));
                    obj = m.require(joined);
                    retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj;
                }
            }
        });
        return retval;
    }
    module.exports = requireDirectory;
    module.exports.defaults = defaultOptions;
}
,
/* require-main-filename/index */ function _(require, module, exports) {
    module.exports = function (_require) {
        _require = _require || require;
        var main = _require.main;
        if (main && isIISNode(main))
            return handleIISNode(main);
        else
            return main ? main.filename : process.cwd();
    };
    function isIISNode(main) {
        return /\\iisnode\\/.test(main.filename);
    }
    function handleIISNode(main) {
        if (!main.children.length) {
            return main.filename;
        }
        else {
            return main.children[0].filename;
        }
    }
}
,
/* right-align/index */ function _(require, module, exports) {
    var align = require(42) /* align-text */;
    module.exports = function rightAlign(val) {
        return align(val, function (len, longest) {
            return longest - len;
        });
    };
}
,
/* safe-buffer/index */ 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;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
        return Buffer(arg, encodingOrOffset, length);
    }
    // Copy static methods from Buffer
    copyProps(Buffer, SafeBuffer);
    SafeBuffer.from = function (arg, encodingOrOffset, length) {
        if (typeof arg === 'number') {
            throw new TypeError('Argument must not be a number');
        }
        return Buffer(arg, encodingOrOffset, length);
    };
    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;
    };
    SafeBuffer.allocUnsafe = function (size) {
        if (typeof size !== 'number') {
            throw new TypeError('Argument must be a number');
        }
        return Buffer(size);
    };
    SafeBuffer.allocUnsafeSlow = function (size) {
        if (typeof size !== 'number') {
            throw new TypeError('Argument must be a number');
        }
        return buffer.SlowBuffer(size);
    };
}
,
/* safer-buffer/safer */ function _(require, module, exports) {
    var buffer = require('buffer');
    var Buffer = buffer.Buffer;
    var safer = {};
    var key;
    for (key in buffer) {
        if (!buffer.hasOwnProperty(key))
            continue;
        if (key === 'SlowBuffer' || key === 'Buffer')
            continue;
        safer[key] = buffer[key];
    }
    var Safer = safer.Buffer = {};
    for (key in Buffer) {
        if (!Buffer.hasOwnProperty(key))
            continue;
        if (key === 'allocUnsafe' || key === 'allocUnsafeSlow')
            continue;
        Safer[key] = Buffer[key];
    }
    safer.Buffer.prototype = Buffer.prototype;
    if (!Safer.from || Safer.from === Uint8Array.from) {
        Safer.from = function (value, encodingOrOffset, length) {
            if (typeof value === 'number') {
                throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value);
            }
            if (value && typeof value.length === 'undefined') {
                throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value);
            }
            return Buffer(value, encodingOrOffset, length);
        };
    }
    if (!Safer.alloc) {
        Safer.alloc = function (size, fill, encoding) {
            if (typeof size !== 'number') {
                throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size);
            }
            if (size < 0 || size >= 2 * (1 << 30)) {
                throw new RangeError('The value "' + size + '" is invalid for option "size"');
            }
            var buf = Buffer(size);
            if (!fill || fill.length === 0) {
                buf.fill(0);
            }
            else if (typeof encoding === 'string') {
                buf.fill(fill, encoding);
            }
            else {
                buf.fill(fill);
            }
            return buf;
        };
    }
    if (!safer.kStringMaxLength) {
        try {
            safer.kStringMaxLength = process.binding('buffer').kStringMaxLength;
        }
        catch (e) {
            // we can't determine kStringMaxLength in environments where process.binding
            // is unsupported, so let's not set it
        }
    }
    if (!safer.constants) {
        safer.constants = {
            MAX_LENGTH: safer.kMaxLength
        };
        if (safer.kStringMaxLength) {
            safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength;
        }
    }
    module.exports = safer;
}
,
/* set-blocking/index */ function _(require, module, exports) {
    module.exports = function (blocking) {
        [process.stdout, process.stderr].forEach(function (stream) {
            if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') {
                stream._handle.setBlocking(blocking);
            }
        });
    };
}
,
/* shebang-command/index */ function _(require, module, exports) {
    var shebangRegex = require(315) /* shebang-regex */;
    module.exports = function (str) {
        var match = str.match(shebangRegex);
        if (!match) {
            return null;
        }
        var arr = match[0].replace(/#! ?/, '').split(' ');
        var bin = arr[0].split('/').pop();
        var arg = arr[1];
        return (bin === 'env' ?
            arg :
            bin + (arg ? ' ' + arg : ''));
    };
}
,
/* shebang-regex/index */ function _(require, module, exports) {
    module.exports = /^#!.*/;
}
,
/* signal-exit/index */ function _(require, module, exports) {
    // Note: since nyc uses this module to output coverage, any lines
    // that are in the direct sync flow of nyc's outputCoverage are
    // ignored, since we can never get coverage for them.
    var assert = require('assert');
    var signals = require(317) /* ./signals.js */;
    var EE = require('events');
    /* istanbul ignore if */
    if (typeof EE !== 'function') {
        EE = EE.EventEmitter;
    }
    var emitter;
    if (process.__signal_exit_emitter__) {
        emitter = process.__signal_exit_emitter__;
    }
    else {
        emitter = process.__signal_exit_emitter__ = new EE();
        emitter.count = 0;
        emitter.emitted = {};
    }
    // Because this emitter is a global, we have to check to see if a
    // previous version of this library failed to enable infinite listeners.
    // I know what you're about to say.  But literally everything about
    // signal-exit is a compromise with evil.  Get used to it.
    if (!emitter.infinite) {
        emitter.setMaxListeners(Infinity);
        emitter.infinite = true;
    }
    module.exports = function (cb, opts) {
        assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
        if (loaded === false) {
            load();
        }
        var ev = 'exit';
        if (opts && opts.alwaysLast) {
            ev = 'afterexit';
        }
        var remove = function () {
            emitter.removeListener(ev, cb);
            if (emitter.listeners('exit').length === 0 &&
                emitter.listeners('afterexit').length === 0) {
                unload();
            }
        };
        emitter.on(ev, cb);
        return remove;
    };
    module.exports.unload = unload;
    function unload() {
        if (!loaded) {
            return;
        }
        loaded = false;
        signals.forEach(function (sig) {
            try {
                process.removeListener(sig, sigListeners[sig]);
            }
            catch (er) { }
        });
        process.emit = originalProcessEmit;
        process.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
    }
    function emit(event, code, signal) {
        if (emitter.emitted[event]) {
            return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code, signal);
    }
    // { <signal>: <listener fn>, ... }
    var sigListeners = {};
    signals.forEach(function (sig) {
        sigListeners[sig] = function listener() {
            // If there are no other listeners, an exit is coming!
            // Simplest way: remove us and then re-send the signal.
            // We know that this will kill the process, so we can
            // safely emit now.
            var listeners = process.listeners(sig);
            if (listeners.length === emitter.count) {
                unload();
                emit('exit', null, sig);
                /* istanbul ignore next */
                emit('afterexit', null, sig);
                /* istanbul ignore next */
                process.kill(process.pid, sig);
            }
        };
    });
    module.exports.signals = function () {
        return signals;
    };
    module.exports.load = load;
    var loaded = false;
    function load() {
        if (loaded) {
            return;
        }
        loaded = true;
        // This is the number of onSignalExit's that are in play.
        // It's important so that we can count the correct number of
        // listeners on signals, and don't wait for the other one to
        // handle it instead of us.
        emitter.count += 1;
        signals = signals.filter(function (sig) {
            try {
                process.on(sig, sigListeners[sig]);
                return true;
            }
            catch (er) {
                return false;
            }
        });
        process.emit = processEmit;
        process.reallyExit = processReallyExit;
    }
    var originalProcessReallyExit = process.reallyExit;
    function processReallyExit(code) {
        process.exitCode = code || 0;
        emit('exit', process.exitCode, null);
        /* istanbul ignore next */
        emit('afterexit', process.exitCode, null);
        /* istanbul ignore next */
        originalProcessReallyExit.call(process, process.exitCode);
    }
    var originalProcessEmit = process.emit;
    function processEmit(ev, arg) {
        if (ev === 'exit') {
            if (arg !== undefined) {
                process.exitCode = arg;
            }
            var ret = originalProcessEmit.apply(this, arguments);
            emit('exit', process.exitCode, null);
            /* istanbul ignore next */
            emit('afterexit', process.exitCode, null);
            return ret;
        }
        else {
            return originalProcessEmit.apply(this, arguments);
        }
    }
}
,
/* signal-exit/signals */ function _(require, module, exports) {
    // This is not the set of all possible signals.
    //
    // It IS, however, the set of all signals that trigger
    // an exit on either Linux or BSD systems.  Linux is a
    // superset of the signal names supported on BSD, and
    // the unknown signals just fail to register, so we can
    // catch that easily enough.
    //
    // Don't bother with SIGKILL.  It's uncatchable, which
    // means that we can't fire any callbacks anyway.
    //
    // If a user does happen to register a handler on a non-
    // fatal signal like SIGWINCH or something, and then
    // exit, it'll end up firing `process.emit('exit')`, so
    // the handler will be fired anyway.
    //
    // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
    // artificially, inherently leave the process in a
    // state from which it is not safe to try and enter JS
    // listeners.
    module.exports = [
        'SIGABRT',
        'SIGALRM',
        'SIGHUP',
        'SIGINT',
        'SIGTERM'
    ];
    if (process.platform !== 'win32') {
        module.exports.push('SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
        // should detect profiler and enable/disable accordingly.
        // see #21
        // 'SIGPROF'
        );
    }
    if (process.platform === 'linux') {
        module.exports.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED');
    }
}
,
/* source-map-support/source-map-support */ function _(require, module, exports) {
    var SourceMapConsumer = require(319) /* source-map */.SourceMapConsumer;
    var path = require('path');
    var fs;
    try {
        fs = require('fs');
        if (!fs.existsSync || !fs.readFileSync) {
            // fs doesn't have all methods we need
            fs = null;
        }
    }
    catch (err) {
        /* nop */
    }
    var bufferFrom = require(68) /* buffer-from */;
    // Only install once if called multiple times
    var errorFormatterInstalled = false;
    var uncaughtShimInstalled = false;
    // If true, the caches are reset before a stack trace formatting operation
    var emptyCacheBetweenOperations = false;
    // Supports {browser, node, auto}
    var environment = "auto";
    // Maps a file path to a string containing the file contents
    var fileContentsCache = {};
    // Maps a file path to a source map for that file
    var sourceMapCache = {};
    // Regex for detecting source maps
    var reSourceMap = /^data:application\/json[^,]+base64,/;
    // Priority list of retrieve handlers
    var retrieveFileHandlers = [];
    var retrieveMapHandlers = [];
    function isInBrowser() {
        if (environment === "browser")
            return true;
        if (environment === "node")
            return false;
        return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
    }
    function hasGlobalProcessEventEmitter() {
        return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
    }
    function handlerExec(list) {
        return function (arg) {
            for (var i = 0; i < list.length; i++) {
                var ret = list[i](arg);
                if (ret) {
                    return ret;
                }
            }
            return null;
        };
    }
    var retrieveFile = handlerExec(retrieveFileHandlers);
    retrieveFileHandlers.push(function (path) {
        // Trim the path to make sure there is no extra whitespace.
        path = path.trim();
        if (/^file:/.test(path)) {
            // existsSync/readFileSync can't handle file protocol, but once stripped, it works
            path = path.replace(/file:\/\/\/(\w:)?/, function (protocol, drive) {
                return drive ?
                    '' : // file:///C:/dir/file -> C:/dir/file
                    '/'; // file:///root-dir/file -> /root-dir/file
            });
        }
        if (path in fileContentsCache) {
            return fileContentsCache[path];
        }
        var contents = null;
        if (!fs) {
            // Use SJAX if we are in the browser
            var xhr = new XMLHttpRequest();
            xhr.open('GET', path, false);
            xhr.send(null);
            var contents = null;
            if (xhr.readyState === 4 && xhr.status === 200) {
                contents = xhr.responseText;
            }
        }
        else if (fs.existsSync(path)) {
            // Otherwise, use the filesystem
            try {
                contents = fs.readFileSync(path, 'utf8');
            }
            catch (er) {
                contents = '';
            }
        }
        return fileContentsCache[path] = contents;
    });
    // Support URLs relative to a directory, but be careful about a protocol prefix
    // in case we are in the browser (i.e. directories may start with "http://" or "file:///")
    function supportRelativeURL(file, url) {
        if (!file)
            return url;
        var dir = path.dirname(file);
        var match = /^\w+:\/\/[^\/]*/.exec(dir);
        var protocol = match ? match[0] : '';
        var startPath = dir.slice(protocol.length);
        if (protocol && /^\/\w\:/.test(startPath)) {
            // handle file:///C:/ paths
            protocol += '/';
            return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
        }
        return protocol + path.resolve(dir.slice(protocol.length), url);
    }
    function retrieveSourceMapURL(source) {
        var fileData;
        if (isInBrowser()) {
            try {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', source, false);
                xhr.send(null);
                fileData = xhr.readyState === 4 ? xhr.responseText : null;
                // Support providing a sourceMappingURL via the SourceMap header
                var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
                    xhr.getResponseHeader("X-SourceMap");
                if (sourceMapHeader) {
                    return sourceMapHeader;
                }
            }
            catch (e) {
            }
        }
        // Get the URL of the source map
        fileData = retrieveFile(source);
        var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg;
        // Keep executing the search to find the *last* sourceMappingURL to avoid
        // picking up sourceMappingURLs from comments, strings, etc.
        var lastMatch, match;
        while (match = re.exec(fileData))
            lastMatch = match;
        if (!lastMatch)
            return null;
        return lastMatch[1];
    }
    ;
    // Can be overridden by the retrieveSourceMap option to install. Takes a
    // generated source filename; returns a {map, optional url} object, or null if
    // there is no source map.  The map field may be either a string or the parsed
    // JSON object (ie, it must be a valid argument to the SourceMapConsumer
    // constructor).
    var retrieveSourceMap = handlerExec(retrieveMapHandlers);
    retrieveMapHandlers.push(function (source) {
        var sourceMappingURL = retrieveSourceMapURL(source);
        if (!sourceMappingURL)
            return null;
        // Read the contents of the source map
        var sourceMapData;
        if (reSourceMap.test(sourceMappingURL)) {
            // Support source map URL as a data url
            var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
            sourceMapData = bufferFrom(rawData, "base64").toString();
            sourceMappingURL = source;
        }
        else {
            // Support source map URLs relative to the source URL
            sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
            sourceMapData = retrieveFile(sourceMappingURL);
        }
        if (!sourceMapData) {
            return null;
        }
        return {
            url: sourceMappingURL,
            map: sourceMapData
        };
    });
    function mapSourcePosition(position) {
        var sourceMap = sourceMapCache[position.source];
        if (!sourceMap) {
            // Call the (overrideable) retrieveSourceMap function to get the source map.
            var urlAndMap = retrieveSourceMap(position.source);
            if (urlAndMap) {
                sourceMap = sourceMapCache[position.source] = {
                    url: urlAndMap.url,
                    map: new SourceMapConsumer(urlAndMap.map)
                };
                // Load all sources stored inline with the source map into the file cache
                // to pretend like they are already loaded. They may not exist on disk.
                if (sourceMap.map.sourcesContent) {
                    sourceMap.map.sources.forEach(function (source, i) {
                        var contents = sourceMap.map.sourcesContent[i];
                        if (contents) {
                            var url = supportRelativeURL(sourceMap.url, source);
                            fileContentsCache[url] = contents;
                        }
                    });
                }
            }
            else {
                sourceMap = sourceMapCache[position.source] = {
                    url: null,
                    map: null
                };
            }
        }
        // Resolve the source URL relative to the URL of the source map
        if (sourceMap && sourceMap.map) {
            var originalPosition = sourceMap.map.originalPositionFor(position);
            // Only return the original position if a matching line was found. If no
            // matching line is found then we return position instead, which will cause
            // the stack trace to print the path and line for the compiled file. It is
            // better to give a precise location in the compiled file than a vague
            // location in the original file.
            if (originalPosition.source !== null) {
                originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source);
                return originalPosition;
            }
        }
        return position;
    }
    // Parses code generated by FormatEvalOrigin(), a function inside V8:
    // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
    function mapEvalOrigin(origin) {
        // Most eval() calls are in this format
        var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
        if (match) {
            var position = mapSourcePosition({
                source: match[2],
                line: +match[3],
                column: match[4] - 1
            });
            return 'eval at ' + match[1] + ' (' + position.source + ':' +
                position.line + ':' + (position.column + 1) + ')';
        }
        // Parse nested eval() calls using recursion
        match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
        if (match) {
            return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
        }
        // Make sure we still return useful information if we didn't find anything
        return origin;
    }
    // This is copied almost verbatim from the V8 source code at
    // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
    // implementation of wrapCallSite() used to just forward to the actual source
    // code of CallSite.prototype.toString but unfortunately a new release of V8
    // did something to the prototype chain and broke the shim. The only fix I
    // could find was copy/paste.
    function CallSiteToString() {
        var fileName;
        var fileLocation = "";
        if (this.isNative()) {
            fileLocation = "native";
        }
        else {
            fileName = this.getScriptNameOrSourceURL();
            if (!fileName && this.isEval()) {
                fileLocation = this.getEvalOrigin();
                fileLocation += ", "; // Expecting source position to follow.
            }
            if (fileName) {
                fileLocation += fileName;
            }
            else {
                // Source code does not originate from a file and is not native, but we
                // can still get the source position inside the source string, e.g. in
                // an eval string.
                fileLocation += "<anonymous>";
            }
            var lineNumber = this.getLineNumber();
            if (lineNumber != null) {
                fileLocation += ":" + lineNumber;
                var columnNumber = this.getColumnNumber();
                if (columnNumber) {
                    fileLocation += ":" + columnNumber;
                }
            }
        }
        var line = "";
        var functionName = this.getFunctionName();
        var addSuffix = true;
        var isConstructor = this.isConstructor();
        var isMethodCall = !(this.isToplevel() || isConstructor);
        if (isMethodCall) {
            var typeName = this.getTypeName();
            // Fixes shim to be backward compatable with Node v0 to v4
            if (typeName === "[object Object]") {
                typeName = "null";
            }
            var methodName = this.getMethodName();
            if (functionName) {
                if (typeName && functionName.indexOf(typeName) != 0) {
                    line += typeName + ".";
                }
                line += functionName;
                if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
                    line += " [as " + methodName + "]";
                }
            }
            else {
                line += typeName + "." + (methodName || "<anonymous>");
            }
        }
        else if (isConstructor) {
            line += "new " + (functionName || "<anonymous>");
        }
        else if (functionName) {
            line += functionName;
        }
        else {
            line += fileLocation;
            addSuffix = false;
        }
        if (addSuffix) {
            line += " (" + fileLocation + ")";
        }
        return line;
    }
    function cloneCallSite(frame) {
        var object = {};
        Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function (name) {
            object[name] = /^(?:is|get)/.test(name) ? function () { return frame[name].call(frame); } : frame[name];
        });
        object.toString = CallSiteToString;
        return object;
    }
    function wrapCallSite(frame) {
        if (frame.isNative()) {
            return frame;
        }
        // Most call sites will return the source file from getFileName(), but code
        // passed to eval() ending in "//# sourceURL=..." will return the source file
        // from getScriptNameOrSourceURL() instead
        var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
        if (source) {
            var line = frame.getLineNumber();
            var column = frame.getColumnNumber() - 1;
            // Fix position in Node where some (internal) code is prepended.
            // See https://github.com/evanw/node-source-map-support/issues/36
            var headerLength = 62;
            if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
                column -= headerLength;
            }
            var position = mapSourcePosition({
                source: source,
                line: line,
                column: column
            });
            frame = cloneCallSite(frame);
            frame.getFileName = function () { return position.source; };
            frame.getLineNumber = function () { return position.line; };
            frame.getColumnNumber = function () { return position.column + 1; };
            frame.getScriptNameOrSourceURL = function () { return position.source; };
            return frame;
        }
        // Code called using eval() needs special handling
        var origin = frame.isEval() && frame.getEvalOrigin();
        if (origin) {
            origin = mapEvalOrigin(origin);
            frame = cloneCallSite(frame);
            frame.getEvalOrigin = function () { return origin; };
            return frame;
        }
        // If we get here then we were unable to change the source position
        return frame;
    }
    // This function is part of the V8 stack trace API, for more info see:
    // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
    function prepareStackTrace(error, stack) {
        if (emptyCacheBetweenOperations) {
            fileContentsCache = {};
            sourceMapCache = {};
        }
        return error + stack.map(function (frame) {
            return '\n    at ' + wrapCallSite(frame);
        }).join('');
    }
    // Generate position and snippet of original source with pointer
    function getErrorSource(error) {
        var match = /\n    at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
        if (match) {
            var source = match[1];
            var line = +match[2];
            var column = +match[3];
            // Support the inline sourceContents inside the source map
            var contents = fileContentsCache[source];
            // Support files on disk
            if (!contents && fs && fs.existsSync(source)) {
                try {
                    contents = fs.readFileSync(source, 'utf8');
                }
                catch (er) {
                    contents = '';
                }
            }
            // Format the line from the original source code like node does
            if (contents) {
                var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
                if (code) {
                    return source + ':' + line + '\n' + code + '\n' +
                        new Array(column).join(' ') + '^';
                }
            }
        }
        return null;
    }
    function printErrorAndExit(error) {
        var source = getErrorSource(error);
        if (source) {
            fs.writeSync(2, "\n" + source + "\n");
        }
        fs.writeSync(2, error.stack + "\n");
        process.exit(1);
    }
    function shimEmitUncaughtException() {
        var origEmit = process.emit;
        process.emit = function (type) {
            if (type === 'uncaughtException') {
                var hasStack = (arguments[1] && arguments[1].stack);
                var hasListeners = (this.listeners(type).length > 0);
                if (hasStack && !hasListeners) {
                    return printErrorAndExit(arguments[1]);
                }
            }
            return origEmit.apply(this, arguments);
        };
    }
    var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
    var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
    exports.wrapCallSite = wrapCallSite;
    exports.getErrorSource = getErrorSource;
    exports.mapSourcePosition = mapSourcePosition;
    exports.retrieveSourceMap = retrieveSourceMap;
    exports.install = function (options) {
        options = options || {};
        if (options.environment) {
            environment = options.environment;
            if (["node", "browser", "auto"].indexOf(environment) === -1) {
                throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}");
            }
        }
        // Allow sources to be found by methods other than reading the files
        // directly from disk.
        if (options.retrieveFile) {
            if (options.overrideRetrieveFile) {
                retrieveFileHandlers.length = 0;
            }
            retrieveFileHandlers.unshift(options.retrieveFile);
        }
        // Allow source maps to be found by methods other than reading the files
        // directly from disk.
        if (options.retrieveSourceMap) {
            if (options.overrideRetrieveSourceMap) {
                retrieveMapHandlers.length = 0;
            }
            retrieveMapHandlers.unshift(options.retrieveSourceMap);
        }
        // Support runtime transpilers that include inline source maps
        if (options.hookRequire && !isInBrowser()) {
            var Module;
            try {
                Module = require('module');
            }
            catch (err) {
                // NOP: Loading in catch block to convert webpack error to warning.
            }
            var $compile = Module.prototype._compile;
            if (!$compile.__sourceMapSupport) {
                Module.prototype._compile = function (content, filename) {
                    fileContentsCache[filename] = content;
                    sourceMapCache[filename] = undefined;
                    return $compile.call(this, content, filename);
                };
                Module.prototype._compile.__sourceMapSupport = true;
            }
        }
        // Configure options
        if (!emptyCacheBetweenOperations) {
            emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
                options.emptyCacheBetweenOperations : false;
        }
        // Install the error reformatter
        if (!errorFormatterInstalled) {
            errorFormatterInstalled = true;
            Error.prepareStackTrace = prepareStackTrace;
        }
        if (!uncaughtShimInstalled) {
            var installHandler = 'handleUncaughtExceptions' in options ?
                options.handleUncaughtExceptions : true;
            // Provide the option to not install the uncaught exception handler. This is
            // to support other uncaught exception handlers (in test frameworks, for
            // example). If this handler is not installed and there are no other uncaught
            // exception handlers, uncaught exceptions will be caught by node's built-in
            // exception handler and the process will still be terminated. However, the
            // generated JavaScript code will be shown above the stack trace instead of
            // the original source code.
            if (installHandler && hasGlobalProcessEventEmitter()) {
                uncaughtShimInstalled = true;
                shimEmitUncaughtException();
            }
        }
    };
    exports.resetRetrieveHandlers = function () {
        retrieveFileHandlers.length = 0;
        retrieveMapHandlers.length = 0;
        retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
        retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
    };
}
,
/* source-map/lib/source-map */ 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(327) /* ./source-map/source-map-generator */.SourceMapGenerator;
    exports.SourceMapConsumer = require(326) /* ./source-map/source-map-consumer */.SourceMapConsumer;
    exports.SourceNode = require(328) /* ./source-map/source-node */.SourceNode;
}
,
/* source-map/lib/source-map/array-set */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        var util = require(329) /* ./util */;
        /**
         * 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 = {};
        }
        /**
         * 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;
        };
        /**
         * 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 isDuplicate = this.has(aStr);
            var idx = this._array.length;
            if (!isDuplicate || aAllowDuplicates) {
                this._array.push(aStr);
            }
            if (!isDuplicate) {
                this._set[util.toSetString(aStr)] = idx;
            }
        };
        /**
         * Is the given string a member of this set?
         *
         * @param String aStr
         */
        ArraySet.prototype.has = function ArraySet_has(aStr) {
            return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr));
        };
        /**
         * What is the index of the given string in the array?
         *
         * @param String aStr
         */
        ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
            if (this.has(aStr)) {
                return this._set[util.toSetString(aStr)];
            }
            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);
        };
        /**
         * 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();
        };
        exports.ArraySet = ArraySet;
    });
}
,
/* source-map/lib/source-map/base64-vlq */ 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.
     */
    if (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        var base64 = require(322) /* ./base64 */;
        // 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
        var VLQ_BASE_SHIFT = 5;
        // binary: 100000
        var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
        // binary: 011111
        var VLQ_BASE_MASK = VLQ_BASE - 1;
        // binary: 100000
        var VLQ_CONTINUATION_BIT = VLQ_BASE;
        /**
         * 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;
        }
        /**
         * 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;
        }
        /**
         * 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;
        };
        /**
         * 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;
            do {
                if (aIndex >= strLen) {
                    throw new Error("Expected more digits in base 64 VLQ value.");
                }
                digit = base64.decode(aStr.charCodeAt(aIndex++));
                if (digit === -1) {
                    throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
                }
                continuation = !!(digit & VLQ_CONTINUATION_BIT);
                digit &= VLQ_BASE_MASK;
                result = result + (digit << shift);
                shift += VLQ_BASE_SHIFT;
            } while (continuation);
            aOutParam.value = fromVLQSigned(result);
            aOutParam.rest = aIndex;
        };
    });
}
,
/* source-map/lib/source-map/base64 */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        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];
            }
            throw new TypeError("Must be between 0 and 63: " + aNumber);
        };
        /**
         * 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'
            var littleA = 97; // 'a'
            var littleZ = 122; // 'z'
            var zero = 48; // '0'
            var nine = 57; // '9'
            var plus = 43; // '+'
            var slash = 47; // '/'
            var littleOffset = 26;
            var numberOffset = 52;
            // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
            if (bigA <= charCode && charCode <= bigZ) {
                return (charCode - bigA);
            }
            // 26 - 51: abcdefghijklmnopqrstuvwxyz
            if (littleA <= charCode && charCode <= littleZ) {
                return (charCode - littleA + littleOffset);
            }
            // 52 - 61: 0123456789
            if (zero <= charCode && charCode <= nine) {
                return (charCode - zero + numberOffset);
            }
            // 62: +
            if (charCode == plus) {
                return 62;
            }
            // 63: /
            if (charCode == slash) {
                return 63;
            }
            // Invalid base64 digit.
            return -1;
        };
    });
}
,
/* source-map/lib/source-map/binary-search */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        exports.GREATEST_LOWER_BOUND = 1;
        exports.LEAST_UPPER_BOUND = 2;
        /**
         * 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);
                }
                // 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);
                }
                // 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;
                }
            }
        }
        /**
         * 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;
            }
            var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND);
            if (index < 0) {
                return -1;
            }
            // 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;
            }
            return index;
        };
    });
}
,
/* source-map/lib/source-map/mapping-list */ 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
     */
    if (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        var util = require(329) /* ./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;
        }
        /**
         * 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 };
        }
        /**
         * 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) {
            var mapping;
            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;
        };
        exports.MappingList = MappingList;
    });
}
,
/* source-map/lib/source-map/quick-sort */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        // 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`.
         *
         * @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;
        }
        /**
         * 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)));
        }
        /**
         * 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.
            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);
            }
        }
        /**
         * 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);
        };
    });
}
,
/* source-map/lib/source-map/source-map-consumer */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        var util = require(329) /* ./util */;
        var binarySearch = require(323) /* ./binary-search */;
        var ArraySet = require(320) /* ./array-set */.ArraySet;
        var base64VLQ = require(321) /* ./base64-vlq */;
        var quickSort = require(325) /* ./quick-sort */.quickSort;
        function SourceMapConsumer(aSourceMap) {
            var sourceMap = aSourceMap;
            if (typeof aSourceMap === 'string') {
                sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
            }
            return sourceMap.sections != null
                ? new IndexedSourceMapConsumer(sourceMap)
                : new BasicSourceMapConsumer(sourceMap);
        }
        SourceMapConsumer.fromSourceMap = function (aSourceMap) {
            return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
        };
        /**
         * The version of the source mapping spec that we are consuming.
         */
        SourceMapConsumer.prototype._version = 3;
        // `__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.
        SourceMapConsumer.prototype.__generatedMappings = null;
        Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
            get: function () {
                if (!this.__generatedMappings) {
                    this._parseMappings(this._mappings, this.sourceRoot);
                }
                return this.__generatedMappings;
            }
        });
        SourceMapConsumer.prototype.__originalMappings = null;
        Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
            get: function () {
                if (!this.__originalMappings) {
                    this._parseMappings(this._mappings, this.sourceRoot);
                }
                return this.__originalMappings;
            }
        });
        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");
            };
        SourceMapConsumer.GENERATED_ORDER = 1;
        SourceMapConsumer.ORIGINAL_ORDER = 2;
        SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
        SourceMapConsumer.LEAST_UPPER_BOUND = 2;
        /**
         * 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 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 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);
            };
        /**
         * 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');
                // 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)
                };
                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);
                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];
                    if (aArgs.column === undefined) {
                        var originalLine = mapping.originalLine;
                        // 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)
                            });
                            mapping = this._originalMappings[++index];
                        }
                    }
                    else {
                        var originalColumn = mapping.originalColumn;
                        // 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)
                            });
                            mapping = this._originalMappings[++index];
                        }
                    }
                }
                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(/^\)\]\}'/, ''));
            }
            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);
            }
            // 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.
            sources = sources.map(util.normalize);
            // 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, true);
            this._sources = ArraySet.fromArray(sources, true);
            this.sourceRoot = sourceRoot;
            this.sourcesContent = sourcesContent;
            this._mappings = mappings;
            this.file = file;
        }
        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);
                        }
                        destOriginalMappings.push(destMapping);
                    }
                    destGeneratedMappings.push(destMapping);
                }
                quickSort(smc.__originalMappings, util.compareByOriginalPositions);
                return smc;
            };
        /**
         * The version of the source mapping spec that we are consuming.
         */
        BasicSourceMapConsumer.prototype._version = 3;
        /**
         * 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);
            }
        });
        /**
         * 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;
        }
        /**
         * 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;
                while (index < length) {
                    if (aStr.charAt(index) === ';') {
                        generatedLine++;
                        index++;
                        previousGeneratedColumn = 0;
                    }
                    else if (aStr.charAt(index) === ',') {
                        index++;
                    }
                    else {
                        mapping = new Mapping();
                        mapping.generatedLine = generatedLine;
                        // 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);
                        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');
                            }
                            cachedSegments[str] = segment;
                        }
                        // Generated column.
                        mapping.generatedColumn = previousGeneratedColumn + segment[0];
                        previousGeneratedColumn = mapping.generatedColumn;
                        if (segment.length > 1) {
                            // Original source.
                            mapping.source = previousSource + segment[1];
                            previousSource += segment[1];
                            // Original line.
                            mapping.originalLine = previousOriginalLine + segment[2];
                            previousOriginalLine = mapping.originalLine;
                            // Lines are stored 0-based
                            mapping.originalLine += 1;
                            // Original column.
                            mapping.originalColumn = previousOriginalColumn + segment[3];
                            previousOriginalColumn = mapping.originalColumn;
                            if (segment.length > 4) {
                                // Original name.
                                mapping.name = previousName + segment[4];
                                previousName += segment[4];
                            }
                        }
                        generatedMappings.push(mapping);
                        if (typeof mapping.originalLine === 'number') {
                            originalMappings.push(mapping);
                        }
                    }
                }
                quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
                this.__generatedMappings = generatedMappings;
                quickSort(originalMappings, util.compareByOriginalPositions);
                this.__originalMappings = originalMappings;
            };
        /**
         * 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.
                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]);
                }
                return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
            };
        /**
         * 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];
                        if (mapping.generatedLine === nextMapping.generatedLine) {
                            mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
                            continue;
                        }
                    }
                    // The last mapping for each line spans the entire line.
                    mapping.lastGeneratedColumn = Infinity;
                }
            };
        /**
         * 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')
                };
                var index = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
                if (index >= 0) {
                    var mapping = this._generatedMappings[index];
                    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 {
                    source: null,
                    line: null,
                    column: null,
                    name: null
                };
            };
        /**
         * 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; });
            };
        /**
         * Returns the original source content. The only argument is the url of the
         * original source file. Returns null if no original source content is
         * availible.
         */
        BasicSourceMapConsumer.prototype.sourceContentFor =
            function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
                if (!this.sourcesContent) {
                    return null;
                }
                if (this.sourceRoot != null) {
                    aSource = util.relative(this.sourceRoot, aSource);
                }
                if (this._sources.has(aSource)) {
                    return this.sourcesContent[this._sources.indexOf(aSource)];
                }
                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)];
                    }
                    if ((!url.path || url.path == "/")
                        && this._sources.has("/" + aSource)) {
                        return this.sourcesContent[this._sources.indexOf("/" + aSource)];
                    }
                }
                // 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.');
                }
            };
        /**
         * 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);
                var needle = {
                    source: source,
                    originalLine: util.getArg(aArgs, 'line'),
                    originalColumn: util.getArg(aArgs, 'column')
                };
                var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
                if (index >= 0) {
                    var mapping = this._originalMappings[index];
                    if (mapping.source === needle.source) {
                        return {
                            line: util.getArg(mapping, 'generatedLine', null),
                            column: util.getArg(mapping, 'generatedColumn', null),
                            lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
                        };
                    }
                }
                return {
                    line: null,
                    column: null,
                    lastColumn: null
                };
            };
        exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
        /**
         * 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(/^\)\]\}'/, ''));
            }
            var version = util.getArg(sourceMap, 'version');
            var sections = util.getArg(sourceMap, 'sections');
            if (version != this._version) {
                throw new Error('Unsupported version: ' + version);
            }
            this._sources = new ArraySet();
            this._names = new ArraySet();
            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');
                if (offsetLine < lastOffset.line ||
                    (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
                    throw new Error('Section offsets must be ordered and non-overlapping.');
                }
                lastOffset = offset;
                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'))
                };
            });
        }
        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;
        /**
         * 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;
            }
        });
        /**
         * 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')
                };
                // 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;
                    }
                    return (needle.generatedColumn -
                        section.generatedOffset.generatedColumn);
                });
                var section = this._sections[sectionIndex];
                if (!section) {
                    return {
                        source: null,
                        line: null,
                        column: null,
                        name: null
                    };
                }
                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
                });
            };
        /**
         * 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();
                });
            };
        /**
         * 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 content = section.consumer.sourceContentFor(aSource, true);
                    if (content) {
                        return content;
                    }
                }
                if (nullOnMissing) {
                    return null;
                }
                else {
                    throw new Error('"' + aSource + '" is not in the SourceMap.');
                }
            };
        /**
         * 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;
                    }
                }
                return {
                    line: null,
                    column: null
                };
            };
        /**
         * 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[i];
                        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);
                        var name = section.consumer._names.at(mapping.name);
                        this._names.add(name);
                        name = this._names.indexOf(name);
                        // 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.column +
                                (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);
                        }
                    }
                    ;
                }
                ;
                quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
                quickSort(this.__originalMappings, util.compareByOriginalPositions);
            };
        exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
    });
}
,
/* source-map/lib/source-map/source-map-generator */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        var base64VLQ = require(321) /* ./base64-vlq */;
        var util = require(329) /* ./util */;
        var ArraySet = require(320) /* ./array-set */.ArraySet;
        var MappingList = require(324) /* ./mapping-list */.MappingList;
        /**
         * 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;
        }
        SourceMapGenerator.prototype._version = 3;
        /**
         * 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
                        }
                    };
                    if (mapping.source != null) {
                        newMapping.source = mapping.source;
                        if (sourceRoot != null) {
                            newMapping.source = util.relative(sourceRoot, newMapping.source);
                        }
                        newMapping.original = {
                            line: mapping.originalLine,
                            column: mapping.originalColumn
                        };
                        if (mapping.name != null) {
                            newMapping.name = mapping.name;
                        }
                    }
                    generator.addMapping(newMapping);
                });
                aSourceMapConsumer.sources.forEach(function (sourceFile) {
                    var content = aSourceMapConsumer.sourceContentFor(sourceFile);
                    if (content != null) {
                        generator.setSourceContent(sourceFile, content);
                    }
                });
                return generator;
            };
        /**
         * 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);
                if (!this._skipValidation) {
                    this._validateMapping(generated, original, source, name);
                }
                if (source != null && !this._sources.has(source)) {
                    this._sources.add(source);
                }
                if (name != null && !this._names.has(name)) {
                    this._names.add(name);
                }
                this._mappings.add({
                    generatedLine: generated.line,
                    generatedColumn: generated.column,
                    originalLine: original != null && original.line,
                    originalColumn: original != null && original.column,
                    source: source,
                    name: name
                });
            };
        /**
         * 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 (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 = {};
                    }
                    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;
                    }
                }
            };
        /**
         * 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();
                // 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;
                            }
                        }
                    }
                    var source = mapping.source;
                    if (source != null && !newSources.has(source)) {
                        newSources.add(source);
                    }
                    var name = mapping.name;
                    if (name != null && !newNames.has(name)) {
                        newNames.add(name);
                    }
                }, this);
                this._sources = newSources;
                this._names = newNames;
                // 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);
            };
        /**
         * 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
                    }));
                }
            };
        /**
         * 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 mapping;
                var mappings = this._mappings.toArray();
                for (var i = 0, len = mappings.length; i < len; i++) {
                    mapping = mappings[i];
                    if (mapping.generatedLine !== previousGeneratedLine) {
                        previousGeneratedColumn = 0;
                        while (mapping.generatedLine !== previousGeneratedLine) {
                            result += ';';
                            previousGeneratedLine++;
                        }
                    }
                    else {
                        if (i > 0) {
                            if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
                                continue;
                            }
                            result += ',';
                        }
                    }
                    result += base64VLQ.encode(mapping.generatedColumn
                        - previousGeneratedColumn);
                    previousGeneratedColumn = mapping.generatedColumn;
                    if (mapping.source != null) {
                        result += base64VLQ.encode(this._sources.indexOf(mapping.source)
                            - previousSource);
                        previousSource = this._sources.indexOf(mapping.source);
                        // lines are stored 0-based in SourceMap spec version 3
                        result += base64VLQ.encode(mapping.originalLine - 1
                            - previousOriginalLine);
                        previousOriginalLine = mapping.originalLine - 1;
                        result += base64VLQ.encode(mapping.originalColumn
                            - previousOriginalColumn);
                        previousOriginalColumn = mapping.originalColumn;
                        if (mapping.name != null) {
                            result += base64VLQ.encode(this._names.indexOf(mapping.name)
                                - previousName);
                            previousName = this._names.indexOf(mapping.name);
                        }
                    }
                }
                return result;
            };
        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);
            };
        /**
         * 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);
                }
                return map;
            };
        /**
         * Render the source map being generated to a string.
         */
        SourceMapGenerator.prototype.toString =
            function SourceMapGenerator_toString() {
                return JSON.stringify(this.toJSON());
            };
        exports.SourceMapGenerator = SourceMapGenerator;
    });
}
,
/* source-map/lib/source-map/source-node */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        var SourceMapGenerator = require(327) /* ./source-map-generator */.SourceMapGenerator;
        var util = require(329) /* ./util */;
        // 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)/;
        // Newline character code for charCodeAt() comparisons
        var NEWLINE_CODE = 10;
        // 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$$$";
        /**
         * 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);
        }
        /**
         * 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();
                // 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;
                };
                // We need to remember the position of "remainingLines"
                var lastGeneratedLine = 1, lastGeneratedColumn = 0;
                // 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;
                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) {
                            var code = "";
                            // 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);
                    }
                });
                return node;
                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));
                    }
                }
            };
        /**
         * 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;
        };
        /**
         * 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;
        };
        /**
         * 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;
        };
        /**
         * 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;
        };
        /**
         * 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;
            };
        /**
         * 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);
                    }
                }
                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]]);
                }
            };
        /**
         * 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;
        };
        /**
         * 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 };
        };
        exports.SourceNode = SourceNode;
    });
}
,
/* source-map/lib/source-map/util */ 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 (typeof define !== 'function') {
        var define = require(43) /* amdefine */(module, require);
    }
    define(function (require, exports, module) {
        /**
         * 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;
        var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
        var dataUrlRegexp = /^data:.+\,.+$/;
        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;
        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 consequtive slashes with one slash.
         * - Removes unnecessary '.' parts.
         * - Removes unnecessary '<dir>/..' 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 = (path.charAt(0) === '/');
            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 (path === '') {
                path = isAbsolute ? '/' : '.';
            }
            if (url) {
                url.path = path;
                return urlGenerate(url);
            }
            return path;
        }
        exports.normalize = normalize;
        /**
         * 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 || '/';
            }
            // `join(foo, '//www.example.org')`
            if (aPathUrl && !aPathUrl.scheme) {
                if (aRootUrl) {
                    aPathUrl.scheme = aRootUrl.scheme;
                }
                return urlGenerate(aPathUrl);
            }
            if (aPathUrl || aPath.match(dataUrlRegexp)) {
                return aPath;
            }
            // `join('http://', 'www.example.com')`
            if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
                aRootUrl.host = aPath;
                return urlGenerate(aRootUrl);
            }
            var joined = aPath.charAt(0) === '/'
                ? aPath
                : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
            if (aRootUrl) {
                aRootUrl.path = joined;
                return urlGenerate(aRootUrl);
            }
            return joined;
        }
        exports.join = join;
        /**
         * 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 = ".";
            }
            aRoot = aRoot.replace(/\/$/, '');
            // 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;
                }
                // 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;
                }
                ++level;
            }
            // 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;
        /**
         * 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) {
            return '$' + aStr;
        }
        exports.toSetString = toSetString;
        function fromSetString(aStr) {
            return aStr.substr(1);
        }
        exports.fromSetString = fromSetString;
        /**
         * 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;
            }
            cmp = mappingA.originalLine - mappingB.originalLine;
            if (cmp !== 0) {
                return cmp;
            }
            cmp = mappingA.originalColumn - mappingB.originalColumn;
            if (cmp !== 0 || onlyCompareOriginal) {
                return cmp;
            }
            cmp = mappingA.generatedColumn - mappingB.generatedColumn;
            if (cmp !== 0) {
                return cmp;
            }
            cmp = mappingA.generatedLine - mappingB.generatedLine;
            if (cmp !== 0) {
                return cmp;
            }
            return mappingA.name - mappingB.name;
        }
        ;
        exports.compareByOriginalPositions = compareByOriginalPositions;
        /**
         * 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;
            }
            cmp = mappingA.generatedColumn - mappingB.generatedColumn;
            if (cmp !== 0 || onlyCompareGenerated) {
                return cmp;
            }
            cmp = mappingA.source - mappingB.source;
            if (cmp !== 0) {
                return cmp;
            }
            cmp = mappingA.originalLine - mappingB.originalLine;
            if (cmp !== 0) {
                return cmp;
            }
            cmp = mappingA.originalColumn - mappingB.originalColumn;
            if (cmp !== 0) {
                return cmp;
            }
            return mappingA.name - mappingB.name;
        }
        ;
        exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
        function strcmp(aStr1, aStr2) {
            if (aStr1 === aStr2) {
                return 0;
            }
            if (aStr1 > aStr2) {
                return 1;
            }
            return -1;
        }
        /**
         * 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;
            }
            cmp = mappingA.generatedColumn - mappingB.generatedColumn;
            if (cmp !== 0) {
                return cmp;
            }
            cmp = strcmp(mappingA.source, mappingB.source);
            if (cmp !== 0) {
                return cmp;
            }
            cmp = mappingA.originalLine - mappingB.originalLine;
            if (cmp !== 0) {
                return cmp;
            }
            cmp = mappingA.originalColumn - mappingB.originalColumn;
            if (cmp !== 0) {
                return cmp;
            }
            return strcmp(mappingA.name, mappingB.name);
        }
        ;
        exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
    });
}
,
/* spawn-sync/index */ function _(require, module, exports) {
    module.exports = require('child_process').spawnSync;
    if (!module.exports) {
        throw new Error('spawnSync not supported by this version of node. Please upgrade to at least node@6');
    }
}
,
/* sshpk/lib/algs */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algInfo = {
        'dsa': {
            parts: ['p', 'q', 'g', 'y'],
            sizePart: 'p'
        },
        'rsa': {
            parts: ['e', 'n'],
            sizePart: 'n'
        },
        'ecdsa': {
            parts: ['curve', 'Q'],
            sizePart: 'Q'
        },
        'ed25519': {
            parts: ['A'],
            sizePart: 'A'
        }
    };
    algInfo['curve25519'] = algInfo['ed25519'];
    var algPrivInfo = {
        'dsa': {
            parts: ['p', 'q', 'g', 'y', 'x']
        },
        'rsa': {
            parts: ['n', 'e', 'd', 'iqmp', 'p', 'q']
        },
        'ecdsa': {
            parts: ['curve', 'Q', 'd']
        },
        'ed25519': {
            parts: ['A', 'k']
        }
    };
    algPrivInfo['curve25519'] = algPrivInfo['ed25519'];
    var hashAlgs = {
        'md5': true,
        'sha1': true,
        'sha256': true,
        'sha384': true,
        'sha512': true
    };
    /*
     * Taken from
     * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf
     */
    var curves = {
        'nistp256': {
            size: 256,
            pkcs8oid: '1.2.840.10045.3.1.7',
            p: Buffer.from(('00' +
                'ffffffff 00000001 00000000 00000000' +
                '00000000 ffffffff ffffffff ffffffff').
                replace(/ /g, ''), 'hex'),
            a: Buffer.from(('00' +
                'FFFFFFFF 00000001 00000000 00000000' +
                '00000000 FFFFFFFF FFFFFFFF FFFFFFFC').
                replace(/ /g, ''), 'hex'),
            b: Buffer.from(('5ac635d8 aa3a93e7 b3ebbd55 769886bc' +
                '651d06b0 cc53b0f6 3bce3c3e 27d2604b').
                replace(/ /g, ''), 'hex'),
            s: Buffer.from(('00' +
                'c49d3608 86e70493 6a6678e1 139d26b7' +
                '819f7e90').
                replace(/ /g, ''), 'hex'),
            n: Buffer.from(('00' +
                'ffffffff 00000000 ffffffff ffffffff' +
                'bce6faad a7179e84 f3b9cac2 fc632551').
                replace(/ /g, ''), 'hex'),
            G: Buffer.from(('04' +
                '6b17d1f2 e12c4247 f8bce6e5 63a440f2' +
                '77037d81 2deb33a0 f4a13945 d898c296' +
                '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' +
                '2bce3357 6b315ece cbb64068 37bf51f5').
                replace(/ /g, ''), 'hex')
        },
        'nistp384': {
            size: 384,
            pkcs8oid: '1.3.132.0.34',
            p: Buffer.from(('00' +
                'ffffffff ffffffff ffffffff ffffffff' +
                'ffffffff ffffffff ffffffff fffffffe' +
                'ffffffff 00000000 00000000 ffffffff').
                replace(/ /g, ''), 'hex'),
            a: Buffer.from(('00' +
                'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
                'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' +
                'FFFFFFFF 00000000 00000000 FFFFFFFC').
                replace(/ /g, ''), 'hex'),
            b: Buffer.from(('b3312fa7 e23ee7e4 988e056b e3f82d19' +
                '181d9c6e fe814112 0314088f 5013875a' +
                'c656398d 8a2ed19d 2a85c8ed d3ec2aef').
                replace(/ /g, ''), 'hex'),
            s: Buffer.from(('00' +
                'a335926a a319a27a 1d00896a 6773a482' +
                '7acdac73').
                replace(/ /g, ''), 'hex'),
            n: Buffer.from(('00' +
                'ffffffff ffffffff ffffffff ffffffff' +
                'ffffffff ffffffff c7634d81 f4372ddf' +
                '581a0db2 48b0a77a ecec196a ccc52973').
                replace(/ /g, ''), 'hex'),
            G: Buffer.from(('04' +
                'aa87ca22 be8b0537 8eb1c71e f320ad74' +
                '6e1d3b62 8ba79b98 59f741e0 82542a38' +
                '5502f25d bf55296c 3a545e38 72760ab7' +
                '3617de4a 96262c6f 5d9e98bf 9292dc29' +
                'f8f41dbd 289a147c e9da3113 b5f0b8c0' +
                '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f').
                replace(/ /g, ''), 'hex')
        },
        'nistp521': {
            size: 521,
            pkcs8oid: '1.3.132.0.35',
            p: Buffer.from(('01ffffff ffffffff ffffffff ffffffff' +
                'ffffffff ffffffff ffffffff ffffffff' +
                'ffffffff ffffffff ffffffff ffffffff' +
                'ffffffff ffffffff ffffffff ffffffff' +
                'ffff').replace(/ /g, ''), 'hex'),
            a: Buffer.from(('01FF' +
                'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
                'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
                'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
                'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC').
                replace(/ /g, ''), 'hex'),
            b: Buffer.from(('51' +
                '953eb961 8e1c9a1f 929a21a0 b68540ee' +
                'a2da725b 99b315f3 b8b48991 8ef109e1' +
                '56193951 ec7e937b 1652c0bd 3bb1bf07' +
                '3573df88 3d2c34f1 ef451fd4 6b503f00').
                replace(/ /g, ''), 'hex'),
            s: Buffer.from(('00' +
                'd09e8800 291cb853 96cc6717 393284aa' +
                'a0da64ba').replace(/ /g, ''), 'hex'),
            n: Buffer.from(('01ff' +
                'ffffffff ffffffff ffffffff ffffffff' +
                'ffffffff ffffffff ffffffff fffffffa' +
                '51868783 bf2f966b 7fcc0148 f709a5d0' +
                '3bb5c9b8 899c47ae bb6fb71e 91386409').
                replace(/ /g, ''), 'hex'),
            G: Buffer.from(('04' +
                '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' +
                '9c648139 053fb521 f828af60 6b4d3dba' +
                'a14b5e77 efe75928 fe1dc127 a2ffa8de' +
                '3348b3c1 856a429b f97e7e31 c2e5bd66' +
                '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' +
                '98f54449 579b4468 17afbd17 273e662c' +
                '97ee7299 5ef42640 c550b901 3fad0761' +
                '353c7086 a272c240 88be9476 9fd16650').
                replace(/ /g, ''), 'hex')
        }
    };
    module.exports = {
        info: algInfo,
        privInfo: algPrivInfo,
        hashAlgs: hashAlgs,
        curves: curves
    };
}
,
/* sshpk/lib/certificate */ function _(require, module, exports) {
    // Copyright 2016 Joyent, Inc.
    module.exports = Certificate;
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ./algs */;
    var crypto = require('crypto');
    var Fingerprint = require(336) /* ./fingerprint */;
    var Signature = require(352) /* ./signature */;
    var errs = require(335) /* ./errors */;
    var util = require('util');
    var utils = require(354) /* ./utils */;
    var Key = require(350) /* ./key */;
    var PrivateKey = require(351) /* ./private-key */;
    var Identity = require(348) /* ./identity */;
    var formats = {};
    formats['openssh'] = require(339) /* ./formats/openssh-cert */;
    formats['x509'] = require(347) /* ./formats/x509 */;
    formats['pem'] = require(346) /* ./formats/x509-pem */;
    var CertificateParseError = errs.CertificateParseError;
    var InvalidAlgorithmError = errs.InvalidAlgorithmError;
    function Certificate(opts) {
        assert.object(opts, 'options');
        assert.arrayOfObject(opts.subjects, 'options.subjects');
        utils.assertCompatible(opts.subjects[0], Identity, [1, 0], 'options.subjects');
        utils.assertCompatible(opts.subjectKey, Key, [1, 0], 'options.subjectKey');
        utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer');
        if (opts.issuerKey !== undefined) {
            utils.assertCompatible(opts.issuerKey, Key, [1, 0], 'options.issuerKey');
        }
        assert.object(opts.signatures, 'options.signatures');
        assert.buffer(opts.serial, 'options.serial');
        assert.date(opts.validFrom, 'options.validFrom');
        assert.date(opts.validUntil, 'optons.validUntil');
        assert.optionalArrayOfString(opts.purposes, 'options.purposes');
        this._hashCache = {};
        this.subjects = opts.subjects;
        this.issuer = opts.issuer;
        this.subjectKey = opts.subjectKey;
        this.issuerKey = opts.issuerKey;
        this.signatures = opts.signatures;
        this.serial = opts.serial;
        this.validFrom = opts.validFrom;
        this.validUntil = opts.validUntil;
        this.purposes = opts.purposes;
    }
    Certificate.formats = formats;
    Certificate.prototype.toBuffer = function (format, options) {
        if (format === undefined)
            format = 'x509';
        assert.string(format, 'format');
        assert.object(formats[format], 'formats[format]');
        assert.optionalObject(options, 'options');
        return (formats[format].write(this, options));
    };
    Certificate.prototype.toString = function (format, options) {
        if (format === undefined)
            format = 'pem';
        return (this.toBuffer(format, options).toString());
    };
    Certificate.prototype.fingerprint = function (algo) {
        if (algo === undefined)
            algo = 'sha256';
        assert.string(algo, 'algorithm');
        var opts = {
            type: 'certificate',
            hash: this.hash(algo),
            algorithm: algo
        };
        return (new Fingerprint(opts));
    };
    Certificate.prototype.hash = function (algo) {
        assert.string(algo, 'algorithm');
        algo = algo.toLowerCase();
        if (algs.hashAlgs[algo] === undefined)
            throw (new InvalidAlgorithmError(algo));
        if (this._hashCache[algo])
            return (this._hashCache[algo]);
        var hash = crypto.createHash(algo).
            update(this.toBuffer('x509')).digest();
        this._hashCache[algo] = hash;
        return (hash);
    };
    Certificate.prototype.isExpired = function (when) {
        if (when === undefined)
            when = new Date();
        return (!((when.getTime() >= this.validFrom.getTime()) &&
            (when.getTime() < this.validUntil.getTime())));
    };
    Certificate.prototype.isSignedBy = function (issuerCert) {
        utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer');
        if (!this.issuer.equals(issuerCert.subjects[0]))
            return (false);
        if (this.issuer.purposes && this.issuer.purposes.length > 0 &&
            this.issuer.purposes.indexOf('ca') === -1) {
            return (false);
        }
        return (this.isSignedByKey(issuerCert.subjectKey));
    };
    Certificate.prototype.isSignedByKey = function (issuerKey) {
        utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey');
        if (this.issuerKey !== undefined) {
            return (this.issuerKey.
                fingerprint('sha512').matches(issuerKey));
        }
        var fmt = Object.keys(this.signatures)[0];
        var valid = formats[fmt].verify(this, issuerKey);
        if (valid)
            this.issuerKey = issuerKey;
        return (valid);
    };
    Certificate.prototype.signWith = function (key) {
        utils.assertCompatible(key, PrivateKey, [1, 2], 'key');
        var fmts = Object.keys(formats);
        var didOne = false;
        for (var i = 0; i < fmts.length; ++i) {
            if (fmts[i] !== 'pem') {
                var ret = formats[fmts[i]].sign(this, key);
                if (ret === true)
                    didOne = true;
            }
        }
        if (!didOne) {
            throw (new Error('Failed to sign the certificate for any ' +
                'available certificate formats'));
        }
    };
    Certificate.createSelfSigned = function (subjectOrSubjects, key, options) {
        var subjects;
        if (Array.isArray(subjectOrSubjects))
            subjects = subjectOrSubjects;
        else
            subjects = [subjectOrSubjects];
        assert.arrayOfObject(subjects);
        subjects.forEach(function (subject) {
            utils.assertCompatible(subject, Identity, [1, 0], 'subject');
        });
        utils.assertCompatible(key, PrivateKey, [1, 2], 'private key');
        assert.optionalObject(options, 'options');
        if (options === undefined)
            options = {};
        assert.optionalObject(options.validFrom, 'options.validFrom');
        assert.optionalObject(options.validUntil, 'options.validUntil');
        var validFrom = options.validFrom;
        var validUntil = options.validUntil;
        if (validFrom === undefined)
            validFrom = new Date();
        if (validUntil === undefined) {
            assert.optionalNumber(options.lifetime, 'options.lifetime');
            var lifetime = options.lifetime;
            if (lifetime === undefined)
                lifetime = 10 * 365 * 24 * 3600;
            validUntil = new Date();
            validUntil.setTime(validUntil.getTime() + lifetime * 1000);
        }
        assert.optionalBuffer(options.serial, 'options.serial');
        var serial = options.serial;
        if (serial === undefined)
            serial = Buffer.from('0000000000000001', 'hex');
        var purposes = options.purposes;
        if (purposes === undefined)
            purposes = [];
        if (purposes.indexOf('signature') === -1)
            purposes.push('signature');
        /* Self-signed certs are always CAs. */
        if (purposes.indexOf('ca') === -1)
            purposes.push('ca');
        if (purposes.indexOf('crl') === -1)
            purposes.push('crl');
        /*
         * If we weren't explicitly given any other purposes, do the sensible
         * thing and add some basic ones depending on the subject type.
         */
        if (purposes.length <= 3) {
            var hostSubjects = subjects.filter(function (subject) {
                return (subject.type === 'host');
            });
            var userSubjects = subjects.filter(function (subject) {
                return (subject.type === 'user');
            });
            if (hostSubjects.length > 0) {
                if (purposes.indexOf('serverAuth') === -1)
                    purposes.push('serverAuth');
            }
            if (userSubjects.length > 0) {
                if (purposes.indexOf('clientAuth') === -1)
                    purposes.push('clientAuth');
            }
            if (userSubjects.length > 0 || hostSubjects.length > 0) {
                if (purposes.indexOf('keyAgreement') === -1)
                    purposes.push('keyAgreement');
                if (key.type === 'rsa' &&
                    purposes.indexOf('encryption') === -1)
                    purposes.push('encryption');
            }
        }
        var cert = new Certificate({
            subjects: subjects,
            issuer: subjects[0],
            subjectKey: key.toPublic(),
            issuerKey: key.toPublic(),
            signatures: {},
            serial: serial,
            validFrom: validFrom,
            validUntil: validUntil,
            purposes: purposes
        });
        cert.signWith(key);
        return (cert);
    };
    Certificate.create =
        function (subjectOrSubjects, key, issuer, issuerKey, options) {
            var subjects;
            if (Array.isArray(subjectOrSubjects))
                subjects = subjectOrSubjects;
            else
                subjects = [subjectOrSubjects];
            assert.arrayOfObject(subjects);
            subjects.forEach(function (subject) {
                utils.assertCompatible(subject, Identity, [1, 0], 'subject');
            });
            utils.assertCompatible(key, Key, [1, 0], 'key');
            if (PrivateKey.isPrivateKey(key))
                key = key.toPublic();
            utils.assertCompatible(issuer, Identity, [1, 0], 'issuer');
            utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key');
            assert.optionalObject(options, 'options');
            if (options === undefined)
                options = {};
            assert.optionalObject(options.validFrom, 'options.validFrom');
            assert.optionalObject(options.validUntil, 'options.validUntil');
            var validFrom = options.validFrom;
            var validUntil = options.validUntil;
            if (validFrom === undefined)
                validFrom = new Date();
            if (validUntil === undefined) {
                assert.optionalNumber(options.lifetime, 'options.lifetime');
                var lifetime = options.lifetime;
                if (lifetime === undefined)
                    lifetime = 10 * 365 * 24 * 3600;
                validUntil = new Date();
                validUntil.setTime(validUntil.getTime() + lifetime * 1000);
            }
            assert.optionalBuffer(options.serial, 'options.serial');
            var serial = options.serial;
            if (serial === undefined)
                serial = Buffer.from('0000000000000001', 'hex');
            var purposes = options.purposes;
            if (purposes === undefined)
                purposes = [];
            if (purposes.indexOf('signature') === -1)
                purposes.push('signature');
            if (options.ca === true) {
                if (purposes.indexOf('ca') === -1)
                    purposes.push('ca');
                if (purposes.indexOf('crl') === -1)
                    purposes.push('crl');
            }
            var hostSubjects = subjects.filter(function (subject) {
                return (subject.type === 'host');
            });
            var userSubjects = subjects.filter(function (subject) {
                return (subject.type === 'user');
            });
            if (hostSubjects.length > 0) {
                if (purposes.indexOf('serverAuth') === -1)
                    purposes.push('serverAuth');
            }
            if (userSubjects.length > 0) {
                if (purposes.indexOf('clientAuth') === -1)
                    purposes.push('clientAuth');
            }
            if (userSubjects.length > 0 || hostSubjects.length > 0) {
                if (purposes.indexOf('keyAgreement') === -1)
                    purposes.push('keyAgreement');
                if (key.type === 'rsa' &&
                    purposes.indexOf('encryption') === -1)
                    purposes.push('encryption');
            }
            var cert = new Certificate({
                subjects: subjects,
                issuer: issuer,
                subjectKey: key,
                issuerKey: issuerKey.toPublic(),
                signatures: {},
                serial: serial,
                validFrom: validFrom,
                validUntil: validUntil,
                purposes: purposes
            });
            cert.signWith(issuerKey);
            return (cert);
        };
    Certificate.parse = function (data, format, options) {
        if (typeof (data) !== 'string')
            assert.buffer(data, 'data');
        if (format === undefined)
            format = 'auto';
        assert.string(format, 'format');
        if (typeof (options) === 'string')
            options = { filename: options };
        assert.optionalObject(options, 'options');
        if (options === undefined)
            options = {};
        assert.optionalString(options.filename, 'options.filename');
        if (options.filename === undefined)
            options.filename = '(unnamed)';
        assert.object(formats[format], 'formats[format]');
        try {
            var k = formats[format].read(data, options);
            return (k);
        }
        catch (e) {
            throw (new CertificateParseError(options.filename, format, e));
        }
    };
    Certificate.isCertificate = function (obj, ver) {
        return (utils.isCompatible(obj, Certificate, ver));
    };
    /*
     * API versions for Certificate:
     * [1,0] -- initial ver
     */
    Certificate.prototype._sshpkApiVersion = [1, 0];
    Certificate._oldVersionDetect = function (obj) {
        return ([1, 0]);
    };
}
,
/* sshpk/lib/dhe */ function _(require, module, exports) {
    // Copyright 2017 Joyent, Inc.
    module.exports = {
        DiffieHellman: DiffieHellman,
        generateECDSA: generateECDSA,
        generateED25519: generateED25519
    };
    var assert = require(53) /* assert-plus */;
    var crypto = require('crypto');
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ./algs */;
    var utils = require(354) /* ./utils */;
    var nacl;
    var Key = require(350) /* ./key */;
    var PrivateKey = require(351) /* ./private-key */;
    var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined);
    var ecdh, ec, jsbn;
    function DiffieHellman(key) {
        utils.assertCompatible(key, Key, [1, 4], 'key');
        this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]);
        this._algo = key.type;
        this._curve = key.curve;
        this._key = key;
        if (key.type === 'dsa') {
            if (!CRYPTO_HAVE_ECDH) {
                throw (new Error('Due to bugs in the node 0.10 ' +
                    'crypto API, node 0.12.x or later is required ' +
                    'to use DH'));
            }
            this._dh = crypto.createDiffieHellman(key.part.p.data, undefined, key.part.g.data, undefined);
            this._p = key.part.p;
            this._g = key.part.g;
            if (this._isPriv)
                this._dh.setPrivateKey(key.part.x.data);
            this._dh.setPublicKey(key.part.y.data);
        }
        else if (key.type === 'ecdsa') {
            if (!CRYPTO_HAVE_ECDH) {
                if (ecdh === undefined)
                    ecdh = require(100) /* ecc-jsbn */;
                if (ec === undefined)
                    ec = require(101) /* ecc-jsbn/lib/ec */;
                if (jsbn === undefined)
                    jsbn = require(155) /* jsbn */.BigInteger;
                this._ecParams = new X9ECParameters(this._curve);
                if (this._isPriv) {
                    this._priv = new ECPrivate(this._ecParams, key.part.d.data);
                }
                return;
            }
            var curve = {
                'nistp256': 'prime256v1',
                'nistp384': 'secp384r1',
                'nistp521': 'secp521r1'
            }[key.curve];
            this._dh = crypto.createECDH(curve);
            if (typeof (this._dh) !== 'object' ||
                typeof (this._dh.setPrivateKey) !== 'function') {
                CRYPTO_HAVE_ECDH = false;
                DiffieHellman.call(this, key);
                return;
            }
            if (this._isPriv)
                this._dh.setPrivateKey(key.part.d.data);
            this._dh.setPublicKey(key.part.Q.data);
        }
        else if (key.type === 'curve25519') {
            if (nacl === undefined)
                nacl = require(366) /* tweetnacl */;
            if (this._isPriv) {
                utils.assertCompatible(key, PrivateKey, [1, 5], 'key');
                this._priv = key.part.k.data;
            }
        }
        else {
            throw (new Error('DH not supported for ' + key.type + ' keys'));
        }
    }
    DiffieHellman.prototype.getPublicKey = function () {
        if (this._isPriv)
            return (this._key.toPublic());
        return (this._key);
    };
    DiffieHellman.prototype.getPrivateKey = function () {
        if (this._isPriv)
            return (this._key);
        else
            return (undefined);
    };
    DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey;
    DiffieHellman.prototype._keyCheck = function (pk, isPub) {
        assert.object(pk, 'key');
        if (!isPub)
            utils.assertCompatible(pk, PrivateKey, [1, 3], 'key');
        utils.assertCompatible(pk, Key, [1, 4], 'key');
        if (pk.type !== this._algo) {
            throw (new Error('A ' + pk.type + ' key cannot be used in ' +
                this._algo + ' Diffie-Hellman'));
        }
        if (pk.curve !== this._curve) {
            throw (new Error('A key from the ' + pk.curve + ' curve ' +
                'cannot be used with a ' + this._curve +
                ' Diffie-Hellman'));
        }
        if (pk.type === 'dsa') {
            assert.deepEqual(pk.part.p, this._p, 'DSA key prime does not match');
            assert.deepEqual(pk.part.g, this._g, 'DSA key generator does not match');
        }
    };
    DiffieHellman.prototype.setKey = function (pk) {
        this._keyCheck(pk);
        if (pk.type === 'dsa') {
            this._dh.setPrivateKey(pk.part.x.data);
            this._dh.setPublicKey(pk.part.y.data);
        }
        else if (pk.type === 'ecdsa') {
            if (CRYPTO_HAVE_ECDH) {
                this._dh.setPrivateKey(pk.part.d.data);
                this._dh.setPublicKey(pk.part.Q.data);
            }
            else {
                this._priv = new ECPrivate(this._ecParams, pk.part.d.data);
            }
        }
        else if (pk.type === 'curve25519') {
            var k = pk.part.k;
            if (!pk.part.k)
                k = pk.part.r;
            this._priv = k.data;
            if (this._priv[0] === 0x00)
                this._priv = this._priv.slice(1);
            this._priv = this._priv.slice(0, 32);
        }
        this._key = pk;
        this._isPriv = true;
    };
    DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey;
    DiffieHellman.prototype.computeSecret = function (otherpk) {
        this._keyCheck(otherpk, true);
        if (!this._isPriv)
            throw (new Error('DH exchange has not been initialized with ' +
                'a private key yet'));
        var pub;
        if (this._algo === 'dsa') {
            return (this._dh.computeSecret(otherpk.part.y.data));
        }
        else if (this._algo === 'ecdsa') {
            if (CRYPTO_HAVE_ECDH) {
                return (this._dh.computeSecret(otherpk.part.Q.data));
            }
            else {
                pub = new ECPublic(this._ecParams, otherpk.part.Q.data);
                return (this._priv.deriveSharedSecret(pub));
            }
        }
        else if (this._algo === 'curve25519') {
            pub = otherpk.part.A.data;
            while (pub[0] === 0x00 && pub.length > 32)
                pub = pub.slice(1);
            var priv = this._priv;
            assert.strictEqual(pub.length, 32);
            assert.strictEqual(priv.length, 32);
            var secret = nacl.box.before(new Uint8Array(pub), new Uint8Array(priv));
            return (Buffer.from(secret));
        }
        throw (new Error('Invalid algorithm: ' + this._algo));
    };
    DiffieHellman.prototype.generateKey = function () {
        var parts = [];
        var priv, pub;
        if (this._algo === 'dsa') {
            this._dh.generateKeys();
            parts.push({ name: 'p', data: this._p.data });
            parts.push({ name: 'q', data: this._key.part.q.data });
            parts.push({ name: 'g', data: this._g.data });
            parts.push({ name: 'y', data: this._dh.getPublicKey() });
            parts.push({ name: 'x', data: this._dh.getPrivateKey() });
            this._key = new PrivateKey({
                type: 'dsa',
                parts: parts
            });
            this._isPriv = true;
            return (this._key);
        }
        else if (this._algo === 'ecdsa') {
            if (CRYPTO_HAVE_ECDH) {
                this._dh.generateKeys();
                parts.push({ name: 'curve',
                    data: Buffer.from(this._curve) });
                parts.push({ name: 'Q', data: this._dh.getPublicKey() });
                parts.push({ name: 'd', data: this._dh.getPrivateKey() });
                this._key = new PrivateKey({
                    type: 'ecdsa',
                    curve: this._curve,
                    parts: parts
                });
                this._isPriv = true;
                return (this._key);
            }
            else {
                var n = this._ecParams.getN();
                var r = new jsbn(crypto.randomBytes(n.bitLength()));
                var n1 = n.subtract(jsbn.ONE);
                priv = r.mod(n1).add(jsbn.ONE);
                pub = this._ecParams.getG().multiply(priv);
                priv = Buffer.from(priv.toByteArray());
                pub = Buffer.from(this._ecParams.getCurve().
                    encodePointHex(pub), 'hex');
                this._priv = new ECPrivate(this._ecParams, priv);
                parts.push({ name: 'curve',
                    data: Buffer.from(this._curve) });
                parts.push({ name: 'Q', data: pub });
                parts.push({ name: 'd', data: priv });
                this._key = new PrivateKey({
                    type: 'ecdsa',
                    curve: this._curve,
                    parts: parts
                });
                this._isPriv = true;
                return (this._key);
            }
        }
        else if (this._algo === 'curve25519') {
            var pair = nacl.box.keyPair();
            priv = Buffer.from(pair.secretKey);
            pub = Buffer.from(pair.publicKey);
            priv = Buffer.concat([priv, pub]);
            assert.strictEqual(priv.length, 64);
            assert.strictEqual(pub.length, 32);
            parts.push({ name: 'A', data: pub });
            parts.push({ name: 'k', data: priv });
            this._key = new PrivateKey({
                type: 'curve25519',
                parts: parts
            });
            this._isPriv = true;
            return (this._key);
        }
        throw (new Error('Invalid algorithm: ' + this._algo));
    };
    DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey;
    /* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */
    function X9ECParameters(name) {
        var params = algs.curves[name];
        assert.object(params);
        var p = new jsbn(params.p);
        var a = new jsbn(params.a);
        var b = new jsbn(params.b);
        var n = new jsbn(params.n);
        var h = jsbn.ONE;
        var curve = new ec.ECCurveFp(p, a, b);
        var G = curve.decodePointHex(params.G.toString('hex'));
        this.curve = curve;
        this.g = G;
        this.n = n;
        this.h = h;
    }
    X9ECParameters.prototype.getCurve = function () { return (this.curve); };
    X9ECParameters.prototype.getG = function () { return (this.g); };
    X9ECParameters.prototype.getN = function () { return (this.n); };
    X9ECParameters.prototype.getH = function () { return (this.h); };
    function ECPublic(params, buffer) {
        this._params = params;
        if (buffer[0] === 0x00)
            buffer = buffer.slice(1);
        this._pub = params.getCurve().decodePointHex(buffer.toString('hex'));
    }
    function ECPrivate(params, buffer) {
        this._params = params;
        this._priv = new jsbn(utils.mpNormalize(buffer));
    }
    ECPrivate.prototype.deriveSharedSecret = function (pubKey) {
        assert.ok(pubKey instanceof ECPublic);
        var S = pubKey._pub.multiply(this._priv);
        return (Buffer.from(S.getX().toBigInteger().toByteArray()));
    };
    function generateED25519() {
        if (nacl === undefined)
            nacl = require(366) /* tweetnacl */;
        var pair = nacl.sign.keyPair();
        var priv = Buffer.from(pair.secretKey);
        var pub = Buffer.from(pair.publicKey);
        assert.strictEqual(priv.length, 64);
        assert.strictEqual(pub.length, 32);
        var parts = [];
        parts.push({ name: 'A', data: pub });
        parts.push({ name: 'k', data: priv.slice(0, 32) });
        var key = new PrivateKey({
            type: 'ed25519',
            parts: parts
        });
        return (key);
    }
    /* Generates a new ECDSA private key on a given curve. */
    function generateECDSA(curve) {
        var parts = [];
        var key;
        if (CRYPTO_HAVE_ECDH) {
            /*
             * Node crypto doesn't expose key generation directly, but the
             * ECDH instances can generate keys. It turns out this just
             * calls into the OpenSSL generic key generator, and we can
             * read its output happily without doing an actual DH. So we
             * use that here.
             */
            var osCurve = {
                'nistp256': 'prime256v1',
                'nistp384': 'secp384r1',
                'nistp521': 'secp521r1'
            }[curve];
            var dh = crypto.createECDH(osCurve);
            dh.generateKeys();
            parts.push({ name: 'curve',
                data: Buffer.from(curve) });
            parts.push({ name: 'Q', data: dh.getPublicKey() });
            parts.push({ name: 'd', data: dh.getPrivateKey() });
            key = new PrivateKey({
                type: 'ecdsa',
                curve: curve,
                parts: parts
            });
            return (key);
        }
        else {
            if (ecdh === undefined)
                ecdh = require(100) /* ecc-jsbn */;
            if (ec === undefined)
                ec = require(101) /* ecc-jsbn/lib/ec */;
            if (jsbn === undefined)
                jsbn = require(155) /* jsbn */.BigInteger;
            var ecParams = new X9ECParameters(curve);
            /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */
            var n = ecParams.getN();
            /*
             * The crypto.randomBytes() function can only give us whole
             * bytes, so taking a nod from X9.62, we round up.
             */
            var cByteLen = Math.ceil((n.bitLength() + 64) / 8);
            var c = new jsbn(crypto.randomBytes(cByteLen));
            var n1 = n.subtract(jsbn.ONE);
            var priv = c.mod(n1).add(jsbn.ONE);
            var pub = ecParams.getG().multiply(priv);
            priv = Buffer.from(priv.toByteArray());
            pub = Buffer.from(ecParams.getCurve().
                encodePointHex(pub), 'hex');
            parts.push({ name: 'curve', data: Buffer.from(curve) });
            parts.push({ name: 'Q', data: pub });
            parts.push({ name: 'd', data: priv });
            key = new PrivateKey({
                type: 'ecdsa',
                curve: curve,
                parts: parts
            });
            return (key);
        }
    }
}
,
/* sshpk/lib/ed-compat */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        Verifier: Verifier,
        Signer: Signer
    };
    var nacl;
    var stream = require('stream');
    var util = require('util');
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var Signature = require(352) /* ./signature */;
    function Verifier(key, hashAlgo) {
        if (nacl === undefined)
            nacl = require(366) /* tweetnacl */;
        if (hashAlgo.toLowerCase() !== 'sha512')
            throw (new Error('ED25519 only supports the use of ' +
                'SHA-512 hashes'));
        this.key = key;
        this.chunks = [];
        stream.Writable.call(this, {});
    }
    util.inherits(Verifier, stream.Writable);
    Verifier.prototype._write = function (chunk, enc, cb) {
        this.chunks.push(chunk);
        cb();
    };
    Verifier.prototype.update = function (chunk) {
        if (typeof (chunk) === 'string')
            chunk = Buffer.from(chunk, 'binary');
        this.chunks.push(chunk);
    };
    Verifier.prototype.verify = function (signature, fmt) {
        var sig;
        if (Signature.isSignature(signature, [2, 0])) {
            if (signature.type !== 'ed25519')
                return (false);
            sig = signature.toBuffer('raw');
        }
        else if (typeof (signature) === 'string') {
            sig = Buffer.from(signature, 'base64');
        }
        else if (Signature.isSignature(signature, [1, 0])) {
            throw (new Error('signature was created by too old ' +
                'a version of sshpk and cannot be verified'));
        }
        assert.buffer(sig);
        return (nacl.sign.detached.verify(new Uint8Array(Buffer.concat(this.chunks)), new Uint8Array(sig), new Uint8Array(this.key.part.A.data)));
    };
    function Signer(key, hashAlgo) {
        if (nacl === undefined)
            nacl = require(366) /* tweetnacl */;
        if (hashAlgo.toLowerCase() !== 'sha512')
            throw (new Error('ED25519 only supports the use of ' +
                'SHA-512 hashes'));
        this.key = key;
        this.chunks = [];
        stream.Writable.call(this, {});
    }
    util.inherits(Signer, stream.Writable);
    Signer.prototype._write = function (chunk, enc, cb) {
        this.chunks.push(chunk);
        cb();
    };
    Signer.prototype.update = function (chunk) {
        if (typeof (chunk) === 'string')
            chunk = Buffer.from(chunk, 'binary');
        this.chunks.push(chunk);
    };
    Signer.prototype.sign = function () {
        var sig = nacl.sign.detached(new Uint8Array(Buffer.concat(this.chunks)), new Uint8Array(Buffer.concat([
            this.key.part.k.data, this.key.part.A.data
        ])));
        var sigBuf = Buffer.from(sig);
        var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw');
        sigObj.hashAlgorithm = 'sha512';
        return (sigObj);
    };
}
,
/* sshpk/lib/errors */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    var assert = require(53) /* assert-plus */;
    var util = require('util');
    function FingerprintFormatError(fp, format) {
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, FingerprintFormatError);
        this.name = 'FingerprintFormatError';
        this.fingerprint = fp;
        this.format = format;
        this.message = 'Fingerprint format is not supported, or is invalid: ';
        if (fp !== undefined)
            this.message += ' fingerprint = ' + fp;
        if (format !== undefined)
            this.message += ' format = ' + format;
    }
    util.inherits(FingerprintFormatError, Error);
    function InvalidAlgorithmError(alg) {
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, InvalidAlgorithmError);
        this.name = 'InvalidAlgorithmError';
        this.algorithm = alg;
        this.message = 'Algorithm "' + alg + '" is not supported';
    }
    util.inherits(InvalidAlgorithmError, Error);
    function KeyParseError(name, format, innerErr) {
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, KeyParseError);
        this.name = 'KeyParseError';
        this.format = format;
        this.keyName = name;
        this.innerErr = innerErr;
        this.message = 'Failed to parse ' + name + ' as a valid ' + format +
            ' format key: ' + innerErr.message;
    }
    util.inherits(KeyParseError, Error);
    function SignatureParseError(type, format, innerErr) {
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, SignatureParseError);
        this.name = 'SignatureParseError';
        this.type = type;
        this.format = format;
        this.innerErr = innerErr;
        this.message = 'Failed to parse the given data as a ' + type +
            ' signature in ' + format + ' format: ' + innerErr.message;
    }
    util.inherits(SignatureParseError, Error);
    function CertificateParseError(name, format, innerErr) {
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, CertificateParseError);
        this.name = 'CertificateParseError';
        this.format = format;
        this.certName = name;
        this.innerErr = innerErr;
        this.message = 'Failed to parse ' + name + ' as a valid ' + format +
            ' format certificate: ' + innerErr.message;
    }
    util.inherits(CertificateParseError, Error);
    function KeyEncryptedError(name, format) {
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, KeyEncryptedError);
        this.name = 'KeyEncryptedError';
        this.format = format;
        this.keyName = name;
        this.message = 'The ' + format + ' format key ' + name + ' is ' +
            'encrypted (password-protected), and no passphrase was ' +
            'provided in `options`';
    }
    util.inherits(KeyEncryptedError, Error);
    module.exports = {
        FingerprintFormatError: FingerprintFormatError,
        InvalidAlgorithmError: InvalidAlgorithmError,
        KeyParseError: KeyParseError,
        SignatureParseError: SignatureParseError,
        KeyEncryptedError: KeyEncryptedError,
        CertificateParseError: CertificateParseError
    };
}
,
/* sshpk/lib/fingerprint */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = Fingerprint;
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ./algs */;
    var crypto = require('crypto');
    var errs = require(335) /* ./errors */;
    var Key = require(350) /* ./key */;
    var Certificate = require(332) /* ./certificate */;
    var utils = require(354) /* ./utils */;
    var FingerprintFormatError = errs.FingerprintFormatError;
    var InvalidAlgorithmError = errs.InvalidAlgorithmError;
    function Fingerprint(opts) {
        assert.object(opts, 'options');
        assert.string(opts.type, 'options.type');
        assert.buffer(opts.hash, 'options.hash');
        assert.string(opts.algorithm, 'options.algorithm');
        this.algorithm = opts.algorithm.toLowerCase();
        if (algs.hashAlgs[this.algorithm] !== true)
            throw (new InvalidAlgorithmError(this.algorithm));
        this.hash = opts.hash;
        this.type = opts.type;
    }
    Fingerprint.prototype.toString = function (format) {
        if (format === undefined) {
            if (this.algorithm === 'md5')
                format = 'hex';
            else
                format = 'base64';
        }
        assert.string(format);
        switch (format) {
            case 'hex':
                return (addColons(this.hash.toString('hex')));
            case 'base64':
                return (sshBase64Format(this.algorithm, this.hash.toString('base64')));
            default:
                throw (new FingerprintFormatError(undefined, format));
        }
    };
    Fingerprint.prototype.matches = function (other) {
        assert.object(other, 'key or certificate');
        if (this.type === 'key') {
            utils.assertCompatible(other, Key, [1, 0], 'key');
        }
        else {
            utils.assertCompatible(other, Certificate, [1, 0], 'certificate');
        }
        var theirHash = other.hash(this.algorithm);
        var theirHash2 = crypto.createHash(this.algorithm).
            update(theirHash).digest('base64');
        if (this.hash2 === undefined)
            this.hash2 = crypto.createHash(this.algorithm).
                update(this.hash).digest('base64');
        return (this.hash2 === theirHash2);
    };
    Fingerprint.parse = function (fp, options) {
        assert.string(fp, 'fingerprint');
        var alg, hash, enAlgs;
        if (Array.isArray(options)) {
            enAlgs = options;
            options = {};
        }
        assert.optionalObject(options, 'options');
        if (options === undefined)
            options = {};
        if (options.enAlgs !== undefined)
            enAlgs = options.enAlgs;
        assert.optionalArrayOfString(enAlgs, 'algorithms');
        var parts = fp.split(':');
        if (parts.length == 2) {
            alg = parts[0].toLowerCase();
            /*JSSTYLED*/
            var base64RE = /^[A-Za-z0-9+\/=]+$/;
            if (!base64RE.test(parts[1]))
                throw (new FingerprintFormatError(fp));
            try {
                hash = Buffer.from(parts[1], 'base64');
            }
            catch (e) {
                throw (new FingerprintFormatError(fp));
            }
        }
        else if (parts.length > 2) {
            alg = 'md5';
            if (parts[0].toLowerCase() === 'md5')
                parts = parts.slice(1);
            parts = parts.join('');
            /*JSSTYLED*/
            var md5RE = /^[a-fA-F0-9]+$/;
            if (!md5RE.test(parts))
                throw (new FingerprintFormatError(fp));
            try {
                hash = Buffer.from(parts, 'hex');
            }
            catch (e) {
                throw (new FingerprintFormatError(fp));
            }
        }
        if (alg === undefined)
            throw (new FingerprintFormatError(fp));
        if (algs.hashAlgs[alg] === undefined)
            throw (new InvalidAlgorithmError(alg));
        if (enAlgs !== undefined) {
            enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); });
            if (enAlgs.indexOf(alg) === -1)
                throw (new InvalidAlgorithmError(alg));
        }
        return (new Fingerprint({
            algorithm: alg,
            hash: hash,
            type: options.type || 'key'
        }));
    };
    function addColons(s) {
        /*JSSTYLED*/
        return (s.replace(/(.{2})(?=.)/g, '$1:'));
    }
    function base64Strip(s) {
        /*JSSTYLED*/
        return (s.replace(/=*$/, ''));
    }
    function sshBase64Format(alg, h) {
        return (alg.toUpperCase() + ':' + base64Strip(h));
    }
    Fingerprint.isFingerprint = function (obj, ver) {
        return (utils.isCompatible(obj, Fingerprint, ver));
    };
    /*
     * API versions for Fingerprint:
     * [1,0] -- initial ver
     * [1,1] -- first tagged ver
     */
    Fingerprint.prototype._sshpkApiVersion = [1, 1];
    Fingerprint._oldVersionDetect = function (obj) {
        assert.func(obj.toString);
        assert.func(obj.matches);
        return ([1, 0]);
    };
}
,
/* sshpk/lib/formats/auto */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        read: read,
        write: write
    };
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var pem = require(340) /* ./pem */;
    var ssh = require(345) /* ./ssh */;
    var rfc4253 = require(343) /* ./rfc4253 */;
    var dnssec = require(338) /* ./dnssec */;
    var DNSSEC_PRIVKEY_HEADER_PREFIX = 'Private-key-format: v1';
    function read(buf, options) {
        if (typeof (buf) === 'string') {
            if (buf.trim().match(/^[-]+[ ]*BEGIN/))
                return (pem.read(buf, options));
            if (buf.match(/^\s*ssh-[a-z]/))
                return (ssh.read(buf, options));
            if (buf.match(/^\s*ecdsa-/))
                return (ssh.read(buf, options));
            if (findDNSSECHeader(buf))
                return (dnssec.read(buf, options));
            buf = Buffer.from(buf, 'binary');
        }
        else {
            assert.buffer(buf);
            if (findPEMHeader(buf))
                return (pem.read(buf, options));
            if (findSSHHeader(buf))
                return (ssh.read(buf, options));
            if (findDNSSECHeader(buf))
                return (dnssec.read(buf, options));
        }
        if (buf.readUInt32BE(0) < buf.length)
            return (rfc4253.read(buf, options));
        throw (new Error('Failed to auto-detect format of key'));
    }
    function findSSHHeader(buf) {
        var offset = 0;
        while (offset < buf.length &&
            (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
            ++offset;
        if (offset + 4 <= buf.length &&
            buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
            return (true);
        if (offset + 6 <= buf.length &&
            buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
            return (true);
        return (false);
    }
    function findPEMHeader(buf) {
        var offset = 0;
        while (offset < buf.length &&
            (buf[offset] === 32 || buf[offset] === 10))
            ++offset;
        if (buf[offset] !== 45)
            return (false);
        while (offset < buf.length &&
            (buf[offset] === 45))
            ++offset;
        while (offset < buf.length &&
            (buf[offset] === 32))
            ++offset;
        if (offset + 5 > buf.length ||
            buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
            return (false);
        return (true);
    }
    function findDNSSECHeader(buf) {
        // private case first
        if (buf.length <= DNSSEC_PRIVKEY_HEADER_PREFIX.length)
            return (false);
        var headerCheck = buf.slice(0, DNSSEC_PRIVKEY_HEADER_PREFIX.length);
        if (headerCheck.toString('ascii') === DNSSEC_PRIVKEY_HEADER_PREFIX)
            return (true);
        // public-key RFC3110 ?
        // 'domain.com. IN KEY ...' or 'domain.com. IN DNSKEY ...'
        // skip any comment-lines
        if (typeof (buf) !== 'string') {
            buf = buf.toString('ascii');
        }
        var lines = buf.split('\n');
        var line = 0;
        /* JSSTYLED */
        while (lines[line].match(/^\;/))
            line++;
        if (lines[line].toString('ascii').match(/\. IN KEY /))
            return (true);
        if (lines[line].toString('ascii').match(/\. IN DNSKEY /))
            return (true);
        return (false);
    }
    function write(key, options) {
        throw (new Error('"auto" format cannot be used for writing'));
    }
}
,
/* sshpk/lib/formats/dnssec */ function _(require, module, exports) {
    // Copyright 2017 Joyent, Inc.
    module.exports = {
        read: read,
        write: write
    };
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var utils = require(354) /* ../utils */;
    var SSHBuffer = require(353) /* ../ssh-buffer */;
    var Dhe = require(333) /* ../dhe */;
    var supportedAlgos = {
        'rsa-sha1': 5,
        'rsa-sha256': 8,
        'rsa-sha512': 10,
        'ecdsa-p256-sha256': 13,
        'ecdsa-p384-sha384': 14
        /*
         * ed25519 is hypothetically supported with id 15
         * but the common tools available don't appear to be
         * capable of generating/using ed25519 keys
         */
    };
    var supportedAlgosById = {};
    Object.keys(supportedAlgos).forEach(function (k) {
        supportedAlgosById[supportedAlgos[k]] = k.toUpperCase();
    });
    function read(buf, options) {
        if (typeof (buf) !== 'string') {
            assert.buffer(buf, 'buf');
            buf = buf.toString('ascii');
        }
        var lines = buf.split('\n');
        if (lines[0].match(/^Private-key-format\: v1/)) {
            var algElems = lines[1].split(' ');
            var algoNum = parseInt(algElems[1], 10);
            var algoName = algElems[2];
            if (!supportedAlgosById[algoNum])
                throw (new Error('Unsupported algorithm: ' + algoName));
            return (readDNSSECPrivateKey(algoNum, lines.slice(2)));
        }
        // skip any comment-lines
        var line = 0;
        /* JSSTYLED */
        while (lines[line].match(/^\;/))
            line++;
        // we should now have *one single* line left with our KEY on it.
        if ((lines[line].match(/\. IN KEY /) ||
            lines[line].match(/\. IN DNSKEY /)) && lines[line + 1].length === 0) {
            return (readRFC3110(lines[line]));
        }
        throw (new Error('Cannot parse dnssec key'));
    }
    function readRFC3110(keyString) {
        var elems = keyString.split(' ');
        //unused var flags = parseInt(elems[3], 10);
        //unused var protocol = parseInt(elems[4], 10);
        var algorithm = parseInt(elems[5], 10);
        if (!supportedAlgosById[algorithm])
            throw (new Error('Unsupported algorithm: ' + algorithm));
        var base64key = elems.slice(6, elems.length).join();
        var keyBuffer = Buffer.from(base64key, 'base64');
        if (supportedAlgosById[algorithm].match(/^RSA-/)) {
            // join the rest of the body into a single base64-blob
            var publicExponentLen = keyBuffer.readUInt8(0);
            if (publicExponentLen != 3 && publicExponentLen != 1)
                throw (new Error('Cannot parse dnssec key: ' +
                    'unsupported exponent length'));
            var publicExponent = keyBuffer.slice(1, publicExponentLen + 1);
            publicExponent = utils.mpNormalize(publicExponent);
            var modulus = keyBuffer.slice(1 + publicExponentLen);
            modulus = utils.mpNormalize(modulus);
            // now, make the key
            var rsaKey = {
                type: 'rsa',
                parts: []
            };
            rsaKey.parts.push({ name: 'e', data: publicExponent });
            rsaKey.parts.push({ name: 'n', data: modulus });
            return (new Key(rsaKey));
        }
        if (supportedAlgosById[algorithm] === 'ECDSA-P384-SHA384' ||
            supportedAlgosById[algorithm] === 'ECDSA-P256-SHA256') {
            var curve = 'nistp384';
            var size = 384;
            if (supportedAlgosById[algorithm].match(/^ECDSA-P256-SHA256/)) {
                curve = 'nistp256';
                size = 256;
            }
            var ecdsaKey = {
                type: 'ecdsa',
                curve: curve,
                size: size,
                parts: [
                    { name: 'curve', data: Buffer.from(curve) },
                    { name: 'Q', data: utils.ecNormalize(keyBuffer) }
                ]
            };
            return (new Key(ecdsaKey));
        }
        throw (new Error('Unsupported algorithm: ' +
            supportedAlgosById[algorithm]));
    }
    function elementToBuf(e) {
        return (Buffer.from(e.split(' ')[1], 'base64'));
    }
    function readDNSSECRSAPrivateKey(elements) {
        var rsaParams = {};
        elements.forEach(function (element) {
            if (element.split(' ')[0] === 'Modulus:')
                rsaParams['n'] = elementToBuf(element);
            else if (element.split(' ')[0] === 'PublicExponent:')
                rsaParams['e'] = elementToBuf(element);
            else if (element.split(' ')[0] === 'PrivateExponent:')
                rsaParams['d'] = elementToBuf(element);
            else if (element.split(' ')[0] === 'Prime1:')
                rsaParams['p'] = elementToBuf(element);
            else if (element.split(' ')[0] === 'Prime2:')
                rsaParams['q'] = elementToBuf(element);
            else if (element.split(' ')[0] === 'Exponent1:')
                rsaParams['dmodp'] = elementToBuf(element);
            else if (element.split(' ')[0] === 'Exponent2:')
                rsaParams['dmodq'] = elementToBuf(element);
            else if (element.split(' ')[0] === 'Coefficient:')
                rsaParams['iqmp'] = elementToBuf(element);
        });
        // now, make the key
        var key = {
            type: 'rsa',
            parts: [
                { name: 'e', data: utils.mpNormalize(rsaParams['e']) },
                { name: 'n', data: utils.mpNormalize(rsaParams['n']) },
                { name: 'd', data: utils.mpNormalize(rsaParams['d']) },
                { name: 'p', data: utils.mpNormalize(rsaParams['p']) },
                { name: 'q', data: utils.mpNormalize(rsaParams['q']) },
                { name: 'dmodp',
                    data: utils.mpNormalize(rsaParams['dmodp']) },
                { name: 'dmodq',
                    data: utils.mpNormalize(rsaParams['dmodq']) },
                { name: 'iqmp',
                    data: utils.mpNormalize(rsaParams['iqmp']) }
            ]
        };
        return (new PrivateKey(key));
    }
    function readDNSSECPrivateKey(alg, elements) {
        if (supportedAlgosById[alg].match(/^RSA-/)) {
            return (readDNSSECRSAPrivateKey(elements));
        }
        if (supportedAlgosById[alg] === 'ECDSA-P384-SHA384' ||
            supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
            var d = Buffer.from(elements[0].split(' ')[1], 'base64');
            var curve = 'nistp384';
            var size = 384;
            if (supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
                curve = 'nistp256';
                size = 256;
            }
            // DNSSEC generates the public-key on the fly (go calculate it)
            var publicKey = utils.publicFromPrivateECDSA(curve, d);
            var Q = publicKey.part['Q'].data;
            var ecdsaKey = {
                type: 'ecdsa',
                curve: curve,
                size: size,
                parts: [
                    { name: 'curve', data: Buffer.from(curve) },
                    { name: 'd', data: d },
                    { name: 'Q', data: Q }
                ]
            };
            return (new PrivateKey(ecdsaKey));
        }
        throw (new Error('Unsupported algorithm: ' + supportedAlgosById[alg]));
    }
    function dnssecTimestamp(date) {
        var year = date.getFullYear() + ''; //stringify
        var month = (date.getMonth() + 1);
        var timestampStr = year + month + date.getUTCDate();
        timestampStr += '' + date.getUTCHours() + date.getUTCMinutes();
        timestampStr += date.getUTCSeconds();
        return (timestampStr);
    }
    function rsaAlgFromOptions(opts) {
        if (!opts || !opts.hashAlgo || opts.hashAlgo === 'sha1')
            return ('5 (RSASHA1)');
        else if (opts.hashAlgo === 'sha256')
            return ('8 (RSASHA256)');
        else if (opts.hashAlgo === 'sha512')
            return ('10 (RSASHA512)');
        else
            throw (new Error('Unknown or unsupported hash: ' +
                opts.hashAlgo));
    }
    function writeRSA(key, options) {
        // if we're missing parts, add them.
        if (!key.part.dmodp || !key.part.dmodq) {
            utils.addRSAMissing(key);
        }
        var out = '';
        out += 'Private-key-format: v1.3\n';
        out += 'Algorithm: ' + rsaAlgFromOptions(options) + '\n';
        var n = utils.mpDenormalize(key.part['n'].data);
        out += 'Modulus: ' + n.toString('base64') + '\n';
        var e = utils.mpDenormalize(key.part['e'].data);
        out += 'PublicExponent: ' + e.toString('base64') + '\n';
        var d = utils.mpDenormalize(key.part['d'].data);
        out += 'PrivateExponent: ' + d.toString('base64') + '\n';
        var p = utils.mpDenormalize(key.part['p'].data);
        out += 'Prime1: ' + p.toString('base64') + '\n';
        var q = utils.mpDenormalize(key.part['q'].data);
        out += 'Prime2: ' + q.toString('base64') + '\n';
        var dmodp = utils.mpDenormalize(key.part['dmodp'].data);
        out += 'Exponent1: ' + dmodp.toString('base64') + '\n';
        var dmodq = utils.mpDenormalize(key.part['dmodq'].data);
        out += 'Exponent2: ' + dmodq.toString('base64') + '\n';
        var iqmp = utils.mpDenormalize(key.part['iqmp'].data);
        out += 'Coefficient: ' + iqmp.toString('base64') + '\n';
        // Assume that we're valid as-of now
        var timestamp = new Date();
        out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
        out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
        out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
        return (Buffer.from(out, 'ascii'));
    }
    function writeECDSA(key, options) {
        var out = '';
        out += 'Private-key-format: v1.3\n';
        if (key.curve === 'nistp256') {
            out += 'Algorithm: 13 (ECDSAP256SHA256)\n';
        }
        else if (key.curve === 'nistp384') {
            out += 'Algorithm: 14 (ECDSAP384SHA384)\n';
        }
        else {
            throw (new Error('Unsupported curve'));
        }
        var base64Key = key.part['d'].data.toString('base64');
        out += 'PrivateKey: ' + base64Key + '\n';
        // Assume that we're valid as-of now
        var timestamp = new Date();
        out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
        out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
        out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
        return (Buffer.from(out, 'ascii'));
    }
    function write(key, options) {
        if (PrivateKey.isPrivateKey(key)) {
            if (key.type === 'rsa') {
                return (writeRSA(key, options));
            }
            else if (key.type === 'ecdsa') {
                return (writeECDSA(key, options));
            }
            else {
                throw (new Error('Unsupported algorithm: ' + key.type));
            }
        }
        else if (Key.isKey(key)) {
            /*
             * RFC3110 requires a keyname, and a keytype, which we
             * don't really have a mechanism for specifying such
             * additional metadata.
             */
            throw (new Error('Format "dnssec" only supports ' +
                'writing private keys'));
        }
        else {
            throw (new Error('key is not a Key or PrivateKey'));
        }
    }
}
,
/* sshpk/lib/formats/openssh-cert */ function _(require, module, exports) {
    // Copyright 2017 Joyent, Inc.
    module.exports = {
        read: read,
        verify: verify,
        sign: sign,
        signAsync: signAsync,
        write: write,
        /* Internal private API */
        fromBuffer: fromBuffer,
        toBuffer: toBuffer
    };
    var assert = require(53) /* assert-plus */;
    var SSHBuffer = require(353) /* ../ssh-buffer */;
    var crypto = require('crypto');
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var Identity = require(348) /* ../identity */;
    var rfc4253 = require(343) /* ./rfc4253 */;
    var Signature = require(352) /* ../signature */;
    var utils = require(354) /* ../utils */;
    var Certificate = require(332) /* ../certificate */;
    function verify(cert, key) {
        /*
         * We always give an issuerKey, so if our verify() is being called then
         * there was no signature. Return false.
         */
        return (false);
    }
    var TYPES = {
        'user': 1,
        'host': 2
    };
    Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; });
    var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/;
    function read(buf, options) {
        if (Buffer.isBuffer(buf))
            buf = buf.toString('ascii');
        var parts = buf.trim().split(/[ \t\n]+/g);
        if (parts.length < 2 || parts.length > 3)
            throw (new Error('Not a valid SSH certificate line'));
        var algo = parts[0];
        var data = parts[1];
        data = Buffer.from(data, 'base64');
        return (fromBuffer(data, algo));
    }
    function fromBuffer(data, algo, partial) {
        var sshbuf = new SSHBuffer({ buffer: data });
        var innerAlgo = sshbuf.readString();
        if (algo !== undefined && innerAlgo !== algo)
            throw (new Error('SSH certificate algorithm mismatch'));
        if (algo === undefined)
            algo = innerAlgo;
        var cert = {};
        cert.signatures = {};
        cert.signatures.openssh = {};
        cert.signatures.openssh.nonce = sshbuf.readBuffer();
        var key = {};
        var parts = (key.parts = []);
        key.type = getAlg(algo);
        var partCount = algs.info[key.type].parts.length;
        while (parts.length < partCount)
            parts.push(sshbuf.readPart());
        assert.ok(parts.length >= 1, 'key must have at least one part');
        var algInfo = algs.info[key.type];
        if (key.type === 'ecdsa') {
            var res = ECDSA_ALGO.exec(algo);
            assert.ok(res !== null);
            assert.strictEqual(res[1], parts[0].data.toString());
        }
        for (var i = 0; i < algInfo.parts.length; ++i) {
            parts[i].name = algInfo.parts[i];
            if (parts[i].name !== 'curve' &&
                algInfo.normalize !== false) {
                var p = parts[i];
                p.data = utils.mpNormalize(p.data);
            }
        }
        cert.subjectKey = new Key(key);
        cert.serial = sshbuf.readInt64();
        var type = TYPES[sshbuf.readInt()];
        assert.string(type, 'valid cert type');
        cert.signatures.openssh.keyId = sshbuf.readString();
        var principals = [];
        var pbuf = sshbuf.readBuffer();
        var psshbuf = new SSHBuffer({ buffer: pbuf });
        while (!psshbuf.atEnd())
            principals.push(psshbuf.readString());
        if (principals.length === 0)
            principals = ['*'];
        cert.subjects = principals.map(function (pr) {
            if (type === 'user')
                return (Identity.forUser(pr));
            else if (type === 'host')
                return (Identity.forHost(pr));
            throw (new Error('Unknown identity type ' + type));
        });
        cert.validFrom = int64ToDate(sshbuf.readInt64());
        cert.validUntil = int64ToDate(sshbuf.readInt64());
        cert.signatures.openssh.critical = sshbuf.readBuffer();
        cert.signatures.openssh.exts = sshbuf.readBuffer();
        /* reserved */
        sshbuf.readBuffer();
        var signingKeyBuf = sshbuf.readBuffer();
        cert.issuerKey = rfc4253.read(signingKeyBuf);
        /*
         * OpenSSH certs don't give the identity of the issuer, just their
         * public key. So, we use an Identity that matches anything. The
         * isSignedBy() function will later tell you if the key matches.
         */
        cert.issuer = Identity.forHost('**');
        var sigBuf = sshbuf.readBuffer();
        cert.signatures.openssh.signature =
            Signature.parse(sigBuf, cert.issuerKey.type, 'ssh');
        if (partial !== undefined) {
            partial.remainder = sshbuf.remainder();
            partial.consumed = sshbuf._offset;
        }
        return (new Certificate(cert));
    }
    function int64ToDate(buf) {
        var i = buf.readUInt32BE(0) * 4294967296;
        i += buf.readUInt32BE(4);
        var d = new Date();
        d.setTime(i * 1000);
        d.sourceInt64 = buf;
        return (d);
    }
    function dateToInt64(date) {
        if (date.sourceInt64 !== undefined)
            return (date.sourceInt64);
        var i = Math.round(date.getTime() / 1000);
        var upper = Math.floor(i / 4294967296);
        var lower = Math.floor(i % 4294967296);
        var buf = Buffer.alloc(8);
        buf.writeUInt32BE(upper, 0);
        buf.writeUInt32BE(lower, 4);
        return (buf);
    }
    function sign(cert, key) {
        if (cert.signatures.openssh === undefined)
            cert.signatures.openssh = {};
        try {
            var blob = toBuffer(cert, true);
        }
        catch (e) {
            delete (cert.signatures.openssh);
            return (false);
        }
        var sig = cert.signatures.openssh;
        var hashAlgo = undefined;
        if (key.type === 'rsa' || key.type === 'dsa')
            hashAlgo = 'sha1';
        var signer = key.createSign(hashAlgo);
        signer.write(blob);
        sig.signature = signer.sign();
        return (true);
    }
    function signAsync(cert, signer, done) {
        if (cert.signatures.openssh === undefined)
            cert.signatures.openssh = {};
        try {
            var blob = toBuffer(cert, true);
        }
        catch (e) {
            delete (cert.signatures.openssh);
            done(e);
            return;
        }
        var sig = cert.signatures.openssh;
        signer(blob, function (err, signature) {
            if (err) {
                done(err);
                return;
            }
            try {
                /*
                 * This will throw if the signature isn't of a
                 * type/algo that can be used for SSH.
                 */
                signature.toBuffer('ssh');
            }
            catch (e) {
                done(e);
                return;
            }
            sig.signature = signature;
            done();
        });
    }
    function write(cert, options) {
        if (options === undefined)
            options = {};
        var blob = toBuffer(cert);
        var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64');
        if (options.comment)
            out = out + ' ' + options.comment;
        return (out);
    }
    function toBuffer(cert, noSig) {
        assert.object(cert.signatures.openssh, 'signature for openssh format');
        var sig = cert.signatures.openssh;
        if (sig.nonce === undefined)
            sig.nonce = crypto.randomBytes(16);
        var buf = new SSHBuffer({});
        buf.writeString(getCertType(cert.subjectKey));
        buf.writeBuffer(sig.nonce);
        var key = cert.subjectKey;
        var algInfo = algs.info[key.type];
        algInfo.parts.forEach(function (part) {
            buf.writePart(key.part[part]);
        });
        buf.writeInt64(cert.serial);
        var type = cert.subjects[0].type;
        assert.notStrictEqual(type, 'unknown');
        cert.subjects.forEach(function (id) {
            assert.strictEqual(id.type, type);
        });
        type = TYPES[type];
        buf.writeInt(type);
        if (sig.keyId === undefined) {
            sig.keyId = cert.subjects[0].type + '_' +
                (cert.subjects[0].uid || cert.subjects[0].hostname);
        }
        buf.writeString(sig.keyId);
        var sub = new SSHBuffer({});
        cert.subjects.forEach(function (id) {
            if (type === TYPES.host)
                sub.writeString(id.hostname);
            else if (type === TYPES.user)
                sub.writeString(id.uid);
        });
        buf.writeBuffer(sub.toBuffer());
        buf.writeInt64(dateToInt64(cert.validFrom));
        buf.writeInt64(dateToInt64(cert.validUntil));
        if (sig.critical === undefined)
            sig.critical = Buffer.alloc(0);
        buf.writeBuffer(sig.critical);
        if (sig.exts === undefined)
            sig.exts = Buffer.alloc(0);
        buf.writeBuffer(sig.exts);
        /* reserved */
        buf.writeBuffer(Buffer.alloc(0));
        sub = rfc4253.write(cert.issuerKey);
        buf.writeBuffer(sub);
        if (!noSig)
            buf.writeBuffer(sig.signature.toBuffer('ssh'));
        return (buf.toBuffer());
    }
    function getAlg(certType) {
        if (certType === 'ssh-rsa-cert-v01@openssh.com')
            return ('rsa');
        if (certType === 'ssh-dss-cert-v01@openssh.com')
            return ('dsa');
        if (certType.match(ECDSA_ALGO))
            return ('ecdsa');
        if (certType === 'ssh-ed25519-cert-v01@openssh.com')
            return ('ed25519');
        throw (new Error('Unsupported cert type ' + certType));
    }
    function getCertType(key) {
        if (key.type === 'rsa')
            return ('ssh-rsa-cert-v01@openssh.com');
        if (key.type === 'dsa')
            return ('ssh-dss-cert-v01@openssh.com');
        if (key.type === 'ecdsa')
            return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com');
        if (key.type === 'ed25519')
            return ('ssh-ed25519-cert-v01@openssh.com');
        throw (new Error('Unsupported key type ' + key.type));
    }
}
,
/* sshpk/lib/formats/pem */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        read: read,
        write: write
    };
    var assert = require(53) /* assert-plus */;
    var asn1 = require(52) /* asn1 */;
    var crypto = require('crypto');
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var pkcs1 = require(341) /* ./pkcs1 */;
    var pkcs8 = require(342) /* ./pkcs8 */;
    var sshpriv = require(344) /* ./ssh-private */;
    var rfc4253 = require(343) /* ./rfc4253 */;
    var errors = require(335) /* ../errors */;
    /*
     * For reading we support both PKCS#1 and PKCS#8. If we find a private key,
     * we just take the public component of it and use that.
     */
    function read(buf, options, forceType) {
        var input = buf;
        if (typeof (buf) !== 'string') {
            assert.buffer(buf, 'buf');
            buf = buf.toString('ascii');
        }
        var lines = buf.trim().split('\n');
        var m = lines[0].match(/*JSSTYLED*/ /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
        assert.ok(m, 'invalid PEM header');
        var m2 = lines[lines.length - 1].match(/*JSSTYLED*/ /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
        assert.ok(m2, 'invalid PEM footer');
        /* Begin and end banners must match key type */
        assert.equal(m[2], m2[2]);
        var type = m[2].toLowerCase();
        var alg;
        if (m[1]) {
            /* They also must match algorithms, if given */
            assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
            alg = m[1].trim();
        }
        var headers = {};
        while (true) {
            lines = lines.slice(1);
            m = lines[0].match(/*JSSTYLED*/ /^([A-Za-z0-9-]+): (.+)$/);
            if (!m)
                break;
            headers[m[1].toLowerCase()] = m[2];
        }
        var cipher, key, iv;
        if (headers['proc-type']) {
            var parts = headers['proc-type'].split(',');
            if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
                if (typeof (options.passphrase) === 'string') {
                    options.passphrase = Buffer.from(options.passphrase, 'utf-8');
                }
                if (!Buffer.isBuffer(options.passphrase)) {
                    throw (new errors.KeyEncryptedError(options.filename, 'PEM'));
                }
                else {
                    parts = headers['dek-info'].split(',');
                    assert.ok(parts.length === 2);
                    cipher = parts[0].toLowerCase();
                    iv = Buffer.from(parts[1], 'hex');
                    key = utils.opensslKeyDeriv(cipher, iv, options.passphrase, 1).key;
                }
            }
        }
        /* Chop off the first and last lines */
        lines = lines.slice(0, -1).join('');
        buf = Buffer.from(lines, 'base64');
        if (cipher && key && iv) {
            var cipherStream = crypto.createDecipheriv(cipher, key, iv);
            var chunk, chunks = [];
            cipherStream.once('error', function (e) {
                if (e.toString().indexOf('bad decrypt') !== -1) {
                    throw (new Error('Incorrect passphrase ' +
                        'supplied, could not decrypt key'));
                }
                throw (e);
            });
            cipherStream.write(buf);
            cipherStream.end();
            while ((chunk = cipherStream.read()) !== null)
                chunks.push(chunk);
            buf = Buffer.concat(chunks);
        }
        /* The new OpenSSH internal format abuses PEM headers */
        if (alg && alg.toLowerCase() === 'openssh')
            return (sshpriv.readSSHPrivate(type, buf, options));
        if (alg && alg.toLowerCase() === 'ssh2')
            return (rfc4253.readType(type, buf, options));
        var der = new asn1.BerReader(buf);
        der.originalInput = input;
        /*
         * All of the PEM file types start with a sequence tag, so chop it
         * off here
         */
        der.readSequence();
        /* PKCS#1 type keys name an algorithm in the banner explicitly */
        if (alg) {
            if (forceType)
                assert.strictEqual(forceType, 'pkcs1');
            return (pkcs1.readPkcs1(alg, type, der));
        }
        else {
            if (forceType)
                assert.strictEqual(forceType, 'pkcs8');
            return (pkcs8.readPkcs8(alg, type, der));
        }
    }
    function write(key, options, type) {
        assert.object(key);
        var alg = {
            'ecdsa': 'EC',
            'rsa': 'RSA',
            'dsa': 'DSA',
            'ed25519': 'EdDSA'
        }[key.type];
        var header;
        var der = new asn1.BerWriter();
        if (PrivateKey.isPrivateKey(key)) {
            if (type && type === 'pkcs8') {
                header = 'PRIVATE KEY';
                pkcs8.writePkcs8(der, key);
            }
            else {
                if (type)
                    assert.strictEqual(type, 'pkcs1');
                header = alg + ' PRIVATE KEY';
                pkcs1.writePkcs1(der, key);
            }
        }
        else if (Key.isKey(key)) {
            if (type && type === 'pkcs1') {
                header = alg + ' PUBLIC KEY';
                pkcs1.writePkcs1(der, key);
            }
            else {
                if (type)
                    assert.strictEqual(type, 'pkcs8');
                header = 'PUBLIC KEY';
                pkcs8.writePkcs8(der, key);
            }
        }
        else {
            throw (new Error('key is not a Key or PrivateKey'));
        }
        var tmp = der.buffer.toString('base64');
        var len = tmp.length + (tmp.length / 64) +
            18 + 16 + header.length * 2 + 10;
        var buf = Buffer.alloc(len);
        var o = 0;
        o += buf.write('-----BEGIN ' + header + '-----\n', o);
        for (var i = 0; i < tmp.length;) {
            var limit = i + 64;
            if (limit > tmp.length)
                limit = tmp.length;
            o += buf.write(tmp.slice(i, limit), o);
            buf[o++] = 10;
            i = limit;
        }
        o += buf.write('-----END ' + header + '-----\n', o);
        return (buf.slice(0, o));
    }
}
,
/* sshpk/lib/formats/pkcs1 */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        read: read,
        readPkcs1: readPkcs1,
        write: write,
        writePkcs1: writePkcs1
    };
    var assert = require(53) /* assert-plus */;
    var asn1 = require(52) /* asn1 */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var pem = require(340) /* ./pem */;
    var pkcs8 = require(342) /* ./pkcs8 */;
    var readECDSACurve = pkcs8.readECDSACurve;
    function read(buf, options) {
        return (pem.read(buf, options, 'pkcs1'));
    }
    function write(key, options) {
        return (pem.write(key, options, 'pkcs1'));
    }
    /* Helper to read in a single mpint */
    function readMPInt(der, nm) {
        assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer');
        return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
    }
    function readPkcs1(alg, type, der) {
        switch (alg) {
            case 'RSA':
                if (type === 'public')
                    return (readPkcs1RSAPublic(der));
                else if (type === 'private')
                    return (readPkcs1RSAPrivate(der));
                throw (new Error('Unknown key type: ' + type));
            case 'DSA':
                if (type === 'public')
                    return (readPkcs1DSAPublic(der));
                else if (type === 'private')
                    return (readPkcs1DSAPrivate(der));
                throw (new Error('Unknown key type: ' + type));
            case 'EC':
            case 'ECDSA':
                if (type === 'private')
                    return (readPkcs1ECDSAPrivate(der));
                else if (type === 'public')
                    return (readPkcs1ECDSAPublic(der));
                throw (new Error('Unknown key type: ' + type));
            case 'EDDSA':
            case 'EdDSA':
                if (type === 'private')
                    return (readPkcs1EdDSAPrivate(der));
                throw (new Error(type + ' keys not supported with EdDSA'));
            default:
                throw (new Error('Unknown key algo: ' + alg));
        }
    }
    function readPkcs1RSAPublic(der) {
        // modulus and exponent
        var n = readMPInt(der, 'modulus');
        var e = readMPInt(der, 'exponent');
        // now, make the key
        var key = {
            type: 'rsa',
            parts: [
                { name: 'e', data: e },
                { name: 'n', data: n }
            ]
        };
        return (new Key(key));
    }
    function readPkcs1RSAPrivate(der) {
        var version = readMPInt(der, 'version');
        assert.strictEqual(version[0], 0);
        // modulus then public exponent
        var n = readMPInt(der, 'modulus');
        var e = readMPInt(der, 'public exponent');
        var d = readMPInt(der, 'private exponent');
        var p = readMPInt(der, 'prime1');
        var q = readMPInt(der, 'prime2');
        var dmodp = readMPInt(der, 'exponent1');
        var dmodq = readMPInt(der, 'exponent2');
        var iqmp = readMPInt(der, 'iqmp');
        // now, make the key
        var key = {
            type: 'rsa',
            parts: [
                { name: 'n', data: n },
                { name: 'e', data: e },
                { name: 'd', data: d },
                { name: 'iqmp', data: iqmp },
                { name: 'p', data: p },
                { name: 'q', data: q },
                { name: 'dmodp', data: dmodp },
                { name: 'dmodq', data: dmodq }
            ]
        };
        return (new PrivateKey(key));
    }
    function readPkcs1DSAPrivate(der) {
        var version = readMPInt(der, 'version');
        assert.strictEqual(version.readUInt8(0), 0);
        var p = readMPInt(der, 'p');
        var q = readMPInt(der, 'q');
        var g = readMPInt(der, 'g');
        var y = readMPInt(der, 'y');
        var x = readMPInt(der, 'x');
        // now, make the key
        var key = {
            type: 'dsa',
            parts: [
                { name: 'p', data: p },
                { name: 'q', data: q },
                { name: 'g', data: g },
                { name: 'y', data: y },
                { name: 'x', data: x }
            ]
        };
        return (new PrivateKey(key));
    }
    function readPkcs1EdDSAPrivate(der) {
        var version = readMPInt(der, 'version');
        assert.strictEqual(version.readUInt8(0), 1);
        // private key
        var k = der.readString(asn1.Ber.OctetString, true);
        der.readSequence(0xa0);
        var oid = der.readOID();
        assert.strictEqual(oid, '1.3.101.112', 'the ed25519 curve identifier');
        der.readSequence(0xa1);
        var A = utils.readBitString(der);
        var key = {
            type: 'ed25519',
            parts: [
                { name: 'A', data: utils.zeroPadToLength(A, 32) },
                { name: 'k', data: k }
            ]
        };
        return (new PrivateKey(key));
    }
    function readPkcs1DSAPublic(der) {
        var y = readMPInt(der, 'y');
        var p = readMPInt(der, 'p');
        var q = readMPInt(der, 'q');
        var g = readMPInt(der, 'g');
        var key = {
            type: 'dsa',
            parts: [
                { name: 'y', data: y },
                { name: 'p', data: p },
                { name: 'q', data: q },
                { name: 'g', data: g }
            ]
        };
        return (new Key(key));
    }
    function readPkcs1ECDSAPublic(der) {
        der.readSequence();
        var oid = der.readOID();
        assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey');
        var curveOid = der.readOID();
        var curve;
        var curves = Object.keys(algs.curves);
        for (var j = 0; j < curves.length; ++j) {
            var c = curves[j];
            var cd = algs.curves[c];
            if (cd.pkcs8oid === curveOid) {
                curve = c;
                break;
            }
        }
        assert.string(curve, 'a known ECDSA named curve');
        var Q = der.readString(asn1.Ber.BitString, true);
        Q = utils.ecNormalize(Q);
        var key = {
            type: 'ecdsa',
            parts: [
                { name: 'curve', data: Buffer.from(curve) },
                { name: 'Q', data: Q }
            ]
        };
        return (new Key(key));
    }
    function readPkcs1ECDSAPrivate(der) {
        var version = readMPInt(der, 'version');
        assert.strictEqual(version.readUInt8(0), 1);
        // private key
        var d = der.readString(asn1.Ber.OctetString, true);
        der.readSequence(0xa0);
        var curve = readECDSACurve(der);
        assert.string(curve, 'a known elliptic curve');
        der.readSequence(0xa1);
        var Q = der.readString(asn1.Ber.BitString, true);
        Q = utils.ecNormalize(Q);
        var key = {
            type: 'ecdsa',
            parts: [
                { name: 'curve', data: Buffer.from(curve) },
                { name: 'Q', data: Q },
                { name: 'd', data: d }
            ]
        };
        return (new PrivateKey(key));
    }
    function writePkcs1(der, key) {
        der.startSequence();
        switch (key.type) {
            case 'rsa':
                if (PrivateKey.isPrivateKey(key))
                    writePkcs1RSAPrivate(der, key);
                else
                    writePkcs1RSAPublic(der, key);
                break;
            case 'dsa':
                if (PrivateKey.isPrivateKey(key))
                    writePkcs1DSAPrivate(der, key);
                else
                    writePkcs1DSAPublic(der, key);
                break;
            case 'ecdsa':
                if (PrivateKey.isPrivateKey(key))
                    writePkcs1ECDSAPrivate(der, key);
                else
                    writePkcs1ECDSAPublic(der, key);
                break;
            case 'ed25519':
                if (PrivateKey.isPrivateKey(key))
                    writePkcs1EdDSAPrivate(der, key);
                else
                    writePkcs1EdDSAPublic(der, key);
                break;
            default:
                throw (new Error('Unknown key algo: ' + key.type));
        }
        der.endSequence();
    }
    function writePkcs1RSAPublic(der, key) {
        der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
    }
    function writePkcs1RSAPrivate(der, key) {
        var ver = Buffer.from([0]);
        der.writeBuffer(ver, asn1.Ber.Integer);
        der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
        if (!key.part.dmodp || !key.part.dmodq)
            utils.addRSAMissing(key);
        der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
    }
    function writePkcs1DSAPrivate(der, key) {
        var ver = Buffer.from([0]);
        der.writeBuffer(ver, asn1.Ber.Integer);
        der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
    }
    function writePkcs1DSAPublic(der, key) {
        der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
    }
    function writePkcs1ECDSAPublic(der, key) {
        der.startSequence();
        der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */
        var curve = key.part.curve.data.toString();
        var curveOid = algs.curves[curve].pkcs8oid;
        assert.string(curveOid, 'a known ECDSA named curve');
        der.writeOID(curveOid);
        der.endSequence();
        var Q = utils.ecNormalize(key.part.Q.data, true);
        der.writeBuffer(Q, asn1.Ber.BitString);
    }
    function writePkcs1ECDSAPrivate(der, key) {
        var ver = Buffer.from([1]);
        der.writeBuffer(ver, asn1.Ber.Integer);
        der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
        der.startSequence(0xa0);
        var curve = key.part.curve.data.toString();
        var curveOid = algs.curves[curve].pkcs8oid;
        assert.string(curveOid, 'a known ECDSA named curve');
        der.writeOID(curveOid);
        der.endSequence();
        der.startSequence(0xa1);
        var Q = utils.ecNormalize(key.part.Q.data, true);
        der.writeBuffer(Q, asn1.Ber.BitString);
        der.endSequence();
    }
    function writePkcs1EdDSAPrivate(der, key) {
        var ver = Buffer.from([1]);
        der.writeBuffer(ver, asn1.Ber.Integer);
        der.writeBuffer(key.part.k.data, asn1.Ber.OctetString);
        der.startSequence(0xa0);
        der.writeOID('1.3.101.112');
        der.endSequence();
        der.startSequence(0xa1);
        utils.writeBitString(der, key.part.A.data);
        der.endSequence();
    }
    function writePkcs1EdDSAPublic(der, key) {
        throw (new Error('Public keys are not supported for EdDSA PKCS#1'));
    }
}
,
/* sshpk/lib/formats/pkcs8 */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        read: read,
        readPkcs8: readPkcs8,
        write: write,
        writePkcs8: writePkcs8,
        readECDSACurve: readECDSACurve,
        writeECDSACurve: writeECDSACurve
    };
    var assert = require(53) /* assert-plus */;
    var asn1 = require(52) /* asn1 */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var pem = require(340) /* ./pem */;
    function read(buf, options) {
        return (pem.read(buf, options, 'pkcs8'));
    }
    function write(key, options) {
        return (pem.write(key, options, 'pkcs8'));
    }
    /* Helper to read in a single mpint */
    function readMPInt(der, nm) {
        assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer');
        return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
    }
    function readPkcs8(alg, type, der) {
        /* Private keys in pkcs#8 format have a weird extra int */
        if (der.peek() === asn1.Ber.Integer) {
            assert.strictEqual(type, 'private', 'unexpected Integer at start of public key');
            der.readString(asn1.Ber.Integer, true);
        }
        der.readSequence();
        var next = der.offset + der.length;
        var oid = der.readOID();
        switch (oid) {
            case '1.2.840.113549.1.1.1':
                der._offset = next;
                if (type === 'public')
                    return (readPkcs8RSAPublic(der));
                else
                    return (readPkcs8RSAPrivate(der));
            case '1.2.840.10040.4.1':
                if (type === 'public')
                    return (readPkcs8DSAPublic(der));
                else
                    return (readPkcs8DSAPrivate(der));
            case '1.2.840.10045.2.1':
                if (type === 'public')
                    return (readPkcs8ECDSAPublic(der));
                else
                    return (readPkcs8ECDSAPrivate(der));
            case '1.3.101.112':
                if (type === 'public') {
                    return (readPkcs8EdDSAPublic(der));
                }
                else {
                    return (readPkcs8EdDSAPrivate(der));
                }
            case '1.3.101.110':
                if (type === 'public') {
                    return (readPkcs8X25519Public(der));
                }
                else {
                    return (readPkcs8X25519Private(der));
                }
            default:
                throw (new Error('Unknown key type OID ' + oid));
        }
    }
    function readPkcs8RSAPublic(der) {
        // bit string sequence
        der.readSequence(asn1.Ber.BitString);
        der.readByte();
        der.readSequence();
        // modulus
        var n = readMPInt(der, 'modulus');
        var e = readMPInt(der, 'exponent');
        // now, make the key
        var key = {
            type: 'rsa',
            source: der.originalInput,
            parts: [
                { name: 'e', data: e },
                { name: 'n', data: n }
            ]
        };
        return (new Key(key));
    }
    function readPkcs8RSAPrivate(der) {
        der.readSequence(asn1.Ber.OctetString);
        der.readSequence();
        var ver = readMPInt(der, 'version');
        assert.equal(ver[0], 0x0, 'unknown RSA private key version');
        // modulus then public exponent
        var n = readMPInt(der, 'modulus');
        var e = readMPInt(der, 'public exponent');
        var d = readMPInt(der, 'private exponent');
        var p = readMPInt(der, 'prime1');
        var q = readMPInt(der, 'prime2');
        var dmodp = readMPInt(der, 'exponent1');
        var dmodq = readMPInt(der, 'exponent2');
        var iqmp = readMPInt(der, 'iqmp');
        // now, make the key
        var key = {
            type: 'rsa',
            parts: [
                { name: 'n', data: n },
                { name: 'e', data: e },
                { name: 'd', data: d },
                { name: 'iqmp', data: iqmp },
                { name: 'p', data: p },
                { name: 'q', data: q },
                { name: 'dmodp', data: dmodp },
                { name: 'dmodq', data: dmodq }
            ]
        };
        return (new PrivateKey(key));
    }
    function readPkcs8DSAPublic(der) {
        der.readSequence();
        var p = readMPInt(der, 'p');
        var q = readMPInt(der, 'q');
        var g = readMPInt(der, 'g');
        // bit string sequence
        der.readSequence(asn1.Ber.BitString);
        der.readByte();
        var y = readMPInt(der, 'y');
        // now, make the key
        var key = {
            type: 'dsa',
            parts: [
                { name: 'p', data: p },
                { name: 'q', data: q },
                { name: 'g', data: g },
                { name: 'y', data: y }
            ]
        };
        return (new Key(key));
    }
    function readPkcs8DSAPrivate(der) {
        der.readSequence();
        var p = readMPInt(der, 'p');
        var q = readMPInt(der, 'q');
        var g = readMPInt(der, 'g');
        der.readSequence(asn1.Ber.OctetString);
        var x = readMPInt(der, 'x');
        /* The pkcs#8 format does not include the public key */
        var y = utils.calculateDSAPublic(g, p, x);
        var key = {
            type: 'dsa',
            parts: [
                { name: 'p', data: p },
                { name: 'q', data: q },
                { name: 'g', data: g },
                { name: 'y', data: y },
                { name: 'x', data: x }
            ]
        };
        return (new PrivateKey(key));
    }
    function readECDSACurve(der) {
        var curveName, curveNames;
        var j, c, cd;
        if (der.peek() === asn1.Ber.OID) {
            var oid = der.readOID();
            curveNames = Object.keys(algs.curves);
            for (j = 0; j < curveNames.length; ++j) {
                c = curveNames[j];
                cd = algs.curves[c];
                if (cd.pkcs8oid === oid) {
                    curveName = c;
                    break;
                }
            }
        }
        else {
            // ECParameters sequence
            der.readSequence();
            var version = der.readString(asn1.Ber.Integer, true);
            assert.strictEqual(version[0], 1, 'ECDSA key not version 1');
            var curve = {};
            // FieldID sequence
            der.readSequence();
            var fieldTypeOid = der.readOID();
            assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1', 'ECDSA key is not from a prime-field');
            var p = curve.p = utils.mpNormalize(der.readString(asn1.Ber.Integer, true));
            /*
             * p always starts with a 1 bit, so count the zeros to get its
             * real size.
             */
            curve.size = p.length * 8 - utils.countZeros(p);
            // Curve sequence
            der.readSequence();
            curve.a = utils.mpNormalize(der.readString(asn1.Ber.OctetString, true));
            curve.b = utils.mpNormalize(der.readString(asn1.Ber.OctetString, true));
            if (der.peek() === asn1.Ber.BitString)
                curve.s = der.readString(asn1.Ber.BitString, true);
            // Combined Gx and Gy
            curve.G = der.readString(asn1.Ber.OctetString, true);
            assert.strictEqual(curve.G[0], 0x4, 'uncompressed G is required');
            curve.n = utils.mpNormalize(der.readString(asn1.Ber.Integer, true));
            curve.h = utils.mpNormalize(der.readString(asn1.Ber.Integer, true));
            assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' +
                'required');
            curveNames = Object.keys(algs.curves);
            var ks = Object.keys(curve);
            for (j = 0; j < curveNames.length; ++j) {
                c = curveNames[j];
                cd = algs.curves[c];
                var equal = true;
                for (var i = 0; i < ks.length; ++i) {
                    var k = ks[i];
                    if (cd[k] === undefined)
                        continue;
                    if (typeof (cd[k]) === 'object' &&
                        cd[k].equals !== undefined) {
                        if (!cd[k].equals(curve[k])) {
                            equal = false;
                            break;
                        }
                    }
                    else if (Buffer.isBuffer(cd[k])) {
                        if (cd[k].toString('binary')
                            !== curve[k].toString('binary')) {
                            equal = false;
                            break;
                        }
                    }
                    else {
                        if (cd[k] !== curve[k]) {
                            equal = false;
                            break;
                        }
                    }
                }
                if (equal) {
                    curveName = c;
                    break;
                }
            }
        }
        return (curveName);
    }
    function readPkcs8ECDSAPrivate(der) {
        var curveName = readECDSACurve(der);
        assert.string(curveName, 'a known elliptic curve');
        der.readSequence(asn1.Ber.OctetString);
        der.readSequence();
        var version = readMPInt(der, 'version');
        assert.equal(version[0], 1, 'unknown version of ECDSA key');
        var d = der.readString(asn1.Ber.OctetString, true);
        der.readSequence(0xa1);
        var Q = der.readString(asn1.Ber.BitString, true);
        Q = utils.ecNormalize(Q);
        var key = {
            type: 'ecdsa',
            parts: [
                { name: 'curve', data: Buffer.from(curveName) },
                { name: 'Q', data: Q },
                { name: 'd', data: d }
            ]
        };
        return (new PrivateKey(key));
    }
    function readPkcs8ECDSAPublic(der) {
        var curveName = readECDSACurve(der);
        assert.string(curveName, 'a known elliptic curve');
        var Q = der.readString(asn1.Ber.BitString, true);
        Q = utils.ecNormalize(Q);
        var key = {
            type: 'ecdsa',
            parts: [
                { name: 'curve', data: Buffer.from(curveName) },
                { name: 'Q', data: Q }
            ]
        };
        return (new Key(key));
    }
    function readPkcs8EdDSAPublic(der) {
        if (der.peek() === 0x00)
            der.readByte();
        var A = utils.readBitString(der);
        var key = {
            type: 'ed25519',
            parts: [
                { name: 'A', data: utils.zeroPadToLength(A, 32) }
            ]
        };
        return (new Key(key));
    }
    function readPkcs8X25519Public(der) {
        var A = utils.readBitString(der);
        var key = {
            type: 'curve25519',
            parts: [
                { name: 'A', data: utils.zeroPadToLength(A, 32) }
            ]
        };
        return (new Key(key));
    }
    function readPkcs8EdDSAPrivate(der) {
        if (der.peek() === 0x00)
            der.readByte();
        der.readSequence(asn1.Ber.OctetString);
        var k = der.readString(asn1.Ber.OctetString, true);
        k = utils.zeroPadToLength(k, 32);
        var A;
        if (der.peek() === asn1.Ber.BitString) {
            A = utils.readBitString(der);
            A = utils.zeroPadToLength(A, 32);
        }
        else {
            A = utils.calculateED25519Public(k);
        }
        var key = {
            type: 'ed25519',
            parts: [
                { name: 'A', data: utils.zeroPadToLength(A, 32) },
                { name: 'k', data: utils.zeroPadToLength(k, 32) }
            ]
        };
        return (new PrivateKey(key));
    }
    function readPkcs8X25519Private(der) {
        if (der.peek() === 0x00)
            der.readByte();
        der.readSequence(asn1.Ber.OctetString);
        var k = der.readString(asn1.Ber.OctetString, true);
        k = utils.zeroPadToLength(k, 32);
        var A = utils.calculateX25519Public(k);
        var key = {
            type: 'curve25519',
            parts: [
                { name: 'A', data: utils.zeroPadToLength(A, 32) },
                { name: 'k', data: utils.zeroPadToLength(k, 32) }
            ]
        };
        return (new PrivateKey(key));
    }
    function writePkcs8(der, key) {
        der.startSequence();
        if (PrivateKey.isPrivateKey(key)) {
            var sillyInt = Buffer.from([0]);
            der.writeBuffer(sillyInt, asn1.Ber.Integer);
        }
        der.startSequence();
        switch (key.type) {
            case 'rsa':
                der.writeOID('1.2.840.113549.1.1.1');
                if (PrivateKey.isPrivateKey(key))
                    writePkcs8RSAPrivate(key, der);
                else
                    writePkcs8RSAPublic(key, der);
                break;
            case 'dsa':
                der.writeOID('1.2.840.10040.4.1');
                if (PrivateKey.isPrivateKey(key))
                    writePkcs8DSAPrivate(key, der);
                else
                    writePkcs8DSAPublic(key, der);
                break;
            case 'ecdsa':
                der.writeOID('1.2.840.10045.2.1');
                if (PrivateKey.isPrivateKey(key))
                    writePkcs8ECDSAPrivate(key, der);
                else
                    writePkcs8ECDSAPublic(key, der);
                break;
            case 'ed25519':
                der.writeOID('1.3.101.112');
                if (PrivateKey.isPrivateKey(key))
                    throw (new Error('Ed25519 private keys in pkcs8 ' +
                        'format are not supported'));
                writePkcs8EdDSAPublic(key, der);
                break;
            default:
                throw (new Error('Unsupported key type: ' + key.type));
        }
        der.endSequence();
    }
    function writePkcs8RSAPrivate(key, der) {
        der.writeNull();
        der.endSequence();
        der.startSequence(asn1.Ber.OctetString);
        der.startSequence();
        var version = Buffer.from([0]);
        der.writeBuffer(version, asn1.Ber.Integer);
        der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
        if (!key.part.dmodp || !key.part.dmodq)
            utils.addRSAMissing(key);
        der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
        der.endSequence();
        der.endSequence();
    }
    function writePkcs8RSAPublic(key, der) {
        der.writeNull();
        der.endSequence();
        der.startSequence(asn1.Ber.BitString);
        der.writeByte(0x00);
        der.startSequence();
        der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
        der.endSequence();
        der.endSequence();
    }
    function writePkcs8DSAPrivate(key, der) {
        der.startSequence();
        der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
        der.endSequence();
        der.endSequence();
        der.startSequence(asn1.Ber.OctetString);
        der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
        der.endSequence();
    }
    function writePkcs8DSAPublic(key, der) {
        der.startSequence();
        der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
        der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
        der.endSequence();
        der.endSequence();
        der.startSequence(asn1.Ber.BitString);
        der.writeByte(0x00);
        der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
        der.endSequence();
    }
    function writeECDSACurve(key, der) {
        var curve = algs.curves[key.curve];
        if (curve.pkcs8oid) {
            /* This one has a name in pkcs#8, so just write the oid */
            der.writeOID(curve.pkcs8oid);
        }
        else {
            // ECParameters sequence
            der.startSequence();
            var version = Buffer.from([1]);
            der.writeBuffer(version, asn1.Ber.Integer);
            // FieldID sequence
            der.startSequence();
            der.writeOID('1.2.840.10045.1.1'); // prime-field
            der.writeBuffer(curve.p, asn1.Ber.Integer);
            der.endSequence();
            // Curve sequence
            der.startSequence();
            var a = curve.p;
            if (a[0] === 0x0)
                a = a.slice(1);
            der.writeBuffer(a, asn1.Ber.OctetString);
            der.writeBuffer(curve.b, asn1.Ber.OctetString);
            der.writeBuffer(curve.s, asn1.Ber.BitString);
            der.endSequence();
            der.writeBuffer(curve.G, asn1.Ber.OctetString);
            der.writeBuffer(curve.n, asn1.Ber.Integer);
            var h = curve.h;
            if (!h) {
                h = Buffer.from([1]);
            }
            der.writeBuffer(h, asn1.Ber.Integer);
            // ECParameters
            der.endSequence();
        }
    }
    function writePkcs8ECDSAPublic(key, der) {
        writeECDSACurve(key, der);
        der.endSequence();
        var Q = utils.ecNormalize(key.part.Q.data, true);
        der.writeBuffer(Q, asn1.Ber.BitString);
    }
    function writePkcs8ECDSAPrivate(key, der) {
        writeECDSACurve(key, der);
        der.endSequence();
        der.startSequence(asn1.Ber.OctetString);
        der.startSequence();
        var version = Buffer.from([1]);
        der.writeBuffer(version, asn1.Ber.Integer);
        der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
        der.startSequence(0xa1);
        var Q = utils.ecNormalize(key.part.Q.data, true);
        der.writeBuffer(Q, asn1.Ber.BitString);
        der.endSequence();
        der.endSequence();
        der.endSequence();
    }
    function writePkcs8EdDSAPublic(key, der) {
        der.endSequence();
        utils.writeBitString(der, key.part.A.data);
    }
    function writePkcs8EdDSAPrivate(key, der) {
        der.endSequence();
        var k = utils.mpNormalize(key.part.k.data, true);
        der.startSequence(asn1.Ber.OctetString);
        der.writeBuffer(k, asn1.Ber.OctetString);
        der.endSequence();
    }
}
,
/* sshpk/lib/formats/rfc4253 */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        read: read.bind(undefined, false, undefined),
        readType: read.bind(undefined, false),
        write: write,
        /* semi-private api, used by sshpk-agent */
        readPartial: read.bind(undefined, true),
        /* shared with ssh format */
        readInternal: read,
        keyTypeToAlg: keyTypeToAlg,
        algToKeyType: algToKeyType
    };
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var SSHBuffer = require(353) /* ../ssh-buffer */;
    function algToKeyType(alg) {
        assert.string(alg);
        if (alg === 'ssh-dss')
            return ('dsa');
        else if (alg === 'ssh-rsa')
            return ('rsa');
        else if (alg === 'ssh-ed25519')
            return ('ed25519');
        else if (alg === 'ssh-curve25519')
            return ('curve25519');
        else if (alg.match(/^ecdsa-sha2-/))
            return ('ecdsa');
        else
            throw (new Error('Unknown algorithm ' + alg));
    }
    function keyTypeToAlg(key) {
        assert.object(key);
        if (key.type === 'dsa')
            return ('ssh-dss');
        else if (key.type === 'rsa')
            return ('ssh-rsa');
        else if (key.type === 'ed25519')
            return ('ssh-ed25519');
        else if (key.type === 'curve25519')
            return ('ssh-curve25519');
        else if (key.type === 'ecdsa')
            return ('ecdsa-sha2-' + key.part.curve.data.toString());
        else
            throw (new Error('Unknown key type ' + key.type));
    }
    function read(partial, type, buf, options) {
        if (typeof (buf) === 'string')
            buf = Buffer.from(buf);
        assert.buffer(buf, 'buf');
        var key = {};
        var parts = key.parts = [];
        var sshbuf = new SSHBuffer({ buffer: buf });
        var alg = sshbuf.readString();
        assert.ok(!sshbuf.atEnd(), 'key must have at least one part');
        key.type = algToKeyType(alg);
        var partCount = algs.info[key.type].parts.length;
        if (type && type === 'private')
            partCount = algs.privInfo[key.type].parts.length;
        while (!sshbuf.atEnd() && parts.length < partCount)
            parts.push(sshbuf.readPart());
        while (!partial && !sshbuf.atEnd())
            parts.push(sshbuf.readPart());
        assert.ok(parts.length >= 1, 'key must have at least one part');
        assert.ok(partial || sshbuf.atEnd(), 'leftover bytes at end of key');
        var Constructor = Key;
        var algInfo = algs.info[key.type];
        if (type === 'private' || algInfo.parts.length !== parts.length) {
            algInfo = algs.privInfo[key.type];
            Constructor = PrivateKey;
        }
        assert.strictEqual(algInfo.parts.length, parts.length);
        if (key.type === 'ecdsa') {
            var res = /^ecdsa-sha2-(.+)$/.exec(alg);
            assert.ok(res !== null);
            assert.strictEqual(res[1], parts[0].data.toString());
        }
        var normalized = true;
        for (var i = 0; i < algInfo.parts.length; ++i) {
            var p = parts[i];
            p.name = algInfo.parts[i];
            /*
             * OpenSSH stores ed25519 "private" keys as seed + public key
             * concat'd together (k followed by A). We want to keep them
             * separate for other formats that don't do this.
             */
            if (key.type === 'ed25519' && p.name === 'k')
                p.data = p.data.slice(0, 32);
            if (p.name !== 'curve' && algInfo.normalize !== false) {
                var nd;
                if (key.type === 'ed25519') {
                    nd = utils.zeroPadToLength(p.data, 32);
                }
                else {
                    nd = utils.mpNormalize(p.data);
                }
                if (nd.toString('binary') !==
                    p.data.toString('binary')) {
                    p.data = nd;
                    normalized = false;
                }
            }
        }
        if (normalized)
            key._rfc4253Cache = sshbuf.toBuffer();
        if (partial && typeof (partial) === 'object') {
            partial.remainder = sshbuf.remainder();
            partial.consumed = sshbuf._offset;
        }
        return (new Constructor(key));
    }
    function write(key, options) {
        assert.object(key);
        var alg = keyTypeToAlg(key);
        var i;
        var algInfo = algs.info[key.type];
        if (PrivateKey.isPrivateKey(key))
            algInfo = algs.privInfo[key.type];
        var parts = algInfo.parts;
        var buf = new SSHBuffer({});
        buf.writeString(alg);
        for (i = 0; i < parts.length; ++i) {
            var data = key.part[parts[i]].data;
            if (algInfo.normalize !== false) {
                if (key.type === 'ed25519')
                    data = utils.zeroPadToLength(data, 32);
                else
                    data = utils.mpNormalize(data);
            }
            if (key.type === 'ed25519' && parts[i] === 'k')
                data = Buffer.concat([data, key.part.A.data]);
            buf.writeBuffer(data);
        }
        return (buf.toBuffer());
    }
}
,
/* sshpk/lib/formats/ssh-private */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        read: read,
        readSSHPrivate: readSSHPrivate,
        write: write
    };
    var assert = require(53) /* assert-plus */;
    var asn1 = require(52) /* asn1 */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var utils = require(354) /* ../utils */;
    var crypto = require('crypto');
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var pem = require(340) /* ./pem */;
    var rfc4253 = require(343) /* ./rfc4253 */;
    var SSHBuffer = require(353) /* ../ssh-buffer */;
    var errors = require(335) /* ../errors */;
    var bcrypt;
    function read(buf, options) {
        return (pem.read(buf, options));
    }
    var MAGIC = 'openssh-key-v1';
    function readSSHPrivate(type, buf, options) {
        buf = new SSHBuffer({ buffer: buf });
        var magic = buf.readCString();
        assert.strictEqual(magic, MAGIC, 'bad magic string');
        var cipher = buf.readString();
        var kdf = buf.readString();
        var kdfOpts = buf.readBuffer();
        var nkeys = buf.readInt();
        if (nkeys !== 1) {
            throw (new Error('OpenSSH-format key file contains ' +
                'multiple keys: this is unsupported.'));
        }
        var pubKey = buf.readBuffer();
        if (type === 'public') {
            assert.ok(buf.atEnd(), 'excess bytes left after key');
            return (rfc4253.read(pubKey));
        }
        var privKeyBlob = buf.readBuffer();
        assert.ok(buf.atEnd(), 'excess bytes left after key');
        var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts });
        switch (kdf) {
            case 'none':
                if (cipher !== 'none') {
                    throw (new Error('OpenSSH-format key uses KDF "none" ' +
                        'but specifies a cipher other than "none"'));
                }
                break;
            case 'bcrypt':
                var salt = kdfOptsBuf.readBuffer();
                var rounds = kdfOptsBuf.readInt();
                var cinf = utils.opensshCipherInfo(cipher);
                if (bcrypt === undefined) {
                    bcrypt = require(67) /* bcrypt-pbkdf */;
                }
                if (typeof (options.passphrase) === 'string') {
                    options.passphrase = Buffer.from(options.passphrase, 'utf-8');
                }
                if (!Buffer.isBuffer(options.passphrase)) {
                    throw (new errors.KeyEncryptedError(options.filename, 'OpenSSH'));
                }
                var pass = new Uint8Array(options.passphrase);
                var salti = new Uint8Array(salt);
                /* Use the pbkdf to derive both the key and the IV. */
                var out = new Uint8Array(cinf.keySize + cinf.blockSize);
                var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, out, out.length, rounds);
                if (res !== 0) {
                    throw (new Error('bcrypt_pbkdf function returned ' +
                        'failure, parameters invalid'));
                }
                out = Buffer.from(out);
                var ckey = out.slice(0, cinf.keySize);
                var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
                var cipherStream = crypto.createDecipheriv(cinf.opensslName, ckey, iv);
                cipherStream.setAutoPadding(false);
                var chunk, chunks = [];
                cipherStream.once('error', function (e) {
                    if (e.toString().indexOf('bad decrypt') !== -1) {
                        throw (new Error('Incorrect passphrase ' +
                            'supplied, could not decrypt key'));
                    }
                    throw (e);
                });
                cipherStream.write(privKeyBlob);
                cipherStream.end();
                while ((chunk = cipherStream.read()) !== null)
                    chunks.push(chunk);
                privKeyBlob = Buffer.concat(chunks);
                break;
            default:
                throw (new Error('OpenSSH-format key uses unknown KDF "' + kdf + '"'));
        }
        buf = new SSHBuffer({ buffer: privKeyBlob });
        var checkInt1 = buf.readInt();
        var checkInt2 = buf.readInt();
        if (checkInt1 !== checkInt2) {
            throw (new Error('Incorrect passphrase supplied, could not ' +
                'decrypt key'));
        }
        var ret = {};
        var key = rfc4253.readInternal(ret, 'private', buf.remainder());
        buf.skip(ret.consumed);
        var comment = buf.readString();
        key.comment = comment;
        return (key);
    }
    function write(key, options) {
        var pubKey;
        if (PrivateKey.isPrivateKey(key))
            pubKey = key.toPublic();
        else
            pubKey = key;
        var cipher = 'none';
        var kdf = 'none';
        var kdfopts = Buffer.alloc(0);
        var cinf = { blockSize: 8 };
        var passphrase;
        if (options !== undefined) {
            passphrase = options.passphrase;
            if (typeof (passphrase) === 'string')
                passphrase = Buffer.from(passphrase, 'utf-8');
            if (passphrase !== undefined) {
                assert.buffer(passphrase, 'options.passphrase');
                assert.optionalString(options.cipher, 'options.cipher');
                cipher = options.cipher;
                if (cipher === undefined)
                    cipher = 'aes128-ctr';
                cinf = utils.opensshCipherInfo(cipher);
                kdf = 'bcrypt';
            }
        }
        var privBuf;
        if (PrivateKey.isPrivateKey(key)) {
            privBuf = new SSHBuffer({});
            var checkInt = crypto.randomBytes(4).readUInt32BE(0);
            privBuf.writeInt(checkInt);
            privBuf.writeInt(checkInt);
            privBuf.write(key.toBuffer('rfc4253'));
            privBuf.writeString(key.comment || '');
            var n = 1;
            while (privBuf._offset % cinf.blockSize !== 0)
                privBuf.writeChar(n++);
            privBuf = privBuf.toBuffer();
        }
        switch (kdf) {
            case 'none':
                break;
            case 'bcrypt':
                var salt = crypto.randomBytes(16);
                var rounds = 16;
                var kdfssh = new SSHBuffer({});
                kdfssh.writeBuffer(salt);
                kdfssh.writeInt(rounds);
                kdfopts = kdfssh.toBuffer();
                if (bcrypt === undefined) {
                    bcrypt = require(67) /* bcrypt-pbkdf */;
                }
                var pass = new Uint8Array(passphrase);
                var salti = new Uint8Array(salt);
                /* Use the pbkdf to derive both the key and the IV. */
                var out = new Uint8Array(cinf.keySize + cinf.blockSize);
                var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, out, out.length, rounds);
                if (res !== 0) {
                    throw (new Error('bcrypt_pbkdf function returned ' +
                        'failure, parameters invalid'));
                }
                out = Buffer.from(out);
                var ckey = out.slice(0, cinf.keySize);
                var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
                var cipherStream = crypto.createCipheriv(cinf.opensslName, ckey, iv);
                cipherStream.setAutoPadding(false);
                var chunk, chunks = [];
                cipherStream.once('error', function (e) {
                    throw (e);
                });
                cipherStream.write(privBuf);
                cipherStream.end();
                while ((chunk = cipherStream.read()) !== null)
                    chunks.push(chunk);
                privBuf = Buffer.concat(chunks);
                break;
            default:
                throw (new Error('Unsupported kdf ' + kdf));
        }
        var buf = new SSHBuffer({});
        buf.writeCString(MAGIC);
        buf.writeString(cipher); /* cipher */
        buf.writeString(kdf); /* kdf */
        buf.writeBuffer(kdfopts); /* kdfoptions */
        buf.writeInt(1); /* nkeys */
        buf.writeBuffer(pubKey.toBuffer('rfc4253'));
        if (privBuf)
            buf.writeBuffer(privBuf);
        buf = buf.toBuffer();
        var header;
        if (PrivateKey.isPrivateKey(key))
            header = 'OPENSSH PRIVATE KEY';
        else
            header = 'OPENSSH PUBLIC KEY';
        var tmp = buf.toString('base64');
        var len = tmp.length + (tmp.length / 70) +
            18 + 16 + header.length * 2 + 10;
        buf = Buffer.alloc(len);
        var o = 0;
        o += buf.write('-----BEGIN ' + header + '-----\n', o);
        for (var i = 0; i < tmp.length;) {
            var limit = i + 70;
            if (limit > tmp.length)
                limit = tmp.length;
            o += buf.write(tmp.slice(i, limit), o);
            buf[o++] = 10;
            i = limit;
        }
        o += buf.write('-----END ' + header + '-----\n', o);
        return (buf.slice(0, o));
    }
}
,
/* sshpk/lib/formats/ssh */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        read: read,
        write: write
    };
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var rfc4253 = require(343) /* ./rfc4253 */;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var sshpriv = require(344) /* ./ssh-private */;
    /*JSSTYLED*/
    var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/;
    /*JSSTYLED*/
    var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/;
    function read(buf, options) {
        if (typeof (buf) !== 'string') {
            assert.buffer(buf, 'buf');
            buf = buf.toString('ascii');
        }
        var trimmed = buf.trim().replace(/[\\\r]/g, '');
        var m = trimmed.match(SSHKEY_RE);
        if (!m)
            m = trimmed.match(SSHKEY_RE2);
        assert.ok(m, 'key must match regex');
        var type = rfc4253.algToKeyType(m[1]);
        var kbuf = Buffer.from(m[2], 'base64');
        /*
         * This is a bit tricky. If we managed to parse the key and locate the
         * key comment with the regex, then do a non-partial read and assert
         * that we have consumed all bytes. If we couldn't locate the key
         * comment, though, there may be whitespace shenanigans going on that
         * have conjoined the comment to the rest of the key. We do a partial
         * read in this case to try to make the best out of a sorry situation.
         */
        var key;
        var ret = {};
        if (m[4]) {
            try {
                key = rfc4253.read(kbuf);
            }
            catch (e) {
                m = trimmed.match(SSHKEY_RE2);
                assert.ok(m, 'key must match regex');
                kbuf = Buffer.from(m[2], 'base64');
                key = rfc4253.readInternal(ret, 'public', kbuf);
            }
        }
        else {
            key = rfc4253.readInternal(ret, 'public', kbuf);
        }
        assert.strictEqual(type, key.type);
        if (m[4] && m[4].length > 0) {
            key.comment = m[4];
        }
        else if (ret.consumed) {
            /*
             * Now the magic: trying to recover the key comment when it's
             * gotten conjoined to the key or otherwise shenanigan'd.
             *
             * Work out how much base64 we used, then drop all non-base64
             * chars from the beginning up to this point in the the string.
             * Then offset in this and try to make up for missing = chars.
             */
            var data = m[2] + (m[3] ? m[3] : '');
            var realOffset = Math.ceil(ret.consumed / 3) * 4;
            data = data.slice(0, realOffset - 2). /*JSSTYLED*/
                replace(/[^a-zA-Z0-9+\/=]/g, '') +
                data.slice(realOffset - 2);
            var padding = ret.consumed % 3;
            if (padding > 0 &&
                data.slice(realOffset - 1, realOffset) !== '=')
                realOffset--;
            while (data.slice(realOffset, realOffset + 1) === '=')
                realOffset++;
            /* Finally, grab what we think is the comment & clean it up. */
            var trailer = data.slice(realOffset);
            trailer = trailer.replace(/[\r\n]/g, ' ').
                replace(/^\s+/, '');
            if (trailer.match(/^[a-zA-Z0-9]/))
                key.comment = trailer;
        }
        return (key);
    }
    function write(key, options) {
        assert.object(key);
        if (!Key.isKey(key))
            throw (new Error('Must be a public key'));
        var parts = [];
        var alg = rfc4253.keyTypeToAlg(key);
        parts.push(alg);
        var buf = rfc4253.write(key);
        parts.push(buf.toString('base64'));
        if (key.comment)
            parts.push(key.comment);
        return (Buffer.from(parts.join(' ')));
    }
}
,
/* sshpk/lib/formats/x509-pem */ function _(require, module, exports) {
    // Copyright 2016 Joyent, Inc.
    var x509 = require(347) /* ./x509 */;
    module.exports = {
        read: read,
        verify: x509.verify,
        sign: x509.sign,
        write: write
    };
    var assert = require(53) /* assert-plus */;
    var asn1 = require(52) /* asn1 */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var pem = require(340) /* ./pem */;
    var Identity = require(348) /* ../identity */;
    var Signature = require(352) /* ../signature */;
    var Certificate = require(332) /* ../certificate */;
    function read(buf, options) {
        if (typeof (buf) !== 'string') {
            assert.buffer(buf, 'buf');
            buf = buf.toString('ascii');
        }
        var lines = buf.trim().split(/[\r\n]+/g);
        var m = lines[0].match(/*JSSTYLED*/ /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);
        assert.ok(m, 'invalid PEM header');
        var m2 = lines[lines.length - 1].match(/*JSSTYLED*/ /[-]+[ ]*END CERTIFICATE[ ]*[-]+/);
        assert.ok(m2, 'invalid PEM footer');
        var headers = {};
        while (true) {
            lines = lines.slice(1);
            m = lines[0].match(/*JSSTYLED*/ /^([A-Za-z0-9-]+): (.+)$/);
            if (!m)
                break;
            headers[m[1].toLowerCase()] = m[2];
        }
        /* Chop off the first and last lines */
        lines = lines.slice(0, -1).join('');
        buf = Buffer.from(lines, 'base64');
        return (x509.read(buf, options));
    }
    function write(cert, options) {
        var dbuf = x509.write(cert, options);
        var header = 'CERTIFICATE';
        var tmp = dbuf.toString('base64');
        var len = tmp.length + (tmp.length / 64) +
            18 + 16 + header.length * 2 + 10;
        var buf = Buffer.alloc(len);
        var o = 0;
        o += buf.write('-----BEGIN ' + header + '-----\n', o);
        for (var i = 0; i < tmp.length;) {
            var limit = i + 64;
            if (limit > tmp.length)
                limit = tmp.length;
            o += buf.write(tmp.slice(i, limit), o);
            buf[o++] = 10;
            i = limit;
        }
        o += buf.write('-----END ' + header + '-----\n', o);
        return (buf.slice(0, o));
    }
}
,
/* sshpk/lib/formats/x509 */ function _(require, module, exports) {
    // Copyright 2017 Joyent, Inc.
    module.exports = {
        read: read,
        verify: verify,
        sign: sign,
        signAsync: signAsync,
        write: write
    };
    var assert = require(53) /* assert-plus */;
    var asn1 = require(52) /* asn1 */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ../algs */;
    var utils = require(354) /* ../utils */;
    var Key = require(350) /* ../key */;
    var PrivateKey = require(351) /* ../private-key */;
    var pem = require(340) /* ./pem */;
    var Identity = require(348) /* ../identity */;
    var Signature = require(352) /* ../signature */;
    var Certificate = require(332) /* ../certificate */;
    var pkcs8 = require(342) /* ./pkcs8 */;
    /*
     * This file is based on RFC5280 (X.509).
     */
    /* Helper to read in a single mpint */
    function readMPInt(der, nm) {
        assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer');
        return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
    }
    function verify(cert, key) {
        var sig = cert.signatures.x509;
        assert.object(sig, 'x509 signature');
        var algParts = sig.algo.split('-');
        if (algParts[0] !== key.type)
            return (false);
        var blob = sig.cache;
        if (blob === undefined) {
            var der = new asn1.BerWriter();
            writeTBSCert(cert, der);
            blob = der.buffer;
        }
        var verifier = key.createVerify(algParts[1]);
        verifier.write(blob);
        return (verifier.verify(sig.signature));
    }
    function Local(i) {
        return (asn1.Ber.Context | asn1.Ber.Constructor | i);
    }
    function Context(i) {
        return (asn1.Ber.Context | i);
    }
    var SIGN_ALGS = {
        'rsa-md5': '1.2.840.113549.1.1.4',
        'rsa-sha1': '1.2.840.113549.1.1.5',
        'rsa-sha256': '1.2.840.113549.1.1.11',
        'rsa-sha384': '1.2.840.113549.1.1.12',
        'rsa-sha512': '1.2.840.113549.1.1.13',
        'dsa-sha1': '1.2.840.10040.4.3',
        'dsa-sha256': '2.16.840.1.101.3.4.3.2',
        'ecdsa-sha1': '1.2.840.10045.4.1',
        'ecdsa-sha256': '1.2.840.10045.4.3.2',
        'ecdsa-sha384': '1.2.840.10045.4.3.3',
        'ecdsa-sha512': '1.2.840.10045.4.3.4',
        'ed25519-sha512': '1.3.101.112'
    };
    Object.keys(SIGN_ALGS).forEach(function (k) {
        SIGN_ALGS[SIGN_ALGS[k]] = k;
    });
    SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5';
    SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1';
    var EXTS = {
        'issuerKeyId': '2.5.29.35',
        'altName': '2.5.29.17',
        'basicConstraints': '2.5.29.19',
        'keyUsage': '2.5.29.15',
        'extKeyUsage': '2.5.29.37'
    };
    function read(buf, options) {
        if (typeof (buf) === 'string') {
            buf = Buffer.from(buf, 'binary');
        }
        assert.buffer(buf, 'buf');
        var der = new asn1.BerReader(buf);
        der.readSequence();
        if (Math.abs(der.length - der.remain) > 1) {
            throw (new Error('DER sequence does not contain whole byte ' +
                'stream'));
        }
        var tbsStart = der.offset;
        der.readSequence();
        var sigOffset = der.offset + der.length;
        var tbsEnd = sigOffset;
        if (der.peek() === Local(0)) {
            der.readSequence(Local(0));
            var version = der.readInt();
            assert.ok(version <= 3, 'only x.509 versions up to v3 supported');
        }
        var cert = {};
        cert.signatures = {};
        var sig = (cert.signatures.x509 = {});
        sig.extras = {};
        cert.serial = readMPInt(der, 'serial');
        der.readSequence();
        var after = der.offset + der.length;
        var certAlgOid = der.readOID();
        var certAlg = SIGN_ALGS[certAlgOid];
        if (certAlg === undefined)
            throw (new Error('unknown signature algorithm ' + certAlgOid));
        der._offset = after;
        cert.issuer = Identity.parseAsn1(der);
        der.readSequence();
        cert.validFrom = readDate(der);
        cert.validUntil = readDate(der);
        cert.subjects = [Identity.parseAsn1(der)];
        der.readSequence();
        after = der.offset + der.length;
        cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der);
        der._offset = after;
        /* issuerUniqueID */
        if (der.peek() === Local(1)) {
            der.readSequence(Local(1));
            sig.extras.issuerUniqueID =
                buf.slice(der.offset, der.offset + der.length);
            der._offset += der.length;
        }
        /* subjectUniqueID */
        if (der.peek() === Local(2)) {
            der.readSequence(Local(2));
            sig.extras.subjectUniqueID =
                buf.slice(der.offset, der.offset + der.length);
            der._offset += der.length;
        }
        /* extensions */
        if (der.peek() === Local(3)) {
            der.readSequence(Local(3));
            var extEnd = der.offset + der.length;
            der.readSequence();
            while (der.offset < extEnd)
                readExtension(cert, buf, der);
            assert.strictEqual(der.offset, extEnd);
        }
        assert.strictEqual(der.offset, sigOffset);
        der.readSequence();
        after = der.offset + der.length;
        var sigAlgOid = der.readOID();
        var sigAlg = SIGN_ALGS[sigAlgOid];
        if (sigAlg === undefined)
            throw (new Error('unknown signature algorithm ' + sigAlgOid));
        der._offset = after;
        var sigData = der.readString(asn1.Ber.BitString, true);
        if (sigData[0] === 0)
            sigData = sigData.slice(1);
        var algParts = sigAlg.split('-');
        sig.signature = Signature.parse(sigData, algParts[0], 'asn1');
        sig.signature.hashAlgorithm = algParts[1];
        sig.algo = sigAlg;
        sig.cache = buf.slice(tbsStart, tbsEnd);
        return (new Certificate(cert));
    }
    function readDate(der) {
        if (der.peek() === asn1.Ber.UTCTime) {
            return (utcTimeToDate(der.readString(asn1.Ber.UTCTime)));
        }
        else if (der.peek() === asn1.Ber.GeneralizedTime) {
            return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime)));
        }
        else {
            throw (new Error('Unsupported date format'));
        }
    }
    /* RFC5280, section 4.2.1.6 (GeneralName type) */
    var ALTNAME = {
        OtherName: Local(0),
        RFC822Name: Context(1),
        DNSName: Context(2),
        X400Address: Local(3),
        DirectoryName: Local(4),
        EDIPartyName: Local(5),
        URI: Context(6),
        IPAddress: Context(7),
        OID: Context(8)
    };
    /* RFC5280, section 4.2.1.12 (KeyPurposeId) */
    var EXTPURPOSE = {
        'serverAuth': '1.3.6.1.5.5.7.3.1',
        'clientAuth': '1.3.6.1.5.5.7.3.2',
        'codeSigning': '1.3.6.1.5.5.7.3.3',
        /* See https://github.com/joyent/oid-docs/blob/master/root.md */
        'joyentDocker': '1.3.6.1.4.1.38678.1.4.1',
        'joyentCmon': '1.3.6.1.4.1.38678.1.4.2'
    };
    var EXTPURPOSE_REV = {};
    Object.keys(EXTPURPOSE).forEach(function (k) {
        EXTPURPOSE_REV[EXTPURPOSE[k]] = k;
    });
    var KEYUSEBITS = [
        'signature', 'identity', 'keyEncryption',
        'encryption', 'keyAgreement', 'ca', 'crl'
    ];
    function readExtension(cert, buf, der) {
        der.readSequence();
        var after = der.offset + der.length;
        var extId = der.readOID();
        var id;
        var sig = cert.signatures.x509;
        sig.extras.exts = [];
        var critical;
        if (der.peek() === asn1.Ber.Boolean)
            critical = der.readBoolean();
        switch (extId) {
            case (EXTS.basicConstraints):
                der.readSequence(asn1.Ber.OctetString);
                der.readSequence();
                var bcEnd = der.offset + der.length;
                var ca = false;
                if (der.peek() === asn1.Ber.Boolean)
                    ca = der.readBoolean();
                if (cert.purposes === undefined)
                    cert.purposes = [];
                if (ca === true)
                    cert.purposes.push('ca');
                var bc = { oid: extId, critical: critical };
                if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer)
                    bc.pathLen = der.readInt();
                sig.extras.exts.push(bc);
                break;
            case (EXTS.extKeyUsage):
                der.readSequence(asn1.Ber.OctetString);
                der.readSequence();
                if (cert.purposes === undefined)
                    cert.purposes = [];
                var ekEnd = der.offset + der.length;
                while (der.offset < ekEnd) {
                    var oid = der.readOID();
                    cert.purposes.push(EXTPURPOSE_REV[oid] || oid);
                }
                /*
                 * This is a bit of a hack: in the case where we have a cert
                 * that's only allowed to do serverAuth or clientAuth (and not
                 * the other), we want to make sure all our Subjects are of
                 * the right type. But we already parsed our Subjects and
                 * decided if they were hosts or users earlier (since it appears
                 * first in the cert).
                 *
                 * So we go through and mutate them into the right kind here if
                 * it doesn't match. This might not be hugely beneficial, as it
                 * seems that single-purpose certs are not often seen in the
                 * wild.
                 */
                if (cert.purposes.indexOf('serverAuth') !== -1 &&
                    cert.purposes.indexOf('clientAuth') === -1) {
                    cert.subjects.forEach(function (ide) {
                        if (ide.type !== 'host') {
                            ide.type = 'host';
                            ide.hostname = ide.uid ||
                                ide.email ||
                                ide.components[0].value;
                        }
                    });
                }
                else if (cert.purposes.indexOf('clientAuth') !== -1 &&
                    cert.purposes.indexOf('serverAuth') === -1) {
                    cert.subjects.forEach(function (ide) {
                        if (ide.type !== 'user') {
                            ide.type = 'user';
                            ide.uid = ide.hostname ||
                                ide.email ||
                                ide.components[0].value;
                        }
                    });
                }
                sig.extras.exts.push({ oid: extId, critical: critical });
                break;
            case (EXTS.keyUsage):
                der.readSequence(asn1.Ber.OctetString);
                var bits = der.readString(asn1.Ber.BitString, true);
                var setBits = readBitField(bits, KEYUSEBITS);
                setBits.forEach(function (bit) {
                    if (cert.purposes === undefined)
                        cert.purposes = [];
                    if (cert.purposes.indexOf(bit) === -1)
                        cert.purposes.push(bit);
                });
                sig.extras.exts.push({ oid: extId, critical: critical,
                    bits: bits });
                break;
            case (EXTS.altName):
                der.readSequence(asn1.Ber.OctetString);
                der.readSequence();
                var aeEnd = der.offset + der.length;
                while (der.offset < aeEnd) {
                    switch (der.peek()) {
                        case ALTNAME.OtherName:
                        case ALTNAME.EDIPartyName:
                            der.readSequence();
                            der._offset += der.length;
                            break;
                        case ALTNAME.OID:
                            der.readOID(ALTNAME.OID);
                            break;
                        case ALTNAME.RFC822Name:
                            /* RFC822 specifies email addresses */
                            var email = der.readString(ALTNAME.RFC822Name);
                            id = Identity.forEmail(email);
                            if (!cert.subjects[0].equals(id))
                                cert.subjects.push(id);
                            break;
                        case ALTNAME.DirectoryName:
                            der.readSequence(ALTNAME.DirectoryName);
                            id = Identity.parseAsn1(der);
                            if (!cert.subjects[0].equals(id))
                                cert.subjects.push(id);
                            break;
                        case ALTNAME.DNSName:
                            var host = der.readString(ALTNAME.DNSName);
                            id = Identity.forHost(host);
                            if (!cert.subjects[0].equals(id))
                                cert.subjects.push(id);
                            break;
                        default:
                            der.readString(der.peek());
                            break;
                    }
                }
                sig.extras.exts.push({ oid: extId, critical: critical });
                break;
            default:
                sig.extras.exts.push({
                    oid: extId,
                    critical: critical,
                    data: der.readString(asn1.Ber.OctetString, true)
                });
                break;
        }
        der._offset = after;
    }
    var UTCTIME_RE = /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
    function utcTimeToDate(t) {
        var m = t.match(UTCTIME_RE);
        assert.ok(m, 'timestamps must be in UTC');
        var d = new Date();
        var thisYear = d.getUTCFullYear();
        var century = Math.floor(thisYear / 100) * 100;
        var year = parseInt(m[1], 10);
        if (thisYear % 100 < 50 && year >= 60)
            year += (century - 1);
        else
            year += century;
        d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10));
        d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
        if (m[6] && m[6].length > 0)
            d.setUTCSeconds(parseInt(m[6], 10));
        return (d);
    }
    var GTIME_RE = /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
    function gTimeToDate(t) {
        var m = t.match(GTIME_RE);
        assert.ok(m);
        var d = new Date();
        d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1, parseInt(m[3], 10));
        d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
        if (m[6] && m[6].length > 0)
            d.setUTCSeconds(parseInt(m[6], 10));
        return (d);
    }
    function zeroPad(n) {
        var s = '' + n;
        while (s.length < 2)
            s = '0' + s;
        return (s);
    }
    function dateToUTCTime(d) {
        var s = '';
        s += zeroPad(d.getUTCFullYear() % 100);
        s += zeroPad(d.getUTCMonth() + 1);
        s += zeroPad(d.getUTCDate());
        s += zeroPad(d.getUTCHours());
        s += zeroPad(d.getUTCMinutes());
        s += zeroPad(d.getUTCSeconds());
        s += 'Z';
        return (s);
    }
    function sign(cert, key) {
        if (cert.signatures.x509 === undefined)
            cert.signatures.x509 = {};
        var sig = cert.signatures.x509;
        sig.algo = key.type + '-' + key.defaultHashAlgorithm();
        if (SIGN_ALGS[sig.algo] === undefined)
            return (false);
        var der = new asn1.BerWriter();
        writeTBSCert(cert, der);
        var blob = der.buffer;
        sig.cache = blob;
        var signer = key.createSign();
        signer.write(blob);
        cert.signatures.x509.signature = signer.sign();
        return (true);
    }
    function signAsync(cert, signer, done) {
        if (cert.signatures.x509 === undefined)
            cert.signatures.x509 = {};
        var sig = cert.signatures.x509;
        var der = new asn1.BerWriter();
        writeTBSCert(cert, der);
        var blob = der.buffer;
        sig.cache = blob;
        signer(blob, function (err, signature) {
            if (err) {
                done(err);
                return;
            }
            sig.algo = signature.type + '-' + signature.hashAlgorithm;
            if (SIGN_ALGS[sig.algo] === undefined) {
                done(new Error('Invalid signing algorithm "' +
                    sig.algo + '"'));
                return;
            }
            sig.signature = signature;
            done();
        });
    }
    function write(cert, options) {
        var sig = cert.signatures.x509;
        assert.object(sig, 'x509 signature');
        var der = new asn1.BerWriter();
        der.startSequence();
        if (sig.cache) {
            der._ensure(sig.cache.length);
            sig.cache.copy(der._buf, der._offset);
            der._offset += sig.cache.length;
        }
        else {
            writeTBSCert(cert, der);
        }
        der.startSequence();
        der.writeOID(SIGN_ALGS[sig.algo]);
        if (sig.algo.match(/^rsa-/))
            der.writeNull();
        der.endSequence();
        var sigData = sig.signature.toBuffer('asn1');
        var data = Buffer.alloc(sigData.length + 1);
        data[0] = 0;
        sigData.copy(data, 1);
        der.writeBuffer(data, asn1.Ber.BitString);
        der.endSequence();
        return (der.buffer);
    }
    function writeTBSCert(cert, der) {
        var sig = cert.signatures.x509;
        assert.object(sig, 'x509 signature');
        der.startSequence();
        der.startSequence(Local(0));
        der.writeInt(2);
        der.endSequence();
        der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer);
        der.startSequence();
        der.writeOID(SIGN_ALGS[sig.algo]);
        if (sig.algo.match(/^rsa-/))
            der.writeNull();
        der.endSequence();
        cert.issuer.toAsn1(der);
        der.startSequence();
        der.writeString(dateToUTCTime(cert.validFrom), asn1.Ber.UTCTime);
        der.writeString(dateToUTCTime(cert.validUntil), asn1.Ber.UTCTime);
        der.endSequence();
        var subject = cert.subjects[0];
        var altNames = cert.subjects.slice(1);
        subject.toAsn1(der);
        pkcs8.writePkcs8(der, cert.subjectKey);
        if (sig.extras && sig.extras.issuerUniqueID) {
            der.writeBuffer(sig.extras.issuerUniqueID, Local(1));
        }
        if (sig.extras && sig.extras.subjectUniqueID) {
            der.writeBuffer(sig.extras.subjectUniqueID, Local(2));
        }
        if (altNames.length > 0 || subject.type === 'host' ||
            (cert.purposes !== undefined && cert.purposes.length > 0) ||
            (sig.extras && sig.extras.exts)) {
            der.startSequence(Local(3));
            der.startSequence();
            var exts = [];
            if (cert.purposes !== undefined && cert.purposes.length > 0) {
                exts.push({
                    oid: EXTS.basicConstraints,
                    critical: true
                });
                exts.push({
                    oid: EXTS.keyUsage,
                    critical: true
                });
                exts.push({
                    oid: EXTS.extKeyUsage,
                    critical: true
                });
            }
            exts.push({ oid: EXTS.altName });
            if (sig.extras && sig.extras.exts)
                exts = sig.extras.exts;
            for (var i = 0; i < exts.length; ++i) {
                der.startSequence();
                der.writeOID(exts[i].oid);
                if (exts[i].critical !== undefined)
                    der.writeBoolean(exts[i].critical);
                if (exts[i].oid === EXTS.altName) {
                    der.startSequence(asn1.Ber.OctetString);
                    der.startSequence();
                    if (subject.type === 'host') {
                        der.writeString(subject.hostname, Context(2));
                    }
                    for (var j = 0; j < altNames.length; ++j) {
                        if (altNames[j].type === 'host') {
                            der.writeString(altNames[j].hostname, ALTNAME.DNSName);
                        }
                        else if (altNames[j].type ===
                            'email') {
                            der.writeString(altNames[j].email, ALTNAME.RFC822Name);
                        }
                        else {
                            /*
                             * Encode anything else as a
                             * DN style name for now.
                             */
                            der.startSequence(ALTNAME.DirectoryName);
                            altNames[j].toAsn1(der);
                            der.endSequence();
                        }
                    }
                    der.endSequence();
                    der.endSequence();
                }
                else if (exts[i].oid === EXTS.basicConstraints) {
                    der.startSequence(asn1.Ber.OctetString);
                    der.startSequence();
                    var ca = (cert.purposes.indexOf('ca') !== -1);
                    var pathLen = exts[i].pathLen;
                    der.writeBoolean(ca);
                    if (pathLen !== undefined)
                        der.writeInt(pathLen);
                    der.endSequence();
                    der.endSequence();
                }
                else if (exts[i].oid === EXTS.extKeyUsage) {
                    der.startSequence(asn1.Ber.OctetString);
                    der.startSequence();
                    cert.purposes.forEach(function (purpose) {
                        if (purpose === 'ca')
                            return;
                        if (KEYUSEBITS.indexOf(purpose) !== -1)
                            return;
                        var oid = purpose;
                        if (EXTPURPOSE[purpose] !== undefined)
                            oid = EXTPURPOSE[purpose];
                        der.writeOID(oid);
                    });
                    der.endSequence();
                    der.endSequence();
                }
                else if (exts[i].oid === EXTS.keyUsage) {
                    der.startSequence(asn1.Ber.OctetString);
                    /*
                     * If we parsed this certificate from a byte
                     * stream (i.e. we didn't generate it in sshpk)
                     * then we'll have a ".bits" property on the
                     * ext with the original raw byte contents.
                     *
                     * If we have this, use it here instead of
                     * regenerating it. This guarantees we output
                     * the same data we parsed, so signatures still
                     * validate.
                     */
                    if (exts[i].bits !== undefined) {
                        der.writeBuffer(exts[i].bits, asn1.Ber.BitString);
                    }
                    else {
                        var bits = writeBitField(cert.purposes, KEYUSEBITS);
                        der.writeBuffer(bits, asn1.Ber.BitString);
                    }
                    der.endSequence();
                }
                else {
                    der.writeBuffer(exts[i].data, asn1.Ber.OctetString);
                }
                der.endSequence();
            }
            der.endSequence();
            der.endSequence();
        }
        der.endSequence();
    }
    /*
     * Reads an ASN.1 BER bitfield out of the Buffer produced by doing
     * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw
     * contents of the BitString tag, which is a count of unused bits followed by
     * the bits as a right-padded byte string.
     *
     * `bits` is the Buffer, `bitIndex` should contain an array of string names
     * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec.
     *
     * Returns an array of Strings, the names of the bits that were set to 1.
     */
    function readBitField(bits, bitIndex) {
        var bitLen = 8 * (bits.length - 1) - bits[0];
        var setBits = {};
        for (var i = 0; i < bitLen; ++i) {
            var byteN = 1 + Math.floor(i / 8);
            var bit = 7 - (i % 8);
            var mask = 1 << bit;
            var bitVal = ((bits[byteN] & mask) !== 0);
            var name = bitIndex[i];
            if (bitVal && typeof (name) === 'string') {
                setBits[name] = true;
            }
        }
        return (Object.keys(setBits));
    }
    /*
     * `setBits` is an array of strings, containing the names for each bit that
     * sould be set to 1. `bitIndex` is same as in `readBitField()`.
     *
     * Returns a Buffer, ready to be written out with `BerWriter#writeString()`.
     */
    function writeBitField(setBits, bitIndex) {
        var bitLen = bitIndex.length;
        var blen = Math.ceil(bitLen / 8);
        var unused = blen * 8 - bitLen;
        var bits = Buffer.alloc(1 + blen); // zero-filled
        bits[0] = unused;
        for (var i = 0; i < bitLen; ++i) {
            var byteN = 1 + Math.floor(i / 8);
            var bit = 7 - (i % 8);
            var mask = 1 << bit;
            var name = bitIndex[i];
            if (name === undefined)
                continue;
            var bitVal = (setBits.indexOf(name) !== -1);
            if (bitVal) {
                bits[byteN] |= mask;
            }
        }
        return (bits);
    }
}
,
/* sshpk/lib/identity */ function _(require, module, exports) {
    // Copyright 2017 Joyent, Inc.
    module.exports = Identity;
    var assert = require(53) /* assert-plus */;
    var algs = require(331) /* ./algs */;
    var crypto = require('crypto');
    var Fingerprint = require(336) /* ./fingerprint */;
    var Signature = require(352) /* ./signature */;
    var errs = require(335) /* ./errors */;
    var util = require('util');
    var utils = require(354) /* ./utils */;
    var asn1 = require(52) /* asn1 */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    /*JSSTYLED*/
    var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i;
    var oids = {};
    oids.cn = '2.5.4.3';
    oids.o = '2.5.4.10';
    oids.ou = '2.5.4.11';
    oids.l = '2.5.4.7';
    oids.s = '2.5.4.8';
    oids.c = '2.5.4.6';
    oids.sn = '2.5.4.4';
    oids.dc = '0.9.2342.19200300.100.1.25';
    oids.uid = '0.9.2342.19200300.100.1.1';
    oids.mail = '0.9.2342.19200300.100.1.3';
    var unoids = {};
    Object.keys(oids).forEach(function (k) {
        unoids[oids[k]] = k;
    });
    function Identity(opts) {
        var self = this;
        assert.object(opts, 'options');
        assert.arrayOfObject(opts.components, 'options.components');
        this.components = opts.components;
        this.componentLookup = {};
        this.components.forEach(function (c) {
            if (c.name && !c.oid)
                c.oid = oids[c.name];
            if (c.oid && !c.name)
                c.name = unoids[c.oid];
            if (self.componentLookup[c.name] === undefined)
                self.componentLookup[c.name] = [];
            self.componentLookup[c.name].push(c);
        });
        if (this.componentLookup.cn && this.componentLookup.cn.length > 0) {
            this.cn = this.componentLookup.cn[0].value;
        }
        assert.optionalString(opts.type, 'options.type');
        if (opts.type === undefined) {
            if (this.components.length === 1 &&
                this.componentLookup.cn &&
                this.componentLookup.cn.length === 1 &&
                this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
                this.type = 'host';
                this.hostname = this.componentLookup.cn[0].value;
            }
            else if (this.componentLookup.dc &&
                this.components.length === this.componentLookup.dc.length) {
                this.type = 'host';
                this.hostname = this.componentLookup.dc.map(function (c) {
                    return (c.value);
                }).join('.');
            }
            else if (this.componentLookup.uid &&
                this.components.length ===
                    this.componentLookup.uid.length) {
                this.type = 'user';
                this.uid = this.componentLookup.uid[0].value;
            }
            else if (this.componentLookup.cn &&
                this.componentLookup.cn.length === 1 &&
                this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
                this.type = 'host';
                this.hostname = this.componentLookup.cn[0].value;
            }
            else if (this.componentLookup.uid &&
                this.componentLookup.uid.length === 1) {
                this.type = 'user';
                this.uid = this.componentLookup.uid[0].value;
            }
            else if (this.componentLookup.mail &&
                this.componentLookup.mail.length === 1) {
                this.type = 'email';
                this.email = this.componentLookup.mail[0].value;
            }
            else if (this.componentLookup.cn &&
                this.componentLookup.cn.length === 1) {
                this.type = 'user';
                this.uid = this.componentLookup.cn[0].value;
            }
            else {
                this.type = 'unknown';
            }
        }
        else {
            this.type = opts.type;
            if (this.type === 'host')
                this.hostname = opts.hostname;
            else if (this.type === 'user')
                this.uid = opts.uid;
            else if (this.type === 'email')
                this.email = opts.email;
            else
                throw (new Error('Unknown type ' + this.type));
        }
    }
    Identity.prototype.toString = function () {
        return (this.components.map(function (c) {
            return (c.name.toUpperCase() + '=' + c.value);
        }).join(', '));
    };
    /*
     * These are from X.680 -- PrintableString allowed chars are in section 37.4
     * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to
     * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006
     * (the basic ASCII character set).
     */
    /* JSSTYLED */
    var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/;
    /* JSSTYLED */
    var NOT_IA5 = /[^\x00-\x7f]/;
    Identity.prototype.toAsn1 = function (der, tag) {
        der.startSequence(tag);
        this.components.forEach(function (c) {
            der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set);
            der.startSequence();
            der.writeOID(c.oid);
            /*
             * If we fit in a PrintableString, use that. Otherwise use an
             * IA5String or UTF8String.
             *
             * If this identity was parsed from a DN, use the ASN.1 types
             * from the original representation (otherwise this might not
             * be a full match for the original in some validators).
             */
            if (c.asn1type === asn1.Ber.Utf8String ||
                c.value.match(NOT_IA5)) {
                var v = Buffer.from(c.value, 'utf8');
                der.writeBuffer(v, asn1.Ber.Utf8String);
            }
            else if (c.asn1type === asn1.Ber.IA5String ||
                c.value.match(NOT_PRINTABLE)) {
                der.writeString(c.value, asn1.Ber.IA5String);
            }
            else {
                var type = asn1.Ber.PrintableString;
                if (c.asn1type !== undefined)
                    type = c.asn1type;
                der.writeString(c.value, type);
            }
            der.endSequence();
            der.endSequence();
        });
        der.endSequence();
    };
    function globMatch(a, b) {
        if (a === '**' || b === '**')
            return (true);
        var aParts = a.split('.');
        var bParts = b.split('.');
        if (aParts.length !== bParts.length)
            return (false);
        for (var i = 0; i < aParts.length; ++i) {
            if (aParts[i] === '*' || bParts[i] === '*')
                continue;
            if (aParts[i] !== bParts[i])
                return (false);
        }
        return (true);
    }
    Identity.prototype.equals = function (other) {
        if (!Identity.isIdentity(other, [1, 0]))
            return (false);
        if (other.components.length !== this.components.length)
            return (false);
        for (var i = 0; i < this.components.length; ++i) {
            if (this.components[i].oid !== other.components[i].oid)
                return (false);
            if (!globMatch(this.components[i].value, other.components[i].value)) {
                return (false);
            }
        }
        return (true);
    };
    Identity.forHost = function (hostname) {
        assert.string(hostname, 'hostname');
        return (new Identity({
            type: 'host',
            hostname: hostname,
            components: [{ name: 'cn', value: hostname }]
        }));
    };
    Identity.forUser = function (uid) {
        assert.string(uid, 'uid');
        return (new Identity({
            type: 'user',
            uid: uid,
            components: [{ name: 'uid', value: uid }]
        }));
    };
    Identity.forEmail = function (email) {
        assert.string(email, 'email');
        return (new Identity({
            type: 'email',
            email: email,
            components: [{ name: 'mail', value: email }]
        }));
    };
    Identity.parseDN = function (dn) {
        assert.string(dn, 'dn');
        var parts = dn.split(',');
        var cmps = parts.map(function (c) {
            c = c.trim();
            var eqPos = c.indexOf('=');
            var name = c.slice(0, eqPos).toLowerCase();
            var value = c.slice(eqPos + 1);
            return ({ name: name, value: value });
        });
        return (new Identity({ components: cmps }));
    };
    Identity.parseAsn1 = function (der, top) {
        var components = [];
        der.readSequence(top);
        var end = der.offset + der.length;
        while (der.offset < end) {
            der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set);
            var after = der.offset + der.length;
            der.readSequence();
            var oid = der.readOID();
            var type = der.peek();
            var value;
            switch (type) {
                case asn1.Ber.PrintableString:
                case asn1.Ber.IA5String:
                case asn1.Ber.OctetString:
                case asn1.Ber.T61String:
                    value = der.readString(type);
                    break;
                case asn1.Ber.Utf8String:
                    value = der.readString(type, true);
                    value = value.toString('utf8');
                    break;
                case asn1.Ber.CharacterString:
                case asn1.Ber.BMPString:
                    value = der.readString(type, true);
                    value = value.toString('utf16le');
                    break;
                default:
                    throw (new Error('Unknown asn1 type ' + type));
            }
            components.push({ oid: oid, asn1type: type, value: value });
            der._offset = after;
        }
        der._offset = end;
        return (new Identity({
            components: components
        }));
    };
    Identity.isIdentity = function (obj, ver) {
        return (utils.isCompatible(obj, Identity, ver));
    };
    /*
     * API versions for Identity:
     * [1,0] -- initial ver
     */
    Identity.prototype._sshpkApiVersion = [1, 0];
    Identity._oldVersionDetect = function (obj) {
        return ([1, 0]);
    };
}
,
/* sshpk/lib/index */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    var Key = require(350) /* ./key */;
    var Fingerprint = require(336) /* ./fingerprint */;
    var Signature = require(352) /* ./signature */;
    var PrivateKey = require(351) /* ./private-key */;
    var Certificate = require(332) /* ./certificate */;
    var Identity = require(348) /* ./identity */;
    var errs = require(335) /* ./errors */;
    module.exports = {
        /* top-level classes */
        Key: Key,
        parseKey: Key.parse,
        Fingerprint: Fingerprint,
        parseFingerprint: Fingerprint.parse,
        Signature: Signature,
        parseSignature: Signature.parse,
        PrivateKey: PrivateKey,
        parsePrivateKey: PrivateKey.parse,
        generatePrivateKey: PrivateKey.generate,
        Certificate: Certificate,
        parseCertificate: Certificate.parse,
        createSelfSignedCertificate: Certificate.createSelfSigned,
        createCertificate: Certificate.create,
        Identity: Identity,
        identityFromDN: Identity.parseDN,
        identityForHost: Identity.forHost,
        identityForUser: Identity.forUser,
        identityForEmail: Identity.forEmail,
        /* errors */
        FingerprintFormatError: errs.FingerprintFormatError,
        InvalidAlgorithmError: errs.InvalidAlgorithmError,
        KeyParseError: errs.KeyParseError,
        SignatureParseError: errs.SignatureParseError,
        KeyEncryptedError: errs.KeyEncryptedError,
        CertificateParseError: errs.CertificateParseError
    };
}
,
/* sshpk/lib/key */ function _(require, module, exports) {
    // Copyright 2017 Joyent, Inc.
    module.exports = Key;
    var assert = require(53) /* assert-plus */;
    var algs = require(331) /* ./algs */;
    var crypto = require('crypto');
    var Fingerprint = require(336) /* ./fingerprint */;
    var Signature = require(352) /* ./signature */;
    var DiffieHellman = require(333) /* ./dhe */.DiffieHellman;
    var errs = require(335) /* ./errors */;
    var utils = require(354) /* ./utils */;
    var PrivateKey = require(351) /* ./private-key */;
    var edCompat;
    try {
        edCompat = require(334) /* ./ed-compat */;
    }
    catch (e) {
        /* Just continue through, and bail out if we try to use it. */
    }
    var InvalidAlgorithmError = errs.InvalidAlgorithmError;
    var KeyParseError = errs.KeyParseError;
    var formats = {};
    formats['auto'] = require(337) /* ./formats/auto */;
    formats['pem'] = require(340) /* ./formats/pem */;
    formats['pkcs1'] = require(341) /* ./formats/pkcs1 */;
    formats['pkcs8'] = require(342) /* ./formats/pkcs8 */;
    formats['rfc4253'] = require(343) /* ./formats/rfc4253 */;
    formats['ssh'] = require(345) /* ./formats/ssh */;
    formats['ssh-private'] = require(344) /* ./formats/ssh-private */;
    formats['openssh'] = formats['ssh-private'];
    formats['dnssec'] = require(338) /* ./formats/dnssec */;
    function Key(opts) {
        assert.object(opts, 'options');
        assert.arrayOfObject(opts.parts, 'options.parts');
        assert.string(opts.type, 'options.type');
        assert.optionalString(opts.comment, 'options.comment');
        var algInfo = algs.info[opts.type];
        if (typeof (algInfo) !== 'object')
            throw (new InvalidAlgorithmError(opts.type));
        var partLookup = {};
        for (var i = 0; i < opts.parts.length; ++i) {
            var part = opts.parts[i];
            partLookup[part.name] = part;
        }
        this.type = opts.type;
        this.parts = opts.parts;
        this.part = partLookup;
        this.comment = undefined;
        this.source = opts.source;
        /* for speeding up hashing/fingerprint operations */
        this._rfc4253Cache = opts._rfc4253Cache;
        this._hashCache = {};
        var sz;
        this.curve = undefined;
        if (this.type === 'ecdsa') {
            var curve = this.part.curve.data.toString();
            this.curve = curve;
            sz = algs.curves[curve].size;
        }
        else if (this.type === 'ed25519' || this.type === 'curve25519') {
            sz = 256;
            this.curve = 'curve25519';
        }
        else {
            var szPart = this.part[algInfo.sizePart];
            sz = szPart.data.length;
            sz = sz * 8 - utils.countZeros(szPart.data);
        }
        this.size = sz;
    }
    Key.formats = formats;
    Key.prototype.toBuffer = function (format, options) {
        if (format === undefined)
            format = 'ssh';
        assert.string(format, 'format');
        assert.object(formats[format], 'formats[format]');
        assert.optionalObject(options, 'options');
        if (format === 'rfc4253') {
            if (this._rfc4253Cache === undefined)
                this._rfc4253Cache = formats['rfc4253'].write(this);
            return (this._rfc4253Cache);
        }
        return (formats[format].write(this, options));
    };
    Key.prototype.toString = function (format, options) {
        return (this.toBuffer(format, options).toString());
    };
    Key.prototype.hash = function (algo) {
        assert.string(algo, 'algorithm');
        algo = algo.toLowerCase();
        if (algs.hashAlgs[algo] === undefined)
            throw (new InvalidAlgorithmError(algo));
        if (this._hashCache[algo])
            return (this._hashCache[algo]);
        var hash = crypto.createHash(algo).
            update(this.toBuffer('rfc4253')).digest();
        this._hashCache[algo] = hash;
        return (hash);
    };
    Key.prototype.fingerprint = function (algo) {
        if (algo === undefined)
            algo = 'sha256';
        assert.string(algo, 'algorithm');
        var opts = {
            type: 'key',
            hash: this.hash(algo),
            algorithm: algo
        };
        return (new Fingerprint(opts));
    };
    Key.prototype.defaultHashAlgorithm = function () {
        var hashAlgo = 'sha1';
        if (this.type === 'rsa')
            hashAlgo = 'sha256';
        if (this.type === 'dsa' && this.size > 1024)
            hashAlgo = 'sha256';
        if (this.type === 'ed25519')
            hashAlgo = 'sha512';
        if (this.type === 'ecdsa') {
            if (this.size <= 256)
                hashAlgo = 'sha256';
            else if (this.size <= 384)
                hashAlgo = 'sha384';
            else
                hashAlgo = 'sha512';
        }
        return (hashAlgo);
    };
    Key.prototype.createVerify = function (hashAlgo) {
        if (hashAlgo === undefined)
            hashAlgo = this.defaultHashAlgorithm();
        assert.string(hashAlgo, 'hash algorithm');
        /* ED25519 is not supported by OpenSSL, use a javascript impl. */
        if (this.type === 'ed25519' && edCompat !== undefined)
            return (new edCompat.Verifier(this, hashAlgo));
        if (this.type === 'curve25519')
            throw (new Error('Curve25519 keys are not suitable for ' +
                'signing or verification'));
        var v, nm, err;
        try {
            nm = hashAlgo.toUpperCase();
            v = crypto.createVerify(nm);
        }
        catch (e) {
            err = e;
        }
        if (v === undefined || (err instanceof Error &&
            err.message.match(/Unknown message digest/))) {
            nm = 'RSA-';
            nm += hashAlgo.toUpperCase();
            v = crypto.createVerify(nm);
        }
        assert.ok(v, 'failed to create verifier');
        var oldVerify = v.verify.bind(v);
        var key = this.toBuffer('pkcs8');
        var curve = this.curve;
        var self = this;
        v.verify = function (signature, fmt) {
            if (Signature.isSignature(signature, [2, 0])) {
                if (signature.type !== self.type)
                    return (false);
                if (signature.hashAlgorithm &&
                    signature.hashAlgorithm !== hashAlgo)
                    return (false);
                if (signature.curve && self.type === 'ecdsa' &&
                    signature.curve !== curve)
                    return (false);
                return (oldVerify(key, signature.toBuffer('asn1')));
            }
            else if (typeof (signature) === 'string' ||
                Buffer.isBuffer(signature)) {
                return (oldVerify(key, signature, fmt));
                /*
                 * Avoid doing this on valid arguments, walking the prototype
                 * chain can be quite slow.
                 */
            }
            else if (Signature.isSignature(signature, [1, 0])) {
                throw (new Error('signature was created by too old ' +
                    'a version of sshpk and cannot be verified'));
            }
            else {
                throw (new TypeError('signature must be a string, ' +
                    'Buffer, or Signature object'));
            }
        };
        return (v);
    };
    Key.prototype.createDiffieHellman = function () {
        if (this.type === 'rsa')
            throw (new Error('RSA keys do not support Diffie-Hellman'));
        return (new DiffieHellman(this));
    };
    Key.prototype.createDH = Key.prototype.createDiffieHellman;
    Key.parse = function (data, format, options) {
        if (typeof (data) !== 'string')
            assert.buffer(data, 'data');
        if (format === undefined)
            format = 'auto';
        assert.string(format, 'format');
        if (typeof (options) === 'string')
            options = { filename: options };
        assert.optionalObject(options, 'options');
        if (options === undefined)
            options = {};
        assert.optionalString(options.filename, 'options.filename');
        if (options.filename === undefined)
            options.filename = '(unnamed)';
        assert.object(formats[format], 'formats[format]');
        try {
            var k = formats[format].read(data, options);
            if (k instanceof PrivateKey)
                k = k.toPublic();
            if (!k.comment)
                k.comment = options.filename;
            return (k);
        }
        catch (e) {
            if (e.name === 'KeyEncryptedError')
                throw (e);
            throw (new KeyParseError(options.filename, format, e));
        }
    };
    Key.isKey = function (obj, ver) {
        return (utils.isCompatible(obj, Key, ver));
    };
    /*
     * API versions for Key:
     * [1,0] -- initial ver, may take Signature for createVerify or may not
     * [1,1] -- added pkcs1, pkcs8 formats
     * [1,2] -- added auto, ssh-private, openssh formats
     * [1,3] -- added defaultHashAlgorithm
     * [1,4] -- added ed support, createDH
     * [1,5] -- first explicitly tagged version
     * [1,6] -- changed ed25519 part names
     */
    Key.prototype._sshpkApiVersion = [1, 6];
    Key._oldVersionDetect = function (obj) {
        assert.func(obj.toBuffer);
        assert.func(obj.fingerprint);
        if (obj.createDH)
            return ([1, 4]);
        if (obj.defaultHashAlgorithm)
            return ([1, 3]);
        if (obj.formats['auto'])
            return ([1, 2]);
        if (obj.formats['pkcs1'])
            return ([1, 1]);
        return ([1, 0]);
    };
}
,
/* sshpk/lib/private-key */ function _(require, module, exports) {
    // Copyright 2017 Joyent, Inc.
    module.exports = PrivateKey;
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ./algs */;
    var crypto = require('crypto');
    var Fingerprint = require(336) /* ./fingerprint */;
    var Signature = require(352) /* ./signature */;
    var errs = require(335) /* ./errors */;
    var util = require('util');
    var utils = require(354) /* ./utils */;
    var dhe = require(333) /* ./dhe */;
    var generateECDSA = dhe.generateECDSA;
    var generateED25519 = dhe.generateED25519;
    var edCompat;
    var nacl;
    try {
        edCompat = require(334) /* ./ed-compat */;
    }
    catch (e) {
        /* Just continue through, and bail out if we try to use it. */
    }
    var Key = require(350) /* ./key */;
    var InvalidAlgorithmError = errs.InvalidAlgorithmError;
    var KeyParseError = errs.KeyParseError;
    var KeyEncryptedError = errs.KeyEncryptedError;
    var formats = {};
    formats['auto'] = require(337) /* ./formats/auto */;
    formats['pem'] = require(340) /* ./formats/pem */;
    formats['pkcs1'] = require(341) /* ./formats/pkcs1 */;
    formats['pkcs8'] = require(342) /* ./formats/pkcs8 */;
    formats['rfc4253'] = require(343) /* ./formats/rfc4253 */;
    formats['ssh-private'] = require(344) /* ./formats/ssh-private */;
    formats['openssh'] = formats['ssh-private'];
    formats['ssh'] = formats['ssh-private'];
    formats['dnssec'] = require(338) /* ./formats/dnssec */;
    function PrivateKey(opts) {
        assert.object(opts, 'options');
        Key.call(this, opts);
        this._pubCache = undefined;
    }
    util.inherits(PrivateKey, Key);
    PrivateKey.formats = formats;
    PrivateKey.prototype.toBuffer = function (format, options) {
        if (format === undefined)
            format = 'pkcs1';
        assert.string(format, 'format');
        assert.object(formats[format], 'formats[format]');
        assert.optionalObject(options, 'options');
        return (formats[format].write(this, options));
    };
    PrivateKey.prototype.hash = function (algo) {
        return (this.toPublic().hash(algo));
    };
    PrivateKey.prototype.toPublic = function () {
        if (this._pubCache)
            return (this._pubCache);
        var algInfo = algs.info[this.type];
        var pubParts = [];
        for (var i = 0; i < algInfo.parts.length; ++i) {
            var p = algInfo.parts[i];
            pubParts.push(this.part[p]);
        }
        this._pubCache = new Key({
            type: this.type,
            source: this,
            parts: pubParts
        });
        if (this.comment)
            this._pubCache.comment = this.comment;
        return (this._pubCache);
    };
    PrivateKey.prototype.derive = function (newType) {
        assert.string(newType, 'type');
        var priv, pub, pair;
        if (this.type === 'ed25519' && newType === 'curve25519') {
            if (nacl === undefined)
                nacl = require(366) /* tweetnacl */;
            priv = this.part.k.data;
            if (priv[0] === 0x00)
                priv = priv.slice(1);
            pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv));
            pub = Buffer.from(pair.publicKey);
            return (new PrivateKey({
                type: 'curve25519',
                parts: [
                    { name: 'A', data: utils.mpNormalize(pub) },
                    { name: 'k', data: utils.mpNormalize(priv) }
                ]
            }));
        }
        else if (this.type === 'curve25519' && newType === 'ed25519') {
            if (nacl === undefined)
                nacl = require(366) /* tweetnacl */;
            priv = this.part.k.data;
            if (priv[0] === 0x00)
                priv = priv.slice(1);
            pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv));
            pub = Buffer.from(pair.publicKey);
            return (new PrivateKey({
                type: 'ed25519',
                parts: [
                    { name: 'A', data: utils.mpNormalize(pub) },
                    { name: 'k', data: utils.mpNormalize(priv) }
                ]
            }));
        }
        throw (new Error('Key derivation not supported from ' + this.type +
            ' to ' + newType));
    };
    PrivateKey.prototype.createVerify = function (hashAlgo) {
        return (this.toPublic().createVerify(hashAlgo));
    };
    PrivateKey.prototype.createSign = function (hashAlgo) {
        if (hashAlgo === undefined)
            hashAlgo = this.defaultHashAlgorithm();
        assert.string(hashAlgo, 'hash algorithm');
        /* ED25519 is not supported by OpenSSL, use a javascript impl. */
        if (this.type === 'ed25519' && edCompat !== undefined)
            return (new edCompat.Signer(this, hashAlgo));
        if (this.type === 'curve25519')
            throw (new Error('Curve25519 keys are not suitable for ' +
                'signing or verification'));
        var v, nm, err;
        try {
            nm = hashAlgo.toUpperCase();
            v = crypto.createSign(nm);
        }
        catch (e) {
            err = e;
        }
        if (v === undefined || (err instanceof Error &&
            err.message.match(/Unknown message digest/))) {
            nm = 'RSA-';
            nm += hashAlgo.toUpperCase();
            v = crypto.createSign(nm);
        }
        assert.ok(v, 'failed to create verifier');
        var oldSign = v.sign.bind(v);
        var key = this.toBuffer('pkcs1');
        var type = this.type;
        var curve = this.curve;
        v.sign = function () {
            var sig = oldSign(key);
            if (typeof (sig) === 'string')
                sig = Buffer.from(sig, 'binary');
            sig = Signature.parse(sig, type, 'asn1');
            sig.hashAlgorithm = hashAlgo;
            sig.curve = curve;
            return (sig);
        };
        return (v);
    };
    PrivateKey.parse = function (data, format, options) {
        if (typeof (data) !== 'string')
            assert.buffer(data, 'data');
        if (format === undefined)
            format = 'auto';
        assert.string(format, 'format');
        if (typeof (options) === 'string')
            options = { filename: options };
        assert.optionalObject(options, 'options');
        if (options === undefined)
            options = {};
        assert.optionalString(options.filename, 'options.filename');
        if (options.filename === undefined)
            options.filename = '(unnamed)';
        assert.object(formats[format], 'formats[format]');
        try {
            var k = formats[format].read(data, options);
            assert.ok(k instanceof PrivateKey, 'key is not a private key');
            if (!k.comment)
                k.comment = options.filename;
            return (k);
        }
        catch (e) {
            if (e.name === 'KeyEncryptedError')
                throw (e);
            throw (new KeyParseError(options.filename, format, e));
        }
    };
    PrivateKey.isPrivateKey = function (obj, ver) {
        return (utils.isCompatible(obj, PrivateKey, ver));
    };
    PrivateKey.generate = function (type, options) {
        if (options === undefined)
            options = {};
        assert.object(options, 'options');
        switch (type) {
            case 'ecdsa':
                if (options.curve === undefined)
                    options.curve = 'nistp256';
                assert.string(options.curve, 'options.curve');
                return (generateECDSA(options.curve));
            case 'ed25519':
                return (generateED25519());
            default:
                throw (new Error('Key generation not supported with key ' +
                    'type "' + type + '"'));
        }
    };
    /*
     * API versions for PrivateKey:
     * [1,0] -- initial ver
     * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats
     * [1,2] -- added defaultHashAlgorithm
     * [1,3] -- added derive, ed, createDH
     * [1,4] -- first tagged version
     * [1,5] -- changed ed25519 part names and format
     */
    PrivateKey.prototype._sshpkApiVersion = [1, 5];
    PrivateKey._oldVersionDetect = function (obj) {
        assert.func(obj.toPublic);
        assert.func(obj.createSign);
        if (obj.derive)
            return ([1, 3]);
        if (obj.defaultHashAlgorithm)
            return ([1, 2]);
        if (obj.formats['auto'])
            return ([1, 1]);
        return ([1, 0]);
    };
}
,
/* sshpk/lib/signature */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = Signature;
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var algs = require(331) /* ./algs */;
    var crypto = require('crypto');
    var errs = require(335) /* ./errors */;
    var utils = require(354) /* ./utils */;
    var asn1 = require(52) /* asn1 */;
    var SSHBuffer = require(353) /* ./ssh-buffer */;
    var InvalidAlgorithmError = errs.InvalidAlgorithmError;
    var SignatureParseError = errs.SignatureParseError;
    function Signature(opts) {
        assert.object(opts, 'options');
        assert.arrayOfObject(opts.parts, 'options.parts');
        assert.string(opts.type, 'options.type');
        var partLookup = {};
        for (var i = 0; i < opts.parts.length; ++i) {
            var part = opts.parts[i];
            partLookup[part.name] = part;
        }
        this.type = opts.type;
        this.hashAlgorithm = opts.hashAlgo;
        this.curve = opts.curve;
        this.parts = opts.parts;
        this.part = partLookup;
    }
    Signature.prototype.toBuffer = function (format) {
        if (format === undefined)
            format = 'asn1';
        assert.string(format, 'format');
        var buf;
        var stype = 'ssh-' + this.type;
        switch (this.type) {
            case 'rsa':
                switch (this.hashAlgorithm) {
                    case 'sha256':
                        stype = 'rsa-sha2-256';
                        break;
                    case 'sha512':
                        stype = 'rsa-sha2-512';
                        break;
                    case 'sha1':
                    case undefined:
                        break;
                    default:
                        throw (new Error('SSH signature ' +
                            'format does not support hash ' +
                            'algorithm ' + this.hashAlgorithm));
                }
                if (format === 'ssh') {
                    buf = new SSHBuffer({});
                    buf.writeString(stype);
                    buf.writePart(this.part.sig);
                    return (buf.toBuffer());
                }
                else {
                    return (this.part.sig.data);
                }
                break;
            case 'ed25519':
                if (format === 'ssh') {
                    buf = new SSHBuffer({});
                    buf.writeString(stype);
                    buf.writePart(this.part.sig);
                    return (buf.toBuffer());
                }
                else {
                    return (this.part.sig.data);
                }
                break;
            case 'dsa':
            case 'ecdsa':
                var r, s;
                if (format === 'asn1') {
                    var der = new asn1.BerWriter();
                    der.startSequence();
                    r = utils.mpNormalize(this.part.r.data);
                    s = utils.mpNormalize(this.part.s.data);
                    der.writeBuffer(r, asn1.Ber.Integer);
                    der.writeBuffer(s, asn1.Ber.Integer);
                    der.endSequence();
                    return (der.buffer);
                }
                else if (format === 'ssh' && this.type === 'dsa') {
                    buf = new SSHBuffer({});
                    buf.writeString('ssh-dss');
                    r = this.part.r.data;
                    if (r.length > 20 && r[0] === 0x00)
                        r = r.slice(1);
                    s = this.part.s.data;
                    if (s.length > 20 && s[0] === 0x00)
                        s = s.slice(1);
                    if ((this.hashAlgorithm &&
                        this.hashAlgorithm !== 'sha1') ||
                        r.length + s.length !== 40) {
                        throw (new Error('OpenSSH only supports ' +
                            'DSA signatures with SHA1 hash'));
                    }
                    buf.writeBuffer(Buffer.concat([r, s]));
                    return (buf.toBuffer());
                }
                else if (format === 'ssh' && this.type === 'ecdsa') {
                    var inner = new SSHBuffer({});
                    r = this.part.r.data;
                    inner.writeBuffer(r);
                    inner.writePart(this.part.s);
                    buf = new SSHBuffer({});
                    /* XXX: find a more proper way to do this? */
                    var curve;
                    if (r[0] === 0x00)
                        r = r.slice(1);
                    var sz = r.length * 8;
                    if (sz === 256)
                        curve = 'nistp256';
                    else if (sz === 384)
                        curve = 'nistp384';
                    else if (sz === 528)
                        curve = 'nistp521';
                    buf.writeString('ecdsa-sha2-' + curve);
                    buf.writeBuffer(inner.toBuffer());
                    return (buf.toBuffer());
                }
                throw (new Error('Invalid signature format'));
            default:
                throw (new Error('Invalid signature data'));
        }
    };
    Signature.prototype.toString = function (format) {
        assert.optionalString(format, 'format');
        return (this.toBuffer(format).toString('base64'));
    };
    Signature.parse = function (data, type, format) {
        if (typeof (data) === 'string')
            data = Buffer.from(data, 'base64');
        assert.buffer(data, 'data');
        assert.string(format, 'format');
        assert.string(type, 'type');
        var opts = {};
        opts.type = type.toLowerCase();
        opts.parts = [];
        try {
            assert.ok(data.length > 0, 'signature must not be empty');
            switch (opts.type) {
                case 'rsa':
                    return (parseOneNum(data, type, format, opts));
                case 'ed25519':
                    return (parseOneNum(data, type, format, opts));
                case 'dsa':
                case 'ecdsa':
                    if (format === 'asn1')
                        return (parseDSAasn1(data, type, format, opts));
                    else if (opts.type === 'dsa')
                        return (parseDSA(data, type, format, opts));
                    else
                        return (parseECDSA(data, type, format, opts));
                default:
                    throw (new InvalidAlgorithmError(type));
            }
        }
        catch (e) {
            if (e instanceof InvalidAlgorithmError)
                throw (e);
            throw (new SignatureParseError(type, format, e));
        }
    };
    function parseOneNum(data, type, format, opts) {
        if (format === 'ssh') {
            try {
                var buf = new SSHBuffer({ buffer: data });
                var head = buf.readString();
            }
            catch (e) {
                /* fall through */
            }
            if (buf !== undefined) {
                var msg = 'SSH signature does not match expected ' +
                    'type (expected ' + type + ', got ' + head + ')';
                switch (head) {
                    case 'ssh-rsa':
                        assert.strictEqual(type, 'rsa', msg);
                        opts.hashAlgo = 'sha1';
                        break;
                    case 'rsa-sha2-256':
                        assert.strictEqual(type, 'rsa', msg);
                        opts.hashAlgo = 'sha256';
                        break;
                    case 'rsa-sha2-512':
                        assert.strictEqual(type, 'rsa', msg);
                        opts.hashAlgo = 'sha512';
                        break;
                    case 'ssh-ed25519':
                        assert.strictEqual(type, 'ed25519', msg);
                        opts.hashAlgo = 'sha512';
                        break;
                    default:
                        throw (new Error('Unknown SSH signature ' +
                            'type: ' + head));
                }
                var sig = buf.readPart();
                assert.ok(buf.atEnd(), 'extra trailing bytes');
                sig.name = 'sig';
                opts.parts.push(sig);
                return (new Signature(opts));
            }
        }
        opts.parts.push({ name: 'sig', data: data });
        return (new Signature(opts));
    }
    function parseDSAasn1(data, type, format, opts) {
        var der = new asn1.BerReader(data);
        der.readSequence();
        var r = der.readString(asn1.Ber.Integer, true);
        var s = der.readString(asn1.Ber.Integer, true);
        opts.parts.push({ name: 'r', data: utils.mpNormalize(r) });
        opts.parts.push({ name: 's', data: utils.mpNormalize(s) });
        return (new Signature(opts));
    }
    function parseDSA(data, type, format, opts) {
        if (data.length != 40) {
            var buf = new SSHBuffer({ buffer: data });
            var d = buf.readBuffer();
            if (d.toString('ascii') === 'ssh-dss')
                d = buf.readBuffer();
            assert.ok(buf.atEnd(), 'extra trailing bytes');
            assert.strictEqual(d.length, 40, 'invalid inner length');
            data = d;
        }
        opts.parts.push({ name: 'r', data: data.slice(0, 20) });
        opts.parts.push({ name: 's', data: data.slice(20, 40) });
        return (new Signature(opts));
    }
    function parseECDSA(data, type, format, opts) {
        var buf = new SSHBuffer({ buffer: data });
        var r, s;
        var inner = buf.readBuffer();
        var stype = inner.toString('ascii');
        if (stype.slice(0, 6) === 'ecdsa-') {
            var parts = stype.split('-');
            assert.strictEqual(parts[0], 'ecdsa');
            assert.strictEqual(parts[1], 'sha2');
            opts.curve = parts[2];
            switch (opts.curve) {
                case 'nistp256':
                    opts.hashAlgo = 'sha256';
                    break;
                case 'nistp384':
                    opts.hashAlgo = 'sha384';
                    break;
                case 'nistp521':
                    opts.hashAlgo = 'sha512';
                    break;
                default:
                    throw (new Error('Unsupported ECDSA curve: ' +
                        opts.curve));
            }
            inner = buf.readBuffer();
            assert.ok(buf.atEnd(), 'extra trailing bytes on outer');
            buf = new SSHBuffer({ buffer: inner });
            r = buf.readPart();
        }
        else {
            r = { data: inner };
        }
        s = buf.readPart();
        assert.ok(buf.atEnd(), 'extra trailing bytes');
        r.name = 'r';
        s.name = 's';
        opts.parts.push(r);
        opts.parts.push(s);
        return (new Signature(opts));
    }
    Signature.isSignature = function (obj, ver) {
        return (utils.isCompatible(obj, Signature, ver));
    };
    /*
     * API versions for Signature:
     * [1,0] -- initial ver
     * [2,0] -- support for rsa in full ssh format, compat with sshpk-agent
     *          hashAlgorithm property
     * [2,1] -- first tagged version
     */
    Signature.prototype._sshpkApiVersion = [2, 1];
    Signature._oldVersionDetect = function (obj) {
        assert.func(obj.toBuffer);
        if (obj.hasOwnProperty('hashAlgorithm'))
            return ([2, 0]);
        return ([1, 0]);
    };
}
,
/* sshpk/lib/ssh-buffer */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = SSHBuffer;
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    function SSHBuffer(opts) {
        assert.object(opts, 'options');
        if (opts.buffer !== undefined)
            assert.buffer(opts.buffer, 'options.buffer');
        this._size = opts.buffer ? opts.buffer.length : 1024;
        this._buffer = opts.buffer || Buffer.alloc(this._size);
        this._offset = 0;
    }
    SSHBuffer.prototype.toBuffer = function () {
        return (this._buffer.slice(0, this._offset));
    };
    SSHBuffer.prototype.atEnd = function () {
        return (this._offset >= this._buffer.length);
    };
    SSHBuffer.prototype.remainder = function () {
        return (this._buffer.slice(this._offset));
    };
    SSHBuffer.prototype.skip = function (n) {
        this._offset += n;
    };
    SSHBuffer.prototype.expand = function () {
        this._size *= 2;
        var buf = Buffer.alloc(this._size);
        this._buffer.copy(buf, 0);
        this._buffer = buf;
    };
    SSHBuffer.prototype.readPart = function () {
        return ({ data: this.readBuffer() });
    };
    SSHBuffer.prototype.readBuffer = function () {
        var len = this._buffer.readUInt32BE(this._offset);
        this._offset += 4;
        assert.ok(this._offset + len <= this._buffer.length, 'length out of bounds at +0x' + this._offset.toString(16) +
            ' (data truncated?)');
        var buf = this._buffer.slice(this._offset, this._offset + len);
        this._offset += len;
        return (buf);
    };
    SSHBuffer.prototype.readString = function () {
        return (this.readBuffer().toString());
    };
    SSHBuffer.prototype.readCString = function () {
        var offset = this._offset;
        while (offset < this._buffer.length &&
            this._buffer[offset] !== 0x00)
            offset++;
        assert.ok(offset < this._buffer.length, 'c string does not terminate');
        var str = this._buffer.slice(this._offset, offset).toString();
        this._offset = offset + 1;
        return (str);
    };
    SSHBuffer.prototype.readInt = function () {
        var v = this._buffer.readUInt32BE(this._offset);
        this._offset += 4;
        return (v);
    };
    SSHBuffer.prototype.readInt64 = function () {
        assert.ok(this._offset + 8 < this._buffer.length, 'buffer not long enough to read Int64');
        var v = this._buffer.slice(this._offset, this._offset + 8);
        this._offset += 8;
        return (v);
    };
    SSHBuffer.prototype.readChar = function () {
        var v = this._buffer[this._offset++];
        return (v);
    };
    SSHBuffer.prototype.writeBuffer = function (buf) {
        while (this._offset + 4 + buf.length > this._size)
            this.expand();
        this._buffer.writeUInt32BE(buf.length, this._offset);
        this._offset += 4;
        buf.copy(this._buffer, this._offset);
        this._offset += buf.length;
    };
    SSHBuffer.prototype.writeString = function (str) {
        this.writeBuffer(Buffer.from(str, 'utf8'));
    };
    SSHBuffer.prototype.writeCString = function (str) {
        while (this._offset + 1 + str.length > this._size)
            this.expand();
        this._buffer.write(str, this._offset);
        this._offset += str.length;
        this._buffer[this._offset++] = 0;
    };
    SSHBuffer.prototype.writeInt = function (v) {
        while (this._offset + 4 > this._size)
            this.expand();
        this._buffer.writeUInt32BE(v, this._offset);
        this._offset += 4;
    };
    SSHBuffer.prototype.writeInt64 = function (v) {
        assert.buffer(v, 'value');
        if (v.length > 8) {
            var lead = v.slice(0, v.length - 8);
            for (var i = 0; i < lead.length; ++i) {
                assert.strictEqual(lead[i], 0, 'must fit in 64 bits of precision');
            }
            v = v.slice(v.length - 8, v.length);
        }
        while (this._offset + 8 > this._size)
            this.expand();
        v.copy(this._buffer, this._offset);
        this._offset += 8;
    };
    SSHBuffer.prototype.writeChar = function (v) {
        while (this._offset + 1 > this._size)
            this.expand();
        this._buffer[this._offset++] = v;
    };
    SSHBuffer.prototype.writePart = function (p) {
        this.writeBuffer(p.data);
    };
    SSHBuffer.prototype.write = function (buf) {
        while (this._offset + buf.length > this._size)
            this.expand();
        buf.copy(this._buffer, this._offset);
        this._offset += buf.length;
    };
}
,
/* sshpk/lib/utils */ function _(require, module, exports) {
    // Copyright 2015 Joyent, Inc.
    module.exports = {
        bufferSplit: bufferSplit,
        addRSAMissing: addRSAMissing,
        calculateDSAPublic: calculateDSAPublic,
        calculateED25519Public: calculateED25519Public,
        calculateX25519Public: calculateX25519Public,
        mpNormalize: mpNormalize,
        mpDenormalize: mpDenormalize,
        ecNormalize: ecNormalize,
        countZeros: countZeros,
        assertCompatible: assertCompatible,
        isCompatible: isCompatible,
        opensslKeyDeriv: opensslKeyDeriv,
        opensshCipherInfo: opensshCipherInfo,
        publicFromPrivateECDSA: publicFromPrivateECDSA,
        zeroPadToLength: zeroPadToLength,
        writeBitString: writeBitString,
        readBitString: readBitString
    };
    var assert = require(53) /* assert-plus */;
    var Buffer = require(312) /* safer-buffer */.Buffer;
    var PrivateKey = require(351) /* ./private-key */;
    var Key = require(350) /* ./key */;
    var crypto = require('crypto');
    var algs = require(331) /* ./algs */;
    var asn1 = require(52) /* asn1 */;
    var ec, jsbn;
    var nacl;
    var MAX_CLASS_DEPTH = 3;
    function isCompatible(obj, klass, needVer) {
        if (obj === null || typeof (obj) !== 'object')
            return (false);
        if (needVer === undefined)
            needVer = klass.prototype._sshpkApiVersion;
        if (obj instanceof klass &&
            klass.prototype._sshpkApiVersion[0] == needVer[0])
            return (true);
        var proto = Object.getPrototypeOf(obj);
        var depth = 0;
        while (proto.constructor.name !== klass.name) {
            proto = Object.getPrototypeOf(proto);
            if (!proto || ++depth > MAX_CLASS_DEPTH)
                return (false);
        }
        if (proto.constructor.name !== klass.name)
            return (false);
        var ver = proto._sshpkApiVersion;
        if (ver === undefined)
            ver = klass._oldVersionDetect(obj);
        if (ver[0] != needVer[0] || ver[1] < needVer[1])
            return (false);
        return (true);
    }
    function assertCompatible(obj, klass, needVer, name) {
        if (name === undefined)
            name = 'object';
        assert.ok(obj, name + ' must not be null');
        assert.object(obj, name + ' must be an object');
        if (needVer === undefined)
            needVer = klass.prototype._sshpkApiVersion;
        if (obj instanceof klass &&
            klass.prototype._sshpkApiVersion[0] == needVer[0])
            return;
        var proto = Object.getPrototypeOf(obj);
        var depth = 0;
        while (proto.constructor.name !== klass.name) {
            proto = Object.getPrototypeOf(proto);
            assert.ok(proto && ++depth <= MAX_CLASS_DEPTH, name + ' must be a ' + klass.name + ' instance');
        }
        assert.strictEqual(proto.constructor.name, klass.name, name + ' must be a ' + klass.name + ' instance');
        var ver = proto._sshpkApiVersion;
        if (ver === undefined)
            ver = klass._oldVersionDetect(obj);
        assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1], name + ' must be compatible with ' + klass.name + ' klass ' +
            'version ' + needVer[0] + '.' + needVer[1]);
    }
    var CIPHER_LEN = {
        'des-ede3-cbc': { key: 7, iv: 8 },
        'aes-128-cbc': { key: 16, iv: 16 }
    };
    var PKCS5_SALT_LEN = 8;
    function opensslKeyDeriv(cipher, salt, passphrase, count) {
        assert.buffer(salt, 'salt');
        assert.buffer(passphrase, 'passphrase');
        assert.number(count, 'iteration count');
        var clen = CIPHER_LEN[cipher];
        assert.object(clen, 'supported cipher');
        salt = salt.slice(0, PKCS5_SALT_LEN);
        var D, D_prev, bufs;
        var material = Buffer.alloc(0);
        while (material.length < clen.key + clen.iv) {
            bufs = [];
            if (D_prev)
                bufs.push(D_prev);
            bufs.push(passphrase);
            bufs.push(salt);
            D = Buffer.concat(bufs);
            for (var j = 0; j < count; ++j)
                D = crypto.createHash('md5').update(D).digest();
            material = Buffer.concat([material, D]);
            D_prev = D;
        }
        return ({
            key: material.slice(0, clen.key),
            iv: material.slice(clen.key, clen.key + clen.iv)
        });
    }
    /* Count leading zero bits on a buffer */
    function countZeros(buf) {
        var o = 0, obit = 8;
        while (o < buf.length) {
            var mask = (1 << obit);
            if ((buf[o] & mask) === mask)
                break;
            obit--;
            if (obit < 0) {
                o++;
                obit = 8;
            }
        }
        return (o * 8 + (8 - obit) - 1);
    }
    function bufferSplit(buf, chr) {
        assert.buffer(buf);
        assert.string(chr);
        var parts = [];
        var lastPart = 0;
        var matches = 0;
        for (var i = 0; i < buf.length; ++i) {
            if (buf[i] === chr.charCodeAt(matches))
                ++matches;
            else if (buf[i] === chr.charCodeAt(0))
                matches = 1;
            else
                matches = 0;
            if (matches >= chr.length) {
                var newPart = i + 1;
                parts.push(buf.slice(lastPart, newPart - matches));
                lastPart = newPart;
                matches = 0;
            }
        }
        if (lastPart <= buf.length)
            parts.push(buf.slice(lastPart, buf.length));
        return (parts);
    }
    function ecNormalize(buf, addZero) {
        assert.buffer(buf);
        if (buf[0] === 0x00 && buf[1] === 0x04) {
            if (addZero)
                return (buf);
            return (buf.slice(1));
        }
        else if (buf[0] === 0x04) {
            if (!addZero)
                return (buf);
        }
        else {
            while (buf[0] === 0x00)
                buf = buf.slice(1);
            if (buf[0] === 0x02 || buf[0] === 0x03)
                throw (new Error('Compressed elliptic curve points ' +
                    'are not supported'));
            if (buf[0] !== 0x04)
                throw (new Error('Not a valid elliptic curve point'));
            if (!addZero)
                return (buf);
        }
        var b = Buffer.alloc(buf.length + 1);
        b[0] = 0x0;
        buf.copy(b, 1);
        return (b);
    }
    function readBitString(der, tag) {
        if (tag === undefined)
            tag = asn1.Ber.BitString;
        var buf = der.readString(tag, true);
        assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' +
            'not supported (0x' + buf[0].toString(16) + ')');
        return (buf.slice(1));
    }
    function writeBitString(der, buf, tag) {
        if (tag === undefined)
            tag = asn1.Ber.BitString;
        var b = Buffer.alloc(buf.length + 1);
        b[0] = 0x00;
        buf.copy(b, 1);
        der.writeBuffer(b, tag);
    }
    function mpNormalize(buf) {
        assert.buffer(buf);
        while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00)
            buf = buf.slice(1);
        if ((buf[0] & 0x80) === 0x80) {
            var b = Buffer.alloc(buf.length + 1);
            b[0] = 0x00;
            buf.copy(b, 1);
            buf = b;
        }
        return (buf);
    }
    function mpDenormalize(buf) {
        assert.buffer(buf);
        while (buf.length > 1 && buf[0] === 0x00)
            buf = buf.slice(1);
        return (buf);
    }
    function zeroPadToLength(buf, len) {
        assert.buffer(buf);
        assert.number(len);
        while (buf.length > len) {
            assert.equal(buf[0], 0x00);
            buf = buf.slice(1);
        }
        while (buf.length < len) {
            var b = Buffer.alloc(buf.length + 1);
            b[0] = 0x00;
            buf.copy(b, 1);
            buf = b;
        }
        return (buf);
    }
    function bigintToMpBuf(bigint) {
        var buf = Buffer.from(bigint.toByteArray());
        buf = mpNormalize(buf);
        return (buf);
    }
    function calculateDSAPublic(g, p, x) {
        assert.buffer(g);
        assert.buffer(p);
        assert.buffer(x);
        try {
            var bigInt = require(155) /* jsbn */.BigInteger;
        }
        catch (e) {
            throw (new Error('To load a PKCS#8 format DSA private key, ' +
                'the node jsbn library is required.'));
        }
        g = new bigInt(g);
        p = new bigInt(p);
        x = new bigInt(x);
        var y = g.modPow(x, p);
        var ybuf = bigintToMpBuf(y);
        return (ybuf);
    }
    function calculateED25519Public(k) {
        assert.buffer(k);
        if (nacl === undefined)
            nacl = require(366) /* tweetnacl */;
        var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k));
        return (Buffer.from(kp.publicKey));
    }
    function calculateX25519Public(k) {
        assert.buffer(k);
        if (nacl === undefined)
            nacl = require(366) /* tweetnacl */;
        var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k));
        return (Buffer.from(kp.publicKey));
    }
    function addRSAMissing(key) {
        assert.object(key);
        assertCompatible(key, PrivateKey, [1, 1]);
        try {
            var bigInt = require(155) /* jsbn */.BigInteger;
        }
        catch (e) {
            throw (new Error('To write a PEM private key from ' +
                'this source, the node jsbn lib is required.'));
        }
        var d = new bigInt(key.part.d.data);
        var buf;
        if (!key.part.dmodp) {
            var p = new bigInt(key.part.p.data);
            var dmodp = d.mod(p.subtract(1));
            buf = bigintToMpBuf(dmodp);
            key.part.dmodp = { name: 'dmodp', data: buf };
            key.parts.push(key.part.dmodp);
        }
        if (!key.part.dmodq) {
            var q = new bigInt(key.part.q.data);
            var dmodq = d.mod(q.subtract(1));
            buf = bigintToMpBuf(dmodq);
            key.part.dmodq = { name: 'dmodq', data: buf };
            key.parts.push(key.part.dmodq);
        }
    }
    function publicFromPrivateECDSA(curveName, priv) {
        assert.string(curveName, 'curveName');
        assert.buffer(priv);
        if (ec === undefined)
            ec = require(101) /* ecc-jsbn/lib/ec */;
        if (jsbn === undefined)
            jsbn = require(155) /* jsbn */.BigInteger;
        var params = algs.curves[curveName];
        var p = new jsbn(params.p);
        var a = new jsbn(params.a);
        var b = new jsbn(params.b);
        var curve = new ec.ECCurveFp(p, a, b);
        var G = curve.decodePointHex(params.G.toString('hex'));
        var d = new jsbn(mpNormalize(priv));
        var pub = G.multiply(d);
        pub = Buffer.from(curve.encodePointHex(pub), 'hex');
        var parts = [];
        parts.push({ name: 'curve', data: Buffer.from(curveName) });
        parts.push({ name: 'Q', data: pub });
        var key = new Key({ type: 'ecdsa', curve: curve, parts: parts });
        return (key);
    }
    function opensshCipherInfo(cipher) {
        var inf = {};
        switch (cipher) {
            case '3des-cbc':
                inf.keySize = 24;
                inf.blockSize = 8;
                inf.opensslName = 'des-ede3-cbc';
                break;
            case 'blowfish-cbc':
                inf.keySize = 16;
                inf.blockSize = 8;
                inf.opensslName = 'bf-cbc';
                break;
            case 'aes128-cbc':
            case 'aes128-ctr':
            case 'aes128-gcm@openssh.com':
                inf.keySize = 16;
                inf.blockSize = 16;
                inf.opensslName = 'aes-128-' + cipher.slice(7, 10);
                break;
            case 'aes192-cbc':
            case 'aes192-ctr':
            case 'aes192-gcm@openssh.com':
                inf.keySize = 24;
                inf.blockSize = 16;
                inf.opensslName = 'aes-192-' + cipher.slice(7, 10);
                break;
            case 'aes256-cbc':
            case 'aes256-ctr':
            case 'aes256-gcm@openssh.com':
                inf.keySize = 32;
                inf.blockSize = 16;
                inf.opensslName = 'aes-256-' + cipher.slice(7, 10);
                break;
            default:
                throw (new Error('Unsupported openssl cipher "' + cipher + '"'));
        }
        return (inf);
    }
}
,
/* string-width/index */ function _(require, module, exports) {
    const stripAnsi = require(356) /* strip-ansi */;
    const isFullwidthCodePoint = require(148) /* is-fullwidth-code-point */;
    module.exports = str => {
        if (typeof str !== 'string' || str.length === 0) {
            return 0;
        }
        str = stripAnsi(str);
        let width = 0;
        for (let i = 0; i < str.length; i++) {
            const code = str.codePointAt(i);
            // Ignore control characters
            if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
                continue;
            }
            // Ignore combining characters
            if (code >= 0x300 && code <= 0x36F) {
                continue;
            }
            // Surrogates
            if (code > 0xFFFF) {
                i++;
            }
            width += isFullwidthCodePoint(code) ? 2 : 1;
        }
        return width;
    };
}
,
/* strip-ansi/index */ function _(require, module, exports) {
    var ansiRegex = require(44) /* ansi-regex */();
    module.exports = function (str) {
        return typeof str === 'string' ? str.replace(ansiRegex, '') : str;
    };
}
,
/* strip-eof/index */ function _(require, module, exports) {
    module.exports = function (x) {
        var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt();
        var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt();
        if (x[x.length - 1] === lf) {
            x = x.slice(0, x.length - 1);
        }
        if (x[x.length - 1] === cr) {
            x = x.slice(0, x.length - 1);
        }
        return x;
    };
}
,
/* tough-cookie/lib/cookie */ function _(require, module, exports) {
    var net = require('net');
    var urlParse = require('url').parse;
    var pubsuffix = require(362) /* ./pubsuffix */;
    var Store = require(363) /* ./store */.Store;
    var MemoryCookieStore = require(359) /* ./memstore */.MemoryCookieStore;
    var pathMatch = require(360) /* ./pathMatch */.pathMatch;
    var VERSION = require(364) /* ../package.json */.version;
    var punycode;
    try {
        punycode = require('punycode');
    }
    catch (e) {
        console.warn("cookie: can't load punycode; won't use punycode for domain normalization");
    }
    var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
    // From RFC6265 S4.1.1
    // note that it excludes \x3B ";"
    var COOKIE_OCTET = /[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/;
    var COOKIE_OCTETS = new RegExp('^' + COOKIE_OCTET.source + '+$');
    var CONTROL_CHARS = /[\x00-\x1F]/;
    // For COOKIE_PAIR and LOOSE_COOKIE_PAIR below, the number of spaces has been
    // restricted to 256 to side-step a ReDoS issue reported here:
    // https://github.com/salesforce/tough-cookie/issues/92
    // Double quotes are part of the value (see: S4.1.1).
    // '\r', '\n' and '\0' should be treated as a terminator in the "relaxed" mode
    // (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60)
    // '=' and ';' are attribute/values separators
    // (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L64)
    var COOKIE_PAIR = /^(([^=;]+))\s{0,256}=\s*([^\n\r\0]*)/;
    // Used to parse non-RFC-compliant cookies like '=abc' when given the `loose`
    // option in Cookie.parse:
    var LOOSE_COOKIE_PAIR = /^((?:=)?([^=;]*)\s{0,256}=\s*)?([^\n\r\0]*)/;
    // RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
    // Note ';' is \x3B
    var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
    var DAY_OF_MONTH = /^(\d{1,2})[^\d]*$/;
    var TIME = /^(\d{1,2})[^\d]*:(\d{1,2})[^\d]*:(\d{1,2})[^\d]*$/;
    var MONTH = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i;
    var MONTH_TO_NUM = {
        jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5,
        jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11
    };
    var NUM_TO_MONTH = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    ];
    var NUM_TO_DAY = [
        'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
    ];
    var YEAR = /^(\d{2}|\d{4})$/; // 2 to 4 digits
    var MAX_TIME = 2147483647000; // 31-bit max
    var MIN_TIME = 0; // 31-bit min
    // RFC6265 S5.1.1 date parser:
    function parseDate(str) {
        if (!str) {
            return;
        }
        /* RFC6265 S5.1.1:
         * 2. Process each date-token sequentially in the order the date-tokens
         * appear in the cookie-date
         */
        var tokens = str.split(DATE_DELIM);
        if (!tokens) {
            return;
        }
        var hour = null;
        var minutes = null;
        var seconds = null;
        var day = null;
        var month = null;
        var year = null;
        for (var i = 0; i < tokens.length; i++) {
            var token = tokens[i].trim();
            if (!token.length) {
                continue;
            }
            var result;
            /* 2.1. If the found-time flag is not set and the token matches the time
             * production, set the found-time flag and set the hour- value,
             * minute-value, and second-value to the numbers denoted by the digits in
             * the date-token, respectively.  Skip the remaining sub-steps and continue
             * to the next date-token.
             */
            if (seconds === null) {
                result = TIME.exec(token);
                if (result) {
                    hour = parseInt(result[1], 10);
                    minutes = parseInt(result[2], 10);
                    seconds = parseInt(result[3], 10);
                    /* RFC6265 S5.1.1.5:
                     * [fail if]
                     * *  the hour-value is greater than 23,
                     * *  the minute-value is greater than 59, or
                     * *  the second-value is greater than 59.
                     */
                    if (hour > 23 || minutes > 59 || seconds > 59) {
                        return;
                    }
                    continue;
                }
            }
            /* 2.2. If the found-day-of-month flag is not set and the date-token matches
             * the day-of-month production, set the found-day-of- month flag and set
             * the day-of-month-value to the number denoted by the date-token.  Skip
             * the remaining sub-steps and continue to the next date-token.
             */
            if (day === null) {
                result = DAY_OF_MONTH.exec(token);
                if (result) {
                    day = parseInt(result, 10);
                    /* RFC6265 S5.1.1.5:
                     * [fail if] the day-of-month-value is less than 1 or greater than 31
                     */
                    if (day < 1 || day > 31) {
                        return;
                    }
                    continue;
                }
            }
            /* 2.3. If the found-month flag is not set and the date-token matches the
             * month production, set the found-month flag and set the month-value to
             * the month denoted by the date-token.  Skip the remaining sub-steps and
             * continue to the next date-token.
             */
            if (month === null) {
                result = MONTH.exec(token);
                if (result) {
                    month = MONTH_TO_NUM[result[1].toLowerCase()];
                    continue;
                }
            }
            /* 2.4. If the found-year flag is not set and the date-token matches the year
             * production, set the found-year flag and set the year-value to the number
             * denoted by the date-token.  Skip the remaining sub-steps and continue to
             * the next date-token.
             */
            if (year === null) {
                result = YEAR.exec(token);
                if (result) {
                    year = parseInt(result[0], 10);
                    /* From S5.1.1:
                     * 3.  If the year-value is greater than or equal to 70 and less
                     * than or equal to 99, increment the year-value by 1900.
                     * 4.  If the year-value is greater than or equal to 0 and less
                     * than or equal to 69, increment the year-value by 2000.
                     */
                    if (70 <= year && year <= 99) {
                        year += 1900;
                    }
                    else if (0 <= year && year <= 69) {
                        year += 2000;
                    }
                    if (year < 1601) {
                        return; // 5. ... the year-value is less than 1601
                    }
                }
            }
        }
        if (seconds === null || day === null || month === null || year === null) {
            return; // 5. ... at least one of the found-day-of-month, found-month, found-
            // year, or found-time flags is not set,
        }
        return new Date(Date.UTC(year, month, day, hour, minutes, seconds));
    }
    function formatDate(date) {
        var d = date.getUTCDate();
        d = d >= 10 ? d : '0' + d;
        var h = date.getUTCHours();
        h = h >= 10 ? h : '0' + h;
        var m = date.getUTCMinutes();
        m = m >= 10 ? m : '0' + m;
        var s = date.getUTCSeconds();
        s = s >= 10 ? s : '0' + s;
        return NUM_TO_DAY[date.getUTCDay()] + ', ' +
            d + ' ' + NUM_TO_MONTH[date.getUTCMonth()] + ' ' + date.getUTCFullYear() + ' ' +
            h + ':' + m + ':' + s + ' GMT';
    }
    // S5.1.2 Canonicalized Host Names
    function canonicalDomain(str) {
        if (str == null) {
            return null;
        }
        str = str.trim().replace(/^\./, ''); // S4.1.2.3 & S5.2.3: ignore leading .
        // convert to IDN if any non-ASCII characters
        if (punycode && /[^\u0001-\u007f]/.test(str)) {
            str = punycode.toASCII(str);
        }
        return str.toLowerCase();
    }
    // S5.1.3 Domain Matching
    function domainMatch(str, domStr, canonicalize) {
        if (str == null || domStr == null) {
            return null;
        }
        if (canonicalize !== false) {
            str = canonicalDomain(str);
            domStr = canonicalDomain(domStr);
        }
        /*
         * "The domain string and the string are identical. (Note that both the
         * domain string and the string will have been canonicalized to lower case at
         * this point)"
         */
        if (str == domStr) {
            return true;
        }
        /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
        /* "* The string is a host name (i.e., not an IP address)." */
        if (net.isIP(str)) {
            return false;
        }
        /* "* The domain string is a suffix of the string" */
        var idx = str.indexOf(domStr);
        if (idx <= 0) {
            return false; // it's a non-match (-1) or prefix (0)
        }
        // e.g "a.b.c".indexOf("b.c") === 2
        // 5 === 3+2
        if (str.length !== domStr.length + idx) { // it's not a suffix
            return false;
        }
        /* "* The last character of the string that is not included in the domain
        * string is a %x2E (".") character." */
        if (str.substr(idx - 1, 1) !== '.') {
            return false;
        }
        return true;
    }
    // RFC6265 S5.1.4 Paths and Path-Match
    /*
     * "The user agent MUST use an algorithm equivalent to the following algorithm
     * to compute the default-path of a cookie:"
     *
     * Assumption: the path (and not query part or absolute uri) is passed in.
     */
    function defaultPath(path) {
        // "2. If the uri-path is empty or if the first character of the uri-path is not
        // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
        if (!path || path.substr(0, 1) !== "/") {
            return "/";
        }
        // "3. If the uri-path contains no more than one %x2F ("/") character, output
        // %x2F ("/") and skip the remaining step."
        if (path === "/") {
            return path;
        }
        var rightSlash = path.lastIndexOf("/");
        if (rightSlash === 0) {
            return "/";
        }
        // "4. Output the characters of the uri-path from the first character up to,
        // but not including, the right-most %x2F ("/")."
        return path.slice(0, rightSlash);
    }
    function parse(str, options) {
        if (!options || typeof options !== 'object') {
            options = {};
        }
        str = str.trim();
        // We use a regex to parse the "name-value-pair" part of S5.2
        var firstSemi = str.indexOf(';'); // S5.2 step 1
        var pairRe = options.loose ? LOOSE_COOKIE_PAIR : COOKIE_PAIR;
        var result = pairRe.exec(firstSemi === -1 ? str : str.substr(0, firstSemi));
        // Rx satisfies the "the name string is empty" and "lacks a %x3D ("=")"
        // constraints as well as trimming any whitespace.
        if (!result) {
            return;
        }
        var c = new Cookie();
        if (result[1]) {
            c.key = result[2].trim();
        }
        else {
            c.key = '';
        }
        c.value = result[3].trim();
        if (CONTROL_CHARS.test(c.key) || CONTROL_CHARS.test(c.value)) {
            return;
        }
        if (firstSemi === -1) {
            return c;
        }
        // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
        // (including the %x3B (";") in question)." plus later on in the same section
        // "discard the first ";" and trim".
        var unparsed = str.slice(firstSemi + 1).trim();
        // "If the unparsed-attributes string is empty, skip the rest of these
        // steps."
        if (unparsed.length === 0) {
            return c;
        }
        /*
         * S5.2 says that when looping over the items "[p]rocess the attribute-name
         * and attribute-value according to the requirements in the following
         * subsections" for every item.  Plus, for many of the individual attributes
         * in S5.3 it says to use the "attribute-value of the last attribute in the
         * cookie-attribute-list".  Therefore, in this implementation, we overwrite
         * the previous value.
         */
        var cookie_avs = unparsed.split(';');
        while (cookie_avs.length) {
            var av = cookie_avs.shift().trim();
            if (av.length === 0) { // happens if ";;" appears
                continue;
            }
            var av_sep = av.indexOf('=');
            var av_key, av_value;
            if (av_sep === -1) {
                av_key = av;
                av_value = null;
            }
            else {
                av_key = av.substr(0, av_sep);
                av_value = av.substr(av_sep + 1);
            }
            av_key = av_key.trim().toLowerCase();
            if (av_value) {
                av_value = av_value.trim();
            }
            switch (av_key) {
                case 'expires': // S5.2.1
                    if (av_value) {
                        var exp = parseDate(av_value);
                        // "If the attribute-value failed to parse as a cookie date, ignore the
                        // cookie-av."
                        if (exp) {
                            // over and underflow not realistically a concern: V8's getTime() seems to
                            // store something larger than a 32-bit time_t (even with 32-bit node)
                            c.expires = exp;
                        }
                    }
                    break;
                case 'max-age': // S5.2.2
                    if (av_value) {
                        // "If the first character of the attribute-value is not a DIGIT or a "-"
                        // character ...[or]... If the remainder of attribute-value contains a
                        // non-DIGIT character, ignore the cookie-av."
                        if (/^-?[0-9]+$/.test(av_value)) {
                            var delta = parseInt(av_value, 10);
                            // "If delta-seconds is less than or equal to zero (0), let expiry-time
                            // be the earliest representable date and time."
                            c.setMaxAge(delta);
                        }
                    }
                    break;
                case 'domain': // S5.2.3
                    // "If the attribute-value is empty, the behavior is undefined.  However,
                    // the user agent SHOULD ignore the cookie-av entirely."
                    if (av_value) {
                        // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
                        // (".") character."
                        var domain = av_value.trim().replace(/^\./, '');
                        if (domain) {
                            // "Convert the cookie-domain to lower case."
                            c.domain = domain.toLowerCase();
                        }
                    }
                    break;
                case 'path': // S5.2.4
                    /*
                     * "If the attribute-value is empty or if the first character of the
                     * attribute-value is not %x2F ("/"):
                     *   Let cookie-path be the default-path.
                     * Otherwise:
                     *   Let cookie-path be the attribute-value."
                     *
                     * We'll represent the default-path as null since it depends on the
                     * context of the parsing.
                     */
                    c.path = av_value && av_value[0] === "/" ? av_value : null;
                    break;
                case 'secure': // S5.2.5
                    /*
                     * "If the attribute-name case-insensitively matches the string "Secure",
                     * the user agent MUST append an attribute to the cookie-attribute-list
                     * with an attribute-name of Secure and an empty attribute-value."
                     */
                    c.secure = true;
                    break;
                case 'httponly': // S5.2.6 -- effectively the same as 'secure'
                    c.httpOnly = true;
                    break;
                default:
                    c.extensions = c.extensions || [];
                    c.extensions.push(av);
                    break;
            }
        }
        return c;
    }
    // avoid the V8 deoptimization monster!
    function jsonParse(str) {
        var obj;
        try {
            obj = JSON.parse(str);
        }
        catch (e) {
            return e;
        }
        return obj;
    }
    function fromJSON(str) {
        if (!str) {
            return null;
        }
        var obj;
        if (typeof str === 'string') {
            obj = jsonParse(str);
            if (obj instanceof Error) {
                return null;
            }
        }
        else {
            // assume it's an Object
            obj = str;
        }
        var c = new Cookie();
        for (var i = 0; i < Cookie.serializableProperties.length; i++) {
            var prop = Cookie.serializableProperties[i];
            if (obj[prop] === undefined ||
                obj[prop] === Cookie.prototype[prop]) {
                continue; // leave as prototype default
            }
            if (prop === 'expires' ||
                prop === 'creation' ||
                prop === 'lastAccessed') {
                if (obj[prop] === null) {
                    c[prop] = null;
                }
                else {
                    c[prop] = obj[prop] == "Infinity" ?
                        "Infinity" : new Date(obj[prop]);
                }
            }
            else {
                c[prop] = obj[prop];
            }
        }
        return c;
    }
    /* Section 5.4 part 2:
     * "*  Cookies with longer paths are listed before cookies with
     *     shorter paths.
     *
     *  *  Among cookies that have equal-length path fields, cookies with
     *     earlier creation-times are listed before cookies with later
     *     creation-times."
     */
    function cookieCompare(a, b) {
        var cmp = 0;
        // descending for length: b CMP a
        var aPathLen = a.path ? a.path.length : 0;
        var bPathLen = b.path ? b.path.length : 0;
        cmp = bPathLen - aPathLen;
        if (cmp !== 0) {
            return cmp;
        }
        // ascending for time: a CMP b
        var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
        var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
        cmp = aTime - bTime;
        if (cmp !== 0) {
            return cmp;
        }
        // break ties for the same millisecond (precision of JavaScript's clock)
        cmp = a.creationIndex - b.creationIndex;
        return cmp;
    }
    // Gives the permutation of all possible pathMatch()es of a given path. The
    // array is in longest-to-shortest order.  Handy for indexing.
    function permutePath(path) {
        if (path === '/') {
            return ['/'];
        }
        if (path.lastIndexOf('/') === path.length - 1) {
            path = path.substr(0, path.length - 1);
        }
        var permutations = [path];
        while (path.length > 1) {
            var lindex = path.lastIndexOf('/');
            if (lindex === 0) {
                break;
            }
            path = path.substr(0, lindex);
            permutations.push(path);
        }
        permutations.push('/');
        return permutations;
    }
    function getCookieContext(url) {
        if (url instanceof Object) {
            return url;
        }
        // NOTE: decodeURI will throw on malformed URIs (see GH-32).
        // Therefore, we will just skip decoding for such URIs.
        try {
            url = decodeURI(url);
        }
        catch (err) {
            // Silently swallow error
        }
        return urlParse(url);
    }
    function Cookie(options) {
        options = options || {};
        Object.keys(options).forEach(function (prop) {
            if (Cookie.prototype.hasOwnProperty(prop) &&
                Cookie.prototype[prop] !== options[prop] &&
                prop.substr(0, 1) !== '_') {
                this[prop] = options[prop];
            }
        }, this);
        this.creation = this.creation || new Date();
        // used to break creation ties in cookieCompare():
        Object.defineProperty(this, 'creationIndex', {
            configurable: false,
            enumerable: false,
            writable: true,
            value: ++Cookie.cookiesCreated
        });
    }
    Cookie.cookiesCreated = 0; // incremented each time a cookie is created
    Cookie.parse = parse;
    Cookie.fromJSON = fromJSON;
    Cookie.prototype.key = "";
    Cookie.prototype.value = "";
    // the order in which the RFC has them:
    Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
    Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
    Cookie.prototype.domain = null;
    Cookie.prototype.path = null;
    Cookie.prototype.secure = false;
    Cookie.prototype.httpOnly = false;
    Cookie.prototype.extensions = null;
    // set by the CookieJar:
    Cookie.prototype.hostOnly = null; // boolean when set
    Cookie.prototype.pathIsDefault = null; // boolean when set
    Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
    Cookie.prototype.lastAccessed = null; // Date when set
    Object.defineProperty(Cookie.prototype, 'creationIndex', {
        configurable: true,
        enumerable: false,
        writable: true,
        value: 0
    });
    Cookie.serializableProperties = Object.keys(Cookie.prototype)
        .filter(function (prop) {
        return !(Cookie.prototype[prop] instanceof Function ||
            prop === 'creationIndex' ||
            prop.substr(0, 1) === '_');
    });
    Cookie.prototype.inspect = function inspect() {
        var now = Date.now();
        return 'Cookie="' + this.toString() +
            '; hostOnly=' + (this.hostOnly != null ? this.hostOnly : '?') +
            '; aAge=' + (this.lastAccessed ? (now - this.lastAccessed.getTime()) + 'ms' : '?') +
            '; cAge=' + (this.creation ? (now - this.creation.getTime()) + 'ms' : '?') +
            '"';
    };
    Cookie.prototype.toJSON = function () {
        var obj = {};
        var props = Cookie.serializableProperties;
        for (var i = 0; i < props.length; i++) {
            var prop = props[i];
            if (this[prop] === Cookie.prototype[prop]) {
                continue; // leave as prototype default
            }
            if (prop === 'expires' ||
                prop === 'creation' ||
                prop === 'lastAccessed') {
                if (this[prop] === null) {
                    obj[prop] = null;
                }
                else {
                    obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
                        "Infinity" : this[prop].toISOString();
                }
            }
            else if (prop === 'maxAge') {
                if (this[prop] !== null) {
                    // again, intentionally not ===
                    obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
                        this[prop].toString() : this[prop];
                }
            }
            else {
                if (this[prop] !== Cookie.prototype[prop]) {
                    obj[prop] = this[prop];
                }
            }
        }
        return obj;
    };
    Cookie.prototype.clone = function () {
        return fromJSON(this.toJSON());
    };
    Cookie.prototype.validate = function validate() {
        if (!COOKIE_OCTETS.test(this.value)) {
            return false;
        }
        if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
            return false;
        }
        if (this.maxAge != null && this.maxAge <= 0) {
            return false; // "Max-Age=" non-zero-digit *DIGIT
        }
        if (this.path != null && !PATH_VALUE.test(this.path)) {
            return false;
        }
        var cdomain = this.cdomain();
        if (cdomain) {
            if (cdomain.match(/\.$/)) {
                return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
            }
            var suffix = pubsuffix.getPublicSuffix(cdomain);
            if (suffix == null) { // it's a public suffix
                return false;
            }
        }
        return true;
    };
    Cookie.prototype.setExpires = function setExpires(exp) {
        if (exp instanceof Date) {
            this.expires = exp;
        }
        else {
            this.expires = parseDate(exp) || "Infinity";
        }
    };
    Cookie.prototype.setMaxAge = function setMaxAge(age) {
        if (age === Infinity || age === -Infinity) {
            this.maxAge = age.toString(); // so JSON.stringify() works
        }
        else {
            this.maxAge = age;
        }
    };
    // gives Cookie header format
    Cookie.prototype.cookieString = function cookieString() {
        var val = this.value;
        if (val == null) {
            val = '';
        }
        if (this.key === '') {
            return val;
        }
        return this.key + '=' + val;
    };
    // gives Set-Cookie header format
    Cookie.prototype.toString = function toString() {
        var str = this.cookieString();
        if (this.expires != Infinity) {
            if (this.expires instanceof Date) {
                str += '; Expires=' + formatDate(this.expires);
            }
            else {
                str += '; Expires=' + this.expires;
            }
        }
        if (this.maxAge != null && this.maxAge != Infinity) {
            str += '; Max-Age=' + this.maxAge;
        }
        if (this.domain && !this.hostOnly) {
            str += '; Domain=' + this.domain;
        }
        if (this.path) {
            str += '; Path=' + this.path;
        }
        if (this.secure) {
            str += '; Secure';
        }
        if (this.httpOnly) {
            str += '; HttpOnly';
        }
        if (this.extensions) {
            this.extensions.forEach(function (ext) {
                str += '; ' + ext;
            });
        }
        return str;
    };
    // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
    // elsewhere)
    // S5.3 says to give the "latest representable date" for which we use Infinity
    // For "expired" we use 0
    Cookie.prototype.TTL = function TTL(now) {
        /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
         * attribute, the Max-Age attribute has precedence and controls the
         * expiration date of the cookie.
         * (Concurs with S5.3 step 3)
         */
        if (this.maxAge != null) {
            return this.maxAge <= 0 ? 0 : this.maxAge * 1000;
        }
        var expires = this.expires;
        if (expires != Infinity) {
            if (!(expires instanceof Date)) {
                expires = parseDate(expires) || Infinity;
            }
            if (expires == Infinity) {
                return Infinity;
            }
            return expires.getTime() - (now || Date.now());
        }
        return Infinity;
    };
    // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
    // elsewhere)
    Cookie.prototype.expiryTime = function expiryTime(now) {
        if (this.maxAge != null) {
            var relativeTo = now || this.creation || new Date();
            var age = (this.maxAge <= 0) ? -Infinity : this.maxAge * 1000;
            return relativeTo.getTime() + age;
        }
        if (this.expires == Infinity) {
            return Infinity;
        }
        return this.expires.getTime();
    };
    // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
    // elsewhere), except it returns a Date
    Cookie.prototype.expiryDate = function expiryDate(now) {
        var millisec = this.expiryTime(now);
        if (millisec == Infinity) {
            return new Date(MAX_TIME);
        }
        else if (millisec == -Infinity) {
            return new Date(MIN_TIME);
        }
        else {
            return new Date(millisec);
        }
    };
    // This replaces the "persistent-flag" parts of S5.3 step 3
    Cookie.prototype.isPersistent = function isPersistent() {
        return (this.maxAge != null || this.expires != Infinity);
    };
    // Mostly S5.1.2 and S5.2.3:
    Cookie.prototype.cdomain =
        Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
            if (this.domain == null) {
                return null;
            }
            return canonicalDomain(this.domain);
        };
    function CookieJar(store, options) {
        if (typeof options === "boolean") {
            options = { rejectPublicSuffixes: options };
        }
        else if (options == null) {
            options = {};
        }
        if (options.rejectPublicSuffixes != null) {
            this.rejectPublicSuffixes = options.rejectPublicSuffixes;
        }
        if (options.looseMode != null) {
            this.enableLooseMode = options.looseMode;
        }
        if (!store) {
            store = new MemoryCookieStore();
        }
        this.store = store;
    }
    CookieJar.prototype.store = null;
    CookieJar.prototype.rejectPublicSuffixes = true;
    CookieJar.prototype.enableLooseMode = false;
    var CAN_BE_SYNC = [];
    CAN_BE_SYNC.push('setCookie');
    CookieJar.prototype.setCookie = function (cookie, url, options, cb) {
        var err;
        var context = getCookieContext(url);
        if (options instanceof Function) {
            cb = options;
            options = {};
        }
        var host = canonicalDomain(context.hostname);
        var loose = this.enableLooseMode;
        if (options.loose != null) {
            loose = options.loose;
        }
        // S5.3 step 1
        if (!(cookie instanceof Cookie)) {
            cookie = Cookie.parse(cookie, { loose: loose });
        }
        if (!cookie) {
            err = new Error("Cookie failed to parse");
            return cb(options.ignoreError ? null : err);
        }
        // S5.3 step 2
        var now = options.now || new Date(); // will assign later to save effort in the face of errors
        // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
        // S5.3 step 4: NOOP; domain is null by default
        // S5.3 step 5: public suffixes
        if (this.rejectPublicSuffixes && cookie.domain) {
            var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
            if (suffix == null) { // e.g. "com"
                err = new Error("Cookie has domain set to a public suffix");
                return cb(options.ignoreError ? null : err);
            }
        }
        // S5.3 step 6:
        if (cookie.domain) {
            if (!domainMatch(host, cookie.cdomain(), false)) {
                err = new Error("Cookie not in this host's domain. Cookie:" + cookie.cdomain() + " Request:" + host);
                return cb(options.ignoreError ? null : err);
            }
            if (cookie.hostOnly == null) { // don't reset if already set
                cookie.hostOnly = false;
            }
        }
        else {
            cookie.hostOnly = true;
            cookie.domain = host;
        }
        //S5.2.4 If the attribute-value is empty or if the first character of the
        //attribute-value is not %x2F ("/"):
        //Let cookie-path be the default-path.
        if (!cookie.path || cookie.path[0] !== '/') {
            cookie.path = defaultPath(context.pathname);
            cookie.pathIsDefault = true;
        }
        // S5.3 step 8: NOOP; secure attribute
        // S5.3 step 9: NOOP; httpOnly attribute
        // S5.3 step 10
        if (options.http === false && cookie.httpOnly) {
            err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
            return cb(options.ignoreError ? null : err);
        }
        var store = this.store;
        if (!store.updateCookie) {
            store.updateCookie = function (oldCookie, newCookie, cb) {
                this.putCookie(newCookie, cb);
            };
        }
        function withCookie(err, oldCookie) {
            if (err) {
                return cb(err);
            }
            var next = function (err) {
                if (err) {
                    return cb(err);
                }
                else {
                    cb(null, cookie);
                }
            };
            if (oldCookie) {
                // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
                // domain, and path as the newly created cookie:"
                if (options.http === false && oldCookie.httpOnly) { // step 11.2
                    err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
                    return cb(options.ignoreError ? null : err);
                }
                cookie.creation = oldCookie.creation; // step 11.3
                cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
                cookie.lastAccessed = now;
                // Step 11.4 (delete cookie) is implied by just setting the new one:
                store.updateCookie(oldCookie, cookie, next); // step 12
            }
            else {
                cookie.creation = cookie.lastAccessed = now;
                store.putCookie(cookie, next); // step 12
            }
        }
        store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
    };
    // RFC6365 S5.4
    CAN_BE_SYNC.push('getCookies');
    CookieJar.prototype.getCookies = function (url, options, cb) {
        var context = getCookieContext(url);
        if (options instanceof Function) {
            cb = options;
            options = {};
        }
        var host = canonicalDomain(context.hostname);
        var path = context.pathname || '/';
        var secure = options.secure;
        if (secure == null && context.protocol &&
            (context.protocol == 'https:' || context.protocol == 'wss:')) {
            secure = true;
        }
        var http = options.http;
        if (http == null) {
            http = true;
        }
        var now = options.now || Date.now();
        var expireCheck = options.expire !== false;
        var allPaths = !!options.allPaths;
        var store = this.store;
        function matchingCookie(c) {
            // "Either:
            //   The cookie's host-only-flag is true and the canonicalized
            //   request-host is identical to the cookie's domain.
            // Or:
            //   The cookie's host-only-flag is false and the canonicalized
            //   request-host domain-matches the cookie's domain."
            if (c.hostOnly) {
                if (c.domain != host) {
                    return false;
                }
            }
            else {
                if (!domainMatch(host, c.domain, false)) {
                    return false;
                }
            }
            // "The request-uri's path path-matches the cookie's path."
            if (!allPaths && !pathMatch(path, c.path)) {
                return false;
            }
            // "If the cookie's secure-only-flag is true, then the request-uri's
            // scheme must denote a "secure" protocol"
            if (c.secure && !secure) {
                return false;
            }
            // "If the cookie's http-only-flag is true, then exclude the cookie if the
            // cookie-string is being generated for a "non-HTTP" API"
            if (c.httpOnly && !http) {
                return false;
            }
            // deferred from S5.3
            // non-RFC: allow retention of expired cookies by choice
            if (expireCheck && c.expiryTime() <= now) {
                store.removeCookie(c.domain, c.path, c.key, function () { }); // result ignored
                return false;
            }
            return true;
        }
        store.findCookies(host, allPaths ? null : path, function (err, cookies) {
            if (err) {
                return cb(err);
            }
            cookies = cookies.filter(matchingCookie);
            // sorting of S5.4 part 2
            if (options.sort !== false) {
                cookies = cookies.sort(cookieCompare);
            }
            // S5.4 part 3
            var now = new Date();
            cookies.forEach(function (c) {
                c.lastAccessed = now;
            });
            // TODO persist lastAccessed
            cb(null, cookies);
        });
    };
    CAN_BE_SYNC.push('getCookieString');
    CookieJar.prototype.getCookieString = function ( /*..., cb*/) {
        var args = Array.prototype.slice.call(arguments, 0);
        var cb = args.pop();
        var next = function (err, cookies) {
            if (err) {
                cb(err);
            }
            else {
                cb(null, cookies
                    .sort(cookieCompare)
                    .map(function (c) {
                    return c.cookieString();
                })
                    .join('; '));
            }
        };
        args.push(next);
        this.getCookies.apply(this, args);
    };
    CAN_BE_SYNC.push('getSetCookieStrings');
    CookieJar.prototype.getSetCookieStrings = function ( /*..., cb*/) {
        var args = Array.prototype.slice.call(arguments, 0);
        var cb = args.pop();
        var next = function (err, cookies) {
            if (err) {
                cb(err);
            }
            else {
                cb(null, cookies.map(function (c) {
                    return c.toString();
                }));
            }
        };
        args.push(next);
        this.getCookies.apply(this, args);
    };
    CAN_BE_SYNC.push('serialize');
    CookieJar.prototype.serialize = function (cb) {
        var type = this.store.constructor.name;
        if (type === 'Object') {
            type = null;
        }
        // update README.md "Serialization Format" if you change this, please!
        var serialized = {
            // The version of tough-cookie that serialized this jar. Generally a good
            // practice since future versions can make data import decisions based on
            // known past behavior. When/if this matters, use `semver`.
            version: 'tough-cookie@' + VERSION,
            // add the store type, to make humans happy:
            storeType: type,
            // CookieJar configuration:
            rejectPublicSuffixes: !!this.rejectPublicSuffixes,
            // this gets filled from getAllCookies:
            cookies: []
        };
        if (!(this.store.getAllCookies &&
            typeof this.store.getAllCookies === 'function')) {
            return cb(new Error('store does not support getAllCookies and cannot be serialized'));
        }
        this.store.getAllCookies(function (err, cookies) {
            if (err) {
                return cb(err);
            }
            serialized.cookies = cookies.map(function (cookie) {
                // convert to serialized 'raw' cookies
                cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
                // Remove the index so new ones get assigned during deserialization
                delete cookie.creationIndex;
                return cookie;
            });
            return cb(null, serialized);
        });
    };
    // well-known name that JSON.stringify calls
    CookieJar.prototype.toJSON = function () {
        return this.serializeSync();
    };
    // use the class method CookieJar.deserialize instead of calling this directly
    CAN_BE_SYNC.push('_importCookies');
    CookieJar.prototype._importCookies = function (serialized, cb) {
        var jar = this;
        var cookies = serialized.cookies;
        if (!cookies || !Array.isArray(cookies)) {
            return cb(new Error('serialized jar has no cookies array'));
        }
        cookies = cookies.slice(); // do not modify the original
        function putNext(err) {
            if (err) {
                return cb(err);
            }
            if (!cookies.length) {
                return cb(err, jar);
            }
            var cookie;
            try {
                cookie = fromJSON(cookies.shift());
            }
            catch (e) {
                return cb(e);
            }
            if (cookie === null) {
                return putNext(null); // skip this cookie
            }
            jar.store.putCookie(cookie, putNext);
        }
        putNext();
    };
    CookieJar.deserialize = function (strOrObj, store, cb) {
        if (arguments.length !== 3) {
            // store is optional
            cb = store;
            store = null;
        }
        var serialized;
        if (typeof strOrObj === 'string') {
            serialized = jsonParse(strOrObj);
            if (serialized instanceof Error) {
                return cb(serialized);
            }
        }
        else {
            serialized = strOrObj;
        }
        var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
        jar._importCookies(serialized, function (err) {
            if (err) {
                return cb(err);
            }
            cb(null, jar);
        });
    };
    CookieJar.deserializeSync = function (strOrObj, store) {
        var serialized = typeof strOrObj === 'string' ?
            JSON.parse(strOrObj) : strOrObj;
        var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
        // catch this mistake early:
        if (!jar.store.synchronous) {
            throw new Error('CookieJar store is not synchronous; use async API instead.');
        }
        jar._importCookiesSync(serialized);
        return jar;
    };
    CookieJar.fromJSON = CookieJar.deserializeSync;
    CAN_BE_SYNC.push('clone');
    CookieJar.prototype.clone = function (newStore, cb) {
        if (arguments.length === 1) {
            cb = newStore;
            newStore = null;
        }
        this.serialize(function (err, serialized) {
            if (err) {
                return cb(err);
            }
            CookieJar.deserialize(newStore, serialized, cb);
        });
    };
    // Use a closure to provide a true imperative API for synchronous stores.
    function syncWrap(method) {
        return function () {
            if (!this.store.synchronous) {
                throw new Error('CookieJar store is not synchronous; use async API instead.');
            }
            var args = Array.prototype.slice.call(arguments);
            var syncErr, syncResult;
            args.push(function syncCb(err, result) {
                syncErr = err;
                syncResult = result;
            });
            this[method].apply(this, args);
            if (syncErr) {
                throw syncErr;
            }
            return syncResult;
        };
    }
    // wrap all declared CAN_BE_SYNC methods in the sync wrapper
    CAN_BE_SYNC.forEach(function (method) {
        CookieJar.prototype[method + 'Sync'] = syncWrap(method);
    });
    module.exports = {
        CookieJar: CookieJar,
        Cookie: Cookie,
        Store: Store,
        MemoryCookieStore: MemoryCookieStore,
        parseDate: parseDate,
        formatDate: formatDate,
        parse: parse,
        fromJSON: fromJSON,
        domainMatch: domainMatch,
        defaultPath: defaultPath,
        pathMatch: pathMatch,
        getPublicSuffix: pubsuffix.getPublicSuffix,
        cookieCompare: cookieCompare,
        permuteDomain: require(361) /* ./permuteDomain */.permuteDomain,
        permutePath: permutePath,
        canonicalDomain: canonicalDomain
    };
}
,
/* tough-cookie/lib/memstore */ function _(require, module, exports) {
    var Store = require(363) /* ./store */.Store;
    var permuteDomain = require(361) /* ./permuteDomain */.permuteDomain;
    var pathMatch = require(360) /* ./pathMatch */.pathMatch;
    var util = require('util');
    function MemoryCookieStore() {
        Store.call(this);
        this.idx = {};
    }
    util.inherits(MemoryCookieStore, Store);
    exports.MemoryCookieStore = MemoryCookieStore;
    MemoryCookieStore.prototype.idx = null;
    // Since it's just a struct in RAM, this Store is synchronous
    MemoryCookieStore.prototype.synchronous = true;
    // force a default depth:
    MemoryCookieStore.prototype.inspect = function () {
        return "{ idx: " + util.inspect(this.idx, false, 2) + ' }';
    };
    MemoryCookieStore.prototype.findCookie = function (domain, path, key, cb) {
        if (!this.idx[domain]) {
            return cb(null, undefined);
        }
        if (!this.idx[domain][path]) {
            return cb(null, undefined);
        }
        return cb(null, this.idx[domain][path][key] || null);
    };
    MemoryCookieStore.prototype.findCookies = function (domain, path, cb) {
        var results = [];
        if (!domain) {
            return cb(null, []);
        }
        var pathMatcher;
        if (!path) {
            // null means "all paths"
            pathMatcher = function matchAll(domainIndex) {
                for (var curPath in domainIndex) {
                    var pathIndex = domainIndex[curPath];
                    for (var key in pathIndex) {
                        results.push(pathIndex[key]);
                    }
                }
            };
        }
        else {
            pathMatcher = function matchRFC(domainIndex) {
                //NOTE: we should use path-match algorithm from S5.1.4 here
                //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
                Object.keys(domainIndex).forEach(function (cookiePath) {
                    if (pathMatch(path, cookiePath)) {
                        var pathIndex = domainIndex[cookiePath];
                        for (var key in pathIndex) {
                            results.push(pathIndex[key]);
                        }
                    }
                });
            };
        }
        var domains = permuteDomain(domain) || [domain];
        var idx = this.idx;
        domains.forEach(function (curDomain) {
            var domainIndex = idx[curDomain];
            if (!domainIndex) {
                return;
            }
            pathMatcher(domainIndex);
        });
        cb(null, results);
    };
    MemoryCookieStore.prototype.putCookie = function (cookie, cb) {
        if (!this.idx[cookie.domain]) {
            this.idx[cookie.domain] = {};
        }
        if (!this.idx[cookie.domain][cookie.path]) {
            this.idx[cookie.domain][cookie.path] = {};
        }
        this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
        cb(null);
    };
    MemoryCookieStore.prototype.updateCookie = function (oldCookie, newCookie, cb) {
        // updateCookie() may avoid updating cookies that are identical.  For example,
        // lastAccessed may not be important to some stores and an equality
        // comparison could exclude that field.
        this.putCookie(newCookie, cb);
    };
    MemoryCookieStore.prototype.removeCookie = function (domain, path, key, cb) {
        if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
            delete this.idx[domain][path][key];
        }
        cb(null);
    };
    MemoryCookieStore.prototype.removeCookies = function (domain, path, cb) {
        if (this.idx[domain]) {
            if (path) {
                delete this.idx[domain][path];
            }
            else {
                delete this.idx[domain];
            }
        }
        return cb(null);
    };
    MemoryCookieStore.prototype.getAllCookies = function (cb) {
        var cookies = [];
        var idx = this.idx;
        var domains = Object.keys(idx);
        domains.forEach(function (domain) {
            var paths = Object.keys(idx[domain]);
            paths.forEach(function (path) {
                var keys = Object.keys(idx[domain][path]);
                keys.forEach(function (key) {
                    if (key !== null) {
                        cookies.push(idx[domain][path][key]);
                    }
                });
            });
        });
        // Sort by creationIndex so deserializing retains the creation order.
        // When implementing your own store, this SHOULD retain the order too
        cookies.sort(function (a, b) {
            return (a.creationIndex || 0) - (b.creationIndex || 0);
        });
        cb(null, cookies);
    };
}
,
/* tough-cookie/lib/pathMatch */ function _(require, module, exports) {
    /*
     * "A request-path path-matches a given cookie-path if at least one of the
     * following conditions holds:"
     */
    function pathMatch(reqPath, cookiePath) {
        // "o  The cookie-path and the request-path are identical."
        if (cookiePath === reqPath) {
            return true;
        }
        var idx = reqPath.indexOf(cookiePath);
        if (idx === 0) {
            // "o  The cookie-path is a prefix of the request-path, and the last
            // character of the cookie-path is %x2F ("/")."
            if (cookiePath.substr(-1) === "/") {
                return true;
            }
            // " o  The cookie-path is a prefix of the request-path, and the first
            // character of the request-path that is not included in the cookie- path
            // is a %x2F ("/") character."
            if (reqPath.substr(cookiePath.length, 1) === "/") {
                return true;
            }
        }
        return false;
    }
    exports.pathMatch = pathMatch;
}
,
/* tough-cookie/lib/permuteDomain */ function _(require, module, exports) {
    var pubsuffix = require(362) /* ./pubsuffix */;
    // Gives the permutation of all possible domainMatch()es of a given domain. The
    // array is in shortest-to-longest order.  Handy for indexing.
    function permuteDomain(domain) {
        var pubSuf = pubsuffix.getPublicSuffix(domain);
        if (!pubSuf) {
            return null;
        }
        if (pubSuf == domain) {
            return [domain];
        }
        var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
        var parts = prefix.split('.').reverse();
        var cur = pubSuf;
        var permutations = [cur];
        while (parts.length) {
            cur = parts.shift() + '.' + cur;
            permutations.push(cur);
        }
        return permutations;
    }
    exports.permuteDomain = permuteDomain;
}
,
/* tough-cookie/lib/pubsuffix */ function _(require, module, exports) {
    var punycode = require('punycode');
    module.exports.getPublicSuffix = function getPublicSuffix(domain) {
        /*!
         * Copyright (c) 2015, Salesforce.com, Inc.
         * All rights reserved.
         *
         * Redistribution and use in source and binary forms, with or without
         * modification, are permitted provided that the following conditions are met:
         *
         * 1. Redistributions of source code must retain the above copyright notice,
         * this list of conditions and the following disclaimer.
         *
         * 2. 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.
         *
         * 3. Neither the name of Salesforce.com 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 HOLDER OR CONTRIBUTORS BE
         * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
         * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
         * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
         * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
         * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
         * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
         * POSSIBILITY OF SUCH DAMAGE.
         */
        if (!domain) {
            return null;
        }
        if (domain.match(/^\./)) {
            return null;
        }
        var asciiDomain = punycode.toASCII(domain);
        var converted = false;
        if (asciiDomain !== domain) {
            domain = asciiDomain;
            converted = true;
        }
        if (index[domain]) {
            return null;
        }
        domain = domain.toLowerCase();
        var parts = domain.split('.').reverse();
        var suffix = '';
        var suffixLen = 0;
        for (var i = 0; i < parts.length; i++) {
            var part = parts[i];
            var starstr = '*' + suffix;
            var partstr = part + suffix;
            if (index[starstr]) { // star rule matches
                suffixLen = i + 1;
                if (index[partstr] === false) { // exception rule matches (NB: false, not undefined)
                    suffixLen--;
                }
            }
            else if (index[partstr]) { // exact match, not exception
                suffixLen = i + 1;
            }
            suffix = '.' + partstr;
        }
        if (index['*' + suffix]) { // *.domain exists (e.g. *.kyoto.jp for domain='kyoto.jp');
            return null;
        }
        suffixLen = suffixLen || 1;
        if (parts.length > suffixLen) {
            var publicSuffix = parts.slice(0, suffixLen + 1).reverse().join('.');
            return converted ? punycode.toUnicode(publicSuffix) : publicSuffix;
        }
        return null;
    };
    // The following generated structure is used under the MPL version 2.0
    // See public-suffix.txt for more information
    var index = module.exports.index = Object.freeze({ "ac": true, "com.ac": true, "edu.ac": true, "gov.ac": true, "net.ac": true, "mil.ac": true, "org.ac": true, "ad": true, "nom.ad": true, "ae": true, "co.ae": true, "net.ae": true, "org.ae": true, "sch.ae": true, "ac.ae": true, "gov.ae": true, "mil.ae": true, "aero": true, "accident-investigation.aero": true, "accident-prevention.aero": true, "aerobatic.aero": true, "aeroclub.aero": true, "aerodrome.aero": true, "agents.aero": true, "aircraft.aero": true, "airline.aero": true, "airport.aero": true, "air-surveillance.aero": true, "airtraffic.aero": true, "air-traffic-control.aero": true, "ambulance.aero": true, "amusement.aero": true, "association.aero": true, "author.aero": true, "ballooning.aero": true, "broker.aero": true, "caa.aero": true, "cargo.aero": true, "catering.aero": true, "certification.aero": true, "championship.aero": true, "charter.aero": true, "civilaviation.aero": true, "club.aero": true, "conference.aero": true, "consultant.aero": true, "consulting.aero": true, "control.aero": true, "council.aero": true, "crew.aero": true, "design.aero": true, "dgca.aero": true, "educator.aero": true, "emergency.aero": true, "engine.aero": true, "engineer.aero": true, "entertainment.aero": true, "equipment.aero": true, "exchange.aero": true, "express.aero": true, "federation.aero": true, "flight.aero": true, "freight.aero": true, "fuel.aero": true, "gliding.aero": true, "government.aero": true, "groundhandling.aero": true, "group.aero": true, "hanggliding.aero": true, "homebuilt.aero": true, "insurance.aero": true, "journal.aero": true, "journalist.aero": true, "leasing.aero": true, "logistics.aero": true, "magazine.aero": true, "maintenance.aero": true, "media.aero": true, "microlight.aero": true, "modelling.aero": true, "navigation.aero": true, "parachuting.aero": true, "paragliding.aero": true, "passenger-association.aero": true, "pilot.aero": true, "press.aero": true, "production.aero": true, "recreation.aero": true, "repbody.aero": true, "res.aero": true, "research.aero": true, "rotorcraft.aero": true, "safety.aero": true, "scientist.aero": true, "services.aero": true, "show.aero": true, "skydiving.aero": true, "software.aero": true, "student.aero": true, "trader.aero": true, "trading.aero": true, "trainer.aero": true, "union.aero": true, "workinggroup.aero": true, "works.aero": true, "af": true, "gov.af": true, "com.af": true, "org.af": true, "net.af": true, "edu.af": true, "ag": true, "com.ag": true, "org.ag": true, "net.ag": true, "co.ag": true, "nom.ag": true, "ai": true, "off.ai": true, "com.ai": true, "net.ai": true, "org.ai": true, "al": true, "com.al": true, "edu.al": true, "gov.al": true, "mil.al": true, "net.al": true, "org.al": true, "am": true, "ao": true, "ed.ao": true, "gv.ao": true, "og.ao": true, "co.ao": true, "pb.ao": true, "it.ao": true, "aq": true, "ar": true, "com.ar": true, "edu.ar": true, "gob.ar": true, "gov.ar": true, "int.ar": true, "mil.ar": true, "net.ar": true, "org.ar": true, "tur.ar": true, "arpa": true, "e164.arpa": true, "in-addr.arpa": true, "ip6.arpa": true, "iris.arpa": true, "uri.arpa": true, "urn.arpa": true, "as": true, "gov.as": true, "asia": true, "at": true, "ac.at": true, "co.at": true, "gv.at": true, "or.at": true, "au": true, "com.au": true, "net.au": true, "org.au": true, "edu.au": true, "gov.au": true, "asn.au": true, "id.au": true, "info.au": true, "conf.au": true, "oz.au": true, "act.au": true, "nsw.au": true, "nt.au": true, "qld.au": true, "sa.au": true, "tas.au": true, "vic.au": true, "wa.au": true, "act.edu.au": true, "nsw.edu.au": true, "nt.edu.au": true, "qld.edu.au": true, "sa.edu.au": true, "tas.edu.au": true, "vic.edu.au": true, "wa.edu.au": true, "qld.gov.au": true, "sa.gov.au": true, "tas.gov.au": true, "vic.gov.au": true, "wa.gov.au": true, "aw": true, "com.aw": true, "ax": true, "az": true, "com.az": true, "net.az": true, "int.az": true, "gov.az": true, "org.az": true, "edu.az": true, "info.az": true, "pp.az": true, "mil.az": true, "name.az": true, "pro.az": true, "biz.az": true, "ba": true, "com.ba": true, "edu.ba": true, "gov.ba": true, "mil.ba": true, "net.ba": true, "org.ba": true, "bb": true, "biz.bb": true, "co.bb": true, "com.bb": true, "edu.bb": true, "gov.bb": true, "info.bb": true, "net.bb": true, "org.bb": true, "store.bb": true, "tv.bb": true, "*.bd": true, "be": true, "ac.be": true, "bf": true, "gov.bf": true, "bg": true, "a.bg": true, "b.bg": true, "c.bg": true, "d.bg": true, "e.bg": true, "f.bg": true, "g.bg": true, "h.bg": true, "i.bg": true, "j.bg": true, "k.bg": true, "l.bg": true, "m.bg": true, "n.bg": true, "o.bg": true, "p.bg": true, "q.bg": true, "r.bg": true, "s.bg": true, "t.bg": true, "u.bg": true, "v.bg": true, "w.bg": true, "x.bg": true, "y.bg": true, "z.bg": true, "0.bg": true, "1.bg": true, "2.bg": true, "3.bg": true, "4.bg": true, "5.bg": true, "6.bg": true, "7.bg": true, "8.bg": true, "9.bg": true, "bh": true, "com.bh": true, "edu.bh": true, "net.bh": true, "org.bh": true, "gov.bh": true, "bi": true, "co.bi": true, "com.bi": true, "edu.bi": true, "or.bi": true, "org.bi": true, "biz": true, "bj": true, "asso.bj": true, "barreau.bj": true, "gouv.bj": true, "bm": true, "com.bm": true, "edu.bm": true, "gov.bm": true, "net.bm": true, "org.bm": true, "*.bn": true, "bo": true, "com.bo": true, "edu.bo": true, "gov.bo": true, "gob.bo": true, "int.bo": true, "org.bo": true, "net.bo": true, "mil.bo": true, "tv.bo": true, "br": true, "adm.br": true, "adv.br": true, "agr.br": true, "am.br": true, "arq.br": true, "art.br": true, "ato.br": true, "b.br": true, "bio.br": true, "blog.br": true, "bmd.br": true, "cim.br": true, "cng.br": true, "cnt.br": true, "com.br": true, "coop.br": true, "ecn.br": true, "eco.br": true, "edu.br": true, "emp.br": true, "eng.br": true, "esp.br": true, "etc.br": true, "eti.br": true, "far.br": true, "flog.br": true, "fm.br": true, "fnd.br": true, "fot.br": true, "fst.br": true, "g12.br": true, "ggf.br": true, "gov.br": true, "imb.br": true, "ind.br": true, "inf.br": true, "jor.br": true, "jus.br": true, "leg.br": true, "lel.br": true, "mat.br": true, "med.br": true, "mil.br": true, "mp.br": true, "mus.br": true, "net.br": true, "*.nom.br": true, "not.br": true, "ntr.br": true, "odo.br": true, "org.br": true, "ppg.br": true, "pro.br": true, "psc.br": true, "psi.br": true, "qsl.br": true, "radio.br": true, "rec.br": true, "slg.br": true, "srv.br": true, "taxi.br": true, "teo.br": true, "tmp.br": true, "trd.br": true, "tur.br": true, "tv.br": true, "vet.br": true, "vlog.br": true, "wiki.br": true, "zlg.br": true, "bs": true, "com.bs": true, "net.bs": true, "org.bs": true, "edu.bs": true, "gov.bs": true, "bt": true, "com.bt": true, "edu.bt": true, "gov.bt": true, "net.bt": true, "org.bt": true, "bv": true, "bw": true, "co.bw": true, "org.bw": true, "by": true, "gov.by": true, "mil.by": true, "com.by": true, "of.by": true, "bz": true, "com.bz": true, "net.bz": true, "org.bz": true, "edu.bz": true, "gov.bz": true, "ca": true, "ab.ca": true, "bc.ca": true, "mb.ca": true, "nb.ca": true, "nf.ca": true, "nl.ca": true, "ns.ca": true, "nt.ca": true, "nu.ca": true, "on.ca": true, "pe.ca": true, "qc.ca": true, "sk.ca": true, "yk.ca": true, "gc.ca": true, "cat": true, "cc": true, "cd": true, "gov.cd": true, "cf": true, "cg": true, "ch": true, "ci": true, "org.ci": true, "or.ci": true, "com.ci": true, "co.ci": true, "edu.ci": true, "ed.ci": true, "ac.ci": true, "net.ci": true, "go.ci": true, "asso.ci": true, "xn--aroport-bya.ci": true, "int.ci": true, "presse.ci": true, "md.ci": true, "gouv.ci": true, "*.ck": true, "www.ck": false, "cl": true, "gov.cl": true, "gob.cl": true, "co.cl": true, "mil.cl": true, "cm": true, "co.cm": true, "com.cm": true, "gov.cm": true, "net.cm": true, "cn": true, "ac.cn": true, "com.cn": true, "edu.cn": true, "gov.cn": true, "net.cn": true, "org.cn": true, "mil.cn": true, "xn--55qx5d.cn": true, "xn--io0a7i.cn": true, "xn--od0alg.cn": true, "ah.cn": true, "bj.cn": true, "cq.cn": true, "fj.cn": true, "gd.cn": true, "gs.cn": true, "gz.cn": true, "gx.cn": true, "ha.cn": true, "hb.cn": true, "he.cn": true, "hi.cn": true, "hl.cn": true, "hn.cn": true, "jl.cn": true, "js.cn": true, "jx.cn": true, "ln.cn": true, "nm.cn": true, "nx.cn": true, "qh.cn": true, "sc.cn": true, "sd.cn": true, "sh.cn": true, "sn.cn": true, "sx.cn": true, "tj.cn": true, "xj.cn": true, "xz.cn": true, "yn.cn": true, "zj.cn": true, "hk.cn": true, "mo.cn": true, "tw.cn": true, "co": true, "arts.co": true, "com.co": true, "edu.co": true, "firm.co": true, "gov.co": true, "info.co": true, "int.co": true, "mil.co": true, "net.co": true, "nom.co": true, "org.co": true, "rec.co": true, "web.co": true, "com": true, "coop": true, "cr": true, "ac.cr": true, "co.cr": true, "ed.cr": true, "fi.cr": true, "go.cr": true, "or.cr": true, "sa.cr": true, "cu": true, "com.cu": true, "edu.cu": true, "org.cu": true, "net.cu": true, "gov.cu": true, "inf.cu": true, "cv": true, "cw": true, "com.cw": true, "edu.cw": true, "net.cw": true, "org.cw": true, "cx": true, "gov.cx": true, "cy": true, "ac.cy": true, "biz.cy": true, "com.cy": true, "ekloges.cy": true, "gov.cy": true, "ltd.cy": true, "name.cy": true, "net.cy": true, "org.cy": true, "parliament.cy": true, "press.cy": true, "pro.cy": true, "tm.cy": true, "cz": true, "de": true, "dj": true, "dk": true, "dm": true, "com.dm": true, "net.dm": true, "org.dm": true, "edu.dm": true, "gov.dm": true, "do": true, "art.do": true, "com.do": true, "edu.do": true, "gob.do": true, "gov.do": true, "mil.do": true, "net.do": true, "org.do": true, "sld.do": true, "web.do": true, "dz": true, "com.dz": true, "org.dz": true, "net.dz": true, "gov.dz": true, "edu.dz": true, "asso.dz": true, "pol.dz": true, "art.dz": true, "ec": true, "com.ec": true, "info.ec": true, "net.ec": true, "fin.ec": true, "k12.ec": true, "med.ec": true, "pro.ec": true, "org.ec": true, "edu.ec": true, "gov.ec": true, "gob.ec": true, "mil.ec": true, "edu": true, "ee": true, "edu.ee": true, "gov.ee": true, "riik.ee": true, "lib.ee": true, "med.ee": true, "com.ee": true, "pri.ee": true, "aip.ee": true, "org.ee": true, "fie.ee": true, "eg": true, "com.eg": true, "edu.eg": true, "eun.eg": true, "gov.eg": true, "mil.eg": true, "name.eg": true, "net.eg": true, "org.eg": true, "sci.eg": true, "*.er": true, "es": true, "com.es": true, "nom.es": true, "org.es": true, "gob.es": true, "edu.es": true, "et": true, "com.et": true, "gov.et": true, "org.et": true, "edu.et": true, "biz.et": true, "name.et": true, "info.et": true, "net.et": true, "eu": true, "fi": true, "aland.fi": true, "*.fj": true, "*.fk": true, "fm": true, "fo": true, "fr": true, "com.fr": true, "asso.fr": true, "nom.fr": true, "prd.fr": true, "presse.fr": true, "tm.fr": true, "aeroport.fr": true, "assedic.fr": true, "avocat.fr": true, "avoues.fr": true, "cci.fr": true, "chambagri.fr": true, "chirurgiens-dentistes.fr": true, "experts-comptables.fr": true, "geometre-expert.fr": true, "gouv.fr": true, "greta.fr": true, "huissier-justice.fr": true, "medecin.fr": true, "notaires.fr": true, "pharmacien.fr": true, "port.fr": true, "veterinaire.fr": true, "ga": true, "gb": true, "gd": true, "ge": true, "com.ge": true, "edu.ge": true, "gov.ge": true, "org.ge": true, "mil.ge": true, "net.ge": true, "pvt.ge": true, "gf": true, "gg": true, "co.gg": true, "net.gg": true, "org.gg": true, "gh": true, "com.gh": true, "edu.gh": true, "gov.gh": true, "org.gh": true, "mil.gh": true, "gi": true, "com.gi": true, "ltd.gi": true, "gov.gi": true, "mod.gi": true, "edu.gi": true, "org.gi": true, "gl": true, "co.gl": true, "com.gl": true, "edu.gl": true, "net.gl": true, "org.gl": true, "gm": true, "gn": true, "ac.gn": true, "com.gn": true, "edu.gn": true, "gov.gn": true, "org.gn": true, "net.gn": true, "gov": true, "gp": true, "com.gp": true, "net.gp": true, "mobi.gp": true, "edu.gp": true, "org.gp": true, "asso.gp": true, "gq": true, "gr": true, "com.gr": true, "edu.gr": true, "net.gr": true, "org.gr": true, "gov.gr": true, "gs": true, "gt": true, "com.gt": true, "edu.gt": true, "gob.gt": true, "ind.gt": true, "mil.gt": true, "net.gt": true, "org.gt": true, "*.gu": true, "gw": true, "gy": true, "co.gy": true, "com.gy": true, "edu.gy": true, "gov.gy": true, "net.gy": true, "org.gy": true, "hk": true, "com.hk": true, "edu.hk": true, "gov.hk": true, "idv.hk": true, "net.hk": true, "org.hk": true, "xn--55qx5d.hk": true, "xn--wcvs22d.hk": true, "xn--lcvr32d.hk": true, "xn--mxtq1m.hk": true, "xn--gmqw5a.hk": true, "xn--ciqpn.hk": true, "xn--gmq050i.hk": true, "xn--zf0avx.hk": true, "xn--io0a7i.hk": true, "xn--mk0axi.hk": true, "xn--od0alg.hk": true, "xn--od0aq3b.hk": true, "xn--tn0ag.hk": true, "xn--uc0atv.hk": true, "xn--uc0ay4a.hk": true, "hm": true, "hn": true, "com.hn": true, "edu.hn": true, "org.hn": true, "net.hn": true, "mil.hn": true, "gob.hn": true, "hr": true, "iz.hr": true, "from.hr": true, "name.hr": true, "com.hr": true, "ht": true, "com.ht": true, "shop.ht": true, "firm.ht": true, "info.ht": true, "adult.ht": true, "net.ht": true, "pro.ht": true, "org.ht": true, "med.ht": true, "art.ht": true, "coop.ht": true, "pol.ht": true, "asso.ht": true, "edu.ht": true, "rel.ht": true, "gouv.ht": true, "perso.ht": true, "hu": true, "co.hu": true, "info.hu": true, "org.hu": true, "priv.hu": true, "sport.hu": true, "tm.hu": true, "2000.hu": true, "agrar.hu": true, "bolt.hu": true, "casino.hu": true, "city.hu": true, "erotica.hu": true, "erotika.hu": true, "film.hu": true, "forum.hu": true, "games.hu": true, "hotel.hu": true, "ingatlan.hu": true, "jogasz.hu": true, "konyvelo.hu": true, "lakas.hu": true, "media.hu": true, "news.hu": true, "reklam.hu": true, "sex.hu": true, "shop.hu": true, "suli.hu": true, "szex.hu": true, "tozsde.hu": true, "utazas.hu": true, "video.hu": true, "id": true, "ac.id": true, "biz.id": true, "co.id": true, "desa.id": true, "go.id": true, "mil.id": true, "my.id": true, "net.id": true, "or.id": true, "sch.id": true, "web.id": true, "ie": true, "gov.ie": true, "il": true, "ac.il": true, "co.il": true, "gov.il": true, "idf.il": true, "k12.il": true, "muni.il": true, "net.il": true, "org.il": true, "im": true, "ac.im": true, "co.im": true, "com.im": true, "ltd.co.im": true, "net.im": true, "org.im": true, "plc.co.im": true, "tt.im": true, "tv.im": true, "in": true, "co.in": true, "firm.in": true, "net.in": true, "org.in": true, "gen.in": true, "ind.in": true, "nic.in": true, "ac.in": true, "edu.in": true, "res.in": true, "gov.in": true, "mil.in": true, "info": true, "int": true, "eu.int": true, "io": true, "com.io": true, "iq": true, "gov.iq": true, "edu.iq": true, "mil.iq": true, "com.iq": true, "org.iq": true, "net.iq": true, "ir": true, "ac.ir": true, "co.ir": true, "gov.ir": true, "id.ir": true, "net.ir": true, "org.ir": true, "sch.ir": true, "xn--mgba3a4f16a.ir": true, "xn--mgba3a4fra.ir": true, "is": true, "net.is": true, "com.is": true, "edu.is": true, "gov.is": true, "org.is": true, "int.is": true, "it": true, "gov.it": true, "edu.it": true, "abr.it": true, "abruzzo.it": true, "aosta-valley.it": true, "aostavalley.it": true, "bas.it": true, "basilicata.it": true, "cal.it": true, "calabria.it": true, "cam.it": true, "campania.it": true, "emilia-romagna.it": true, "emiliaromagna.it": true, "emr.it": true, "friuli-v-giulia.it": true, "friuli-ve-giulia.it": true, "friuli-vegiulia.it": true, "friuli-venezia-giulia.it": true, "friuli-veneziagiulia.it": true, "friuli-vgiulia.it": true, "friuliv-giulia.it": true, "friulive-giulia.it": true, "friulivegiulia.it": true, "friulivenezia-giulia.it": true, "friuliveneziagiulia.it": true, "friulivgiulia.it": true, "fvg.it": true, "laz.it": true, "lazio.it": true, "lig.it": true, "liguria.it": true, "lom.it": true, "lombardia.it": true, "lombardy.it": true, "lucania.it": true, "mar.it": true, "marche.it": true, "mol.it": true, "molise.it": true, "piedmont.it": true, "piemonte.it": true, "pmn.it": true, "pug.it": true, "puglia.it": true, "sar.it": true, "sardegna.it": true, "sardinia.it": true, "sic.it": true, "sicilia.it": true, "sicily.it": true, "taa.it": true, "tos.it": true, "toscana.it": true, "trentino-a-adige.it": true, "trentino-aadige.it": true, "trentino-alto-adige.it": true, "trentino-altoadige.it": true, "trentino-s-tirol.it": true, "trentino-stirol.it": true, "trentino-sud-tirol.it": true, "trentino-sudtirol.it": true, "trentino-sued-tirol.it": true, "trentino-suedtirol.it": true, "trentinoa-adige.it": true, "trentinoaadige.it": true, "trentinoalto-adige.it": true, "trentinoaltoadige.it": true, "trentinos-tirol.it": true, "trentinostirol.it": true, "trentinosud-tirol.it": true, "trentinosudtirol.it": true, "trentinosued-tirol.it": true, "trentinosuedtirol.it": true, "tuscany.it": true, "umb.it": true, "umbria.it": true, "val-d-aosta.it": true, "val-daosta.it": true, "vald-aosta.it": true, "valdaosta.it": true, "valle-aosta.it": true, "valle-d-aosta.it": true, "valle-daosta.it": true, "valleaosta.it": true, "valled-aosta.it": true, "valledaosta.it": true, "vallee-aoste.it": true, "valleeaoste.it": true, "vao.it": true, "vda.it": true, "ven.it": true, "veneto.it": true, "ag.it": true, "agrigento.it": true, "al.it": true, "alessandria.it": true, "alto-adige.it": true, "altoadige.it": true, "an.it": true, "ancona.it": true, "andria-barletta-trani.it": true, "andria-trani-barletta.it": true, "andriabarlettatrani.it": true, "andriatranibarletta.it": true, "ao.it": true, "aosta.it": true, "aoste.it": true, "ap.it": true, "aq.it": true, "aquila.it": true, "ar.it": true, "arezzo.it": true, "ascoli-piceno.it": true, "ascolipiceno.it": true, "asti.it": true, "at.it": true, "av.it": true, "avellino.it": true, "ba.it": true, "balsan.it": true, "bari.it": true, "barletta-trani-andria.it": true, "barlettatraniandria.it": true, "belluno.it": true, "benevento.it": true, "bergamo.it": true, "bg.it": true, "bi.it": true, "biella.it": true, "bl.it": true, "bn.it": true, "bo.it": true, "bologna.it": true, "bolzano.it": true, "bozen.it": true, "br.it": true, "brescia.it": true, "brindisi.it": true, "bs.it": true, "bt.it": true, "bz.it": true, "ca.it": true, "cagliari.it": true, "caltanissetta.it": true, "campidano-medio.it": true, "campidanomedio.it": true, "campobasso.it": true, "carbonia-iglesias.it": true, "carboniaiglesias.it": true, "carrara-massa.it": true, "carraramassa.it": true, "caserta.it": true, "catania.it": true, "catanzaro.it": true, "cb.it": true, "ce.it": true, "cesena-forli.it": true, "cesenaforli.it": true, "ch.it": true, "chieti.it": true, "ci.it": true, "cl.it": true, "cn.it": true, "co.it": true, "como.it": true, "cosenza.it": true, "cr.it": true, "cremona.it": true, "crotone.it": true, "cs.it": true, "ct.it": true, "cuneo.it": true, "cz.it": true, "dell-ogliastra.it": true, "dellogliastra.it": true, "en.it": true, "enna.it": true, "fc.it": true, "fe.it": true, "fermo.it": true, "ferrara.it": true, "fg.it": true, "fi.it": true, "firenze.it": true, "florence.it": true, "fm.it": true, "foggia.it": true, "forli-cesena.it": true, "forlicesena.it": true, "fr.it": true, "frosinone.it": true, "ge.it": true, "genoa.it": true, "genova.it": true, "go.it": true, "gorizia.it": true, "gr.it": true, "grosseto.it": true, "iglesias-carbonia.it": true, "iglesiascarbonia.it": true, "im.it": true, "imperia.it": true, "is.it": true, "isernia.it": true, "kr.it": true, "la-spezia.it": true, "laquila.it": true, "laspezia.it": true, "latina.it": true, "lc.it": true, "le.it": true, "lecce.it": true, "lecco.it": true, "li.it": true, "livorno.it": true, "lo.it": true, "lodi.it": true, "lt.it": true, "lu.it": true, "lucca.it": true, "macerata.it": true, "mantova.it": true, "massa-carrara.it": true, "massacarrara.it": true, "matera.it": true, "mb.it": true, "mc.it": true, "me.it": true, "medio-campidano.it": true, "mediocampidano.it": true, "messina.it": true, "mi.it": true, "milan.it": true, "milano.it": true, "mn.it": true, "mo.it": true, "modena.it": true, "monza-brianza.it": true, "monza-e-della-brianza.it": true, "monza.it": true, "monzabrianza.it": true, "monzaebrianza.it": true, "monzaedellabrianza.it": true, "ms.it": true, "mt.it": true, "na.it": true, "naples.it": true, "napoli.it": true, "no.it": true, "novara.it": true, "nu.it": true, "nuoro.it": true, "og.it": true, "ogliastra.it": true, "olbia-tempio.it": true, "olbiatempio.it": true, "or.it": true, "oristano.it": true, "ot.it": true, "pa.it": true, "padova.it": true, "padua.it": true, "palermo.it": true, "parma.it": true, "pavia.it": true, "pc.it": true, "pd.it": true, "pe.it": true, "perugia.it": true, "pesaro-urbino.it": true, "pesarourbino.it": true, "pescara.it": true, "pg.it": true, "pi.it": true, "piacenza.it": true, "pisa.it": true, "pistoia.it": true, "pn.it": true, "po.it": true, "pordenone.it": true, "potenza.it": true, "pr.it": true, "prato.it": true, "pt.it": true, "pu.it": true, "pv.it": true, "pz.it": true, "ra.it": true, "ragusa.it": true, "ravenna.it": true, "rc.it": true, "re.it": true, "reggio-calabria.it": true, "reggio-emilia.it": true, "reggiocalabria.it": true, "reggioemilia.it": true, "rg.it": true, "ri.it": true, "rieti.it": true, "rimini.it": true, "rm.it": true, "rn.it": true, "ro.it": true, "roma.it": true, "rome.it": true, "rovigo.it": true, "sa.it": true, "salerno.it": true, "sassari.it": true, "savona.it": true, "si.it": true, "siena.it": true, "siracusa.it": true, "so.it": true, "sondrio.it": true, "sp.it": true, "sr.it": true, "ss.it": true, "suedtirol.it": true, "sv.it": true, "ta.it": true, "taranto.it": true, "te.it": true, "tempio-olbia.it": true, "tempioolbia.it": true, "teramo.it": true, "terni.it": true, "tn.it": true, "to.it": true, "torino.it": true, "tp.it": true, "tr.it": true, "trani-andria-barletta.it": true, "trani-barletta-andria.it": true, "traniandriabarletta.it": true, "tranibarlettaandria.it": true, "trapani.it": true, "trentino.it": true, "trento.it": true, "treviso.it": true, "trieste.it": true, "ts.it": true, "turin.it": true, "tv.it": true, "ud.it": true, "udine.it": true, "urbino-pesaro.it": true, "urbinopesaro.it": true, "va.it": true, "varese.it": true, "vb.it": true, "vc.it": true, "ve.it": true, "venezia.it": true, "venice.it": true, "verbania.it": true, "vercelli.it": true, "verona.it": true, "vi.it": true, "vibo-valentia.it": true, "vibovalentia.it": true, "vicenza.it": true, "viterbo.it": true, "vr.it": true, "vs.it": true, "vt.it": true, "vv.it": true, "je": true, "co.je": true, "net.je": true, "org.je": true, "*.jm": true, "jo": true, "com.jo": true, "org.jo": true, "net.jo": true, "edu.jo": true, "sch.jo": true, "gov.jo": true, "mil.jo": true, "name.jo": true, "jobs": true, "jp": true, "ac.jp": true, "ad.jp": true, "co.jp": true, "ed.jp": true, "go.jp": true, "gr.jp": true, "lg.jp": true, "ne.jp": true, "or.jp": true, "aichi.jp": true, "akita.jp": true, "aomori.jp": true, "chiba.jp": true, "ehime.jp": true, "fukui.jp": true, "fukuoka.jp": true, "fukushima.jp": true, "gifu.jp": true, "gunma.jp": true, "hiroshima.jp": true, "hokkaido.jp": true, "hyogo.jp": true, "ibaraki.jp": true, "ishikawa.jp": true, "iwate.jp": true, "kagawa.jp": true, "kagoshima.jp": true, "kanagawa.jp": true, "kochi.jp": true, "kumamoto.jp": true, "kyoto.jp": true, "mie.jp": true, "miyagi.jp": true, "miyazaki.jp": true, "nagano.jp": true, "nagasaki.jp": true, "nara.jp": true, "niigata.jp": true, "oita.jp": true, "okayama.jp": true, "okinawa.jp": true, "osaka.jp": true, "saga.jp": true, "saitama.jp": true, "shiga.jp": true, "shimane.jp": true, "shizuoka.jp": true, "tochigi.jp": true, "tokushima.jp": true, "tokyo.jp": true, "tottori.jp": true, "toyama.jp": true, "wakayama.jp": true, "yamagata.jp": true, "yamaguchi.jp": true, "yamanashi.jp": true, "xn--4pvxs.jp": true, "xn--vgu402c.jp": true, "xn--c3s14m.jp": true, "xn--f6qx53a.jp": true, "xn--8pvr4u.jp": true, "xn--uist22h.jp": true, "xn--djrs72d6uy.jp": true, "xn--mkru45i.jp": true, "xn--0trq7p7nn.jp": true, "xn--8ltr62k.jp": true, "xn--2m4a15e.jp": true, "xn--efvn9s.jp": true, "xn--32vp30h.jp": true, "xn--4it797k.jp": true, "xn--1lqs71d.jp": true, "xn--5rtp49c.jp": true, "xn--5js045d.jp": true, "xn--ehqz56n.jp": true, "xn--1lqs03n.jp": true, "xn--qqqt11m.jp": true, "xn--kbrq7o.jp": true, "xn--pssu33l.jp": true, "xn--ntsq17g.jp": true, "xn--uisz3g.jp": true, "xn--6btw5a.jp": true, "xn--1ctwo.jp": true, "xn--6orx2r.jp": true, "xn--rht61e.jp": true, "xn--rht27z.jp": true, "xn--djty4k.jp": true, "xn--nit225k.jp": true, "xn--rht3d.jp": true, "xn--klty5x.jp": true, "xn--kltx9a.jp": true, "xn--kltp7d.jp": true, "xn--uuwu58a.jp": true, "xn--zbx025d.jp": true, "xn--ntso0iqx3a.jp": true, "xn--elqq16h.jp": true, "xn--4it168d.jp": true, "xn--klt787d.jp": true, "xn--rny31h.jp": true, "xn--7t0a264c.jp": true, "xn--5rtq34k.jp": true, "xn--k7yn95e.jp": true, "xn--tor131o.jp": true, "xn--d5qv7z876c.jp": true, "*.kawasaki.jp": true, "*.kitakyushu.jp": true, "*.kobe.jp": true, "*.nagoya.jp": true, "*.sapporo.jp": true, "*.sendai.jp": true, "*.yokohama.jp": true, "city.kawasaki.jp": false, "city.kitakyushu.jp": false, "city.kobe.jp": false, "city.nagoya.jp": false, "city.sapporo.jp": false, "city.sendai.jp": false, "city.yokohama.jp": false, "aisai.aichi.jp": true, "ama.aichi.jp": true, "anjo.aichi.jp": true, "asuke.aichi.jp": true, "chiryu.aichi.jp": true, "chita.aichi.jp": true, "fuso.aichi.jp": true, "gamagori.aichi.jp": true, "handa.aichi.jp": true, "hazu.aichi.jp": true, "hekinan.aichi.jp": true, "higashiura.aichi.jp": true, "ichinomiya.aichi.jp": true, "inazawa.aichi.jp": true, "inuyama.aichi.jp": true, "isshiki.aichi.jp": true, "iwakura.aichi.jp": true, "kanie.aichi.jp": true, "kariya.aichi.jp": true, "kasugai.aichi.jp": true, "kira.aichi.jp": true, "kiyosu.aichi.jp": true, "komaki.aichi.jp": true, "konan.aichi.jp": true, "kota.aichi.jp": true, "mihama.aichi.jp": true, "miyoshi.aichi.jp": true, "nishio.aichi.jp": true, "nisshin.aichi.jp": true, "obu.aichi.jp": true, "oguchi.aichi.jp": true, "oharu.aichi.jp": true, "okazaki.aichi.jp": true, "owariasahi.aichi.jp": true, "seto.aichi.jp": true, "shikatsu.aichi.jp": true, "shinshiro.aichi.jp": true, "shitara.aichi.jp": true, "tahara.aichi.jp": true, "takahama.aichi.jp": true, "tobishima.aichi.jp": true, "toei.aichi.jp": true, "togo.aichi.jp": true, "tokai.aichi.jp": true, "tokoname.aichi.jp": true, "toyoake.aichi.jp": true, "toyohashi.aichi.jp": true, "toyokawa.aichi.jp": true, "toyone.aichi.jp": true, "toyota.aichi.jp": true, "tsushima.aichi.jp": true, "yatomi.aichi.jp": true, "akita.akita.jp": true, "daisen.akita.jp": true, "fujisato.akita.jp": true, "gojome.akita.jp": true, "hachirogata.akita.jp": true, "happou.akita.jp": true, "higashinaruse.akita.jp": true, "honjo.akita.jp": true, "honjyo.akita.jp": true, "ikawa.akita.jp": true, "kamikoani.akita.jp": true, "kamioka.akita.jp": true, "katagami.akita.jp": true, "kazuno.akita.jp": true, "kitaakita.akita.jp": true, "kosaka.akita.jp": true, "kyowa.akita.jp": true, "misato.akita.jp": true, "mitane.akita.jp": true, "moriyoshi.akita.jp": true, "nikaho.akita.jp": true, "noshiro.akita.jp": true, "odate.akita.jp": true, "oga.akita.jp": true, "ogata.akita.jp": true, "semboku.akita.jp": true, "yokote.akita.jp": true, "yurihonjo.akita.jp": true, "aomori.aomori.jp": true, "gonohe.aomori.jp": true, "hachinohe.aomori.jp": true, "hashikami.aomori.jp": true, "hiranai.aomori.jp": true, "hirosaki.aomori.jp": true, "itayanagi.aomori.jp": true, "kuroishi.aomori.jp": true, "misawa.aomori.jp": true, "mutsu.aomori.jp": true, "nakadomari.aomori.jp": true, "noheji.aomori.jp": true, "oirase.aomori.jp": true, "owani.aomori.jp": true, "rokunohe.aomori.jp": true, "sannohe.aomori.jp": true, "shichinohe.aomori.jp": true, "shingo.aomori.jp": true, "takko.aomori.jp": true, "towada.aomori.jp": true, "tsugaru.aomori.jp": true, "tsuruta.aomori.jp": true, "abiko.chiba.jp": true, "asahi.chiba.jp": true, "chonan.chiba.jp": true, "chosei.chiba.jp": true, "choshi.chiba.jp": true, "chuo.chiba.jp": true, "funabashi.chiba.jp": true, "futtsu.chiba.jp": true, "hanamigawa.chiba.jp": true, "ichihara.chiba.jp": true, "ichikawa.chiba.jp": true, "ichinomiya.chiba.jp": true, "inzai.chiba.jp": true, "isumi.chiba.jp": true, "kamagaya.chiba.jp": true, "kamogawa.chiba.jp": true, "kashiwa.chiba.jp": true, "katori.chiba.jp": true, "katsuura.chiba.jp": true, "kimitsu.chiba.jp": true, "kisarazu.chiba.jp": true, "kozaki.chiba.jp": true, "kujukuri.chiba.jp": true, "kyonan.chiba.jp": true, "matsudo.chiba.jp": true, "midori.chiba.jp": true, "mihama.chiba.jp": true, "minamiboso.chiba.jp": true, "mobara.chiba.jp": true, "mutsuzawa.chiba.jp": true, "nagara.chiba.jp": true, "nagareyama.chiba.jp": true, "narashino.chiba.jp": true, "narita.chiba.jp": true, "noda.chiba.jp": true, "oamishirasato.chiba.jp": true, "omigawa.chiba.jp": true, "onjuku.chiba.jp": true, "otaki.chiba.jp": true, "sakae.chiba.jp": true, "sakura.chiba.jp": true, "shimofusa.chiba.jp": true, "shirako.chiba.jp": true, "shiroi.chiba.jp": true, "shisui.chiba.jp": true, "sodegaura.chiba.jp": true, "sosa.chiba.jp": true, "tako.chiba.jp": true, "tateyama.chiba.jp": true, "togane.chiba.jp": true, "tohnosho.chiba.jp": true, "tomisato.chiba.jp": true, "urayasu.chiba.jp": true, "yachimata.chiba.jp": true, "yachiyo.chiba.jp": true, "yokaichiba.chiba.jp": true, "yokoshibahikari.chiba.jp": true, "yotsukaido.chiba.jp": true, "ainan.ehime.jp": true, "honai.ehime.jp": true, "ikata.ehime.jp": true, "imabari.ehime.jp": true, "iyo.ehime.jp": true, "kamijima.ehime.jp": true, "kihoku.ehime.jp": true, "kumakogen.ehime.jp": true, "masaki.ehime.jp": true, "matsuno.ehime.jp": true, "matsuyama.ehime.jp": true, "namikata.ehime.jp": true, "niihama.ehime.jp": true, "ozu.ehime.jp": true, "saijo.ehime.jp": true, "seiyo.ehime.jp": true, "shikokuchuo.ehime.jp": true, "tobe.ehime.jp": true, "toon.ehime.jp": true, "uchiko.ehime.jp": true, "uwajima.ehime.jp": true, "yawatahama.ehime.jp": true, "echizen.fukui.jp": true, "eiheiji.fukui.jp": true, "fukui.fukui.jp": true, "ikeda.fukui.jp": true, "katsuyama.fukui.jp": true, "mihama.fukui.jp": true, "minamiechizen.fukui.jp": true, "obama.fukui.jp": true, "ohi.fukui.jp": true, "ono.fukui.jp": true, "sabae.fukui.jp": true, "sakai.fukui.jp": true, "takahama.fukui.jp": true, "tsuruga.fukui.jp": true, "wakasa.fukui.jp": true, "ashiya.fukuoka.jp": true, "buzen.fukuoka.jp": true, "chikugo.fukuoka.jp": true, "chikuho.fukuoka.jp": true, "chikujo.fukuoka.jp": true, "chikushino.fukuoka.jp": true, "chikuzen.fukuoka.jp": true, "chuo.fukuoka.jp": true, "dazaifu.fukuoka.jp": true, "fukuchi.fukuoka.jp": true, "hakata.fukuoka.jp": true, "higashi.fukuoka.jp": true, "hirokawa.fukuoka.jp": true, "hisayama.fukuoka.jp": true, "iizuka.fukuoka.jp": true, "inatsuki.fukuoka.jp": true, "kaho.fukuoka.jp": true, "kasuga.fukuoka.jp": true, "kasuya.fukuoka.jp": true, "kawara.fukuoka.jp": true, "keisen.fukuoka.jp": true, "koga.fukuoka.jp": true, "kurate.fukuoka.jp": true, "kurogi.fukuoka.jp": true, "kurume.fukuoka.jp": true, "minami.fukuoka.jp": true, "miyako.fukuoka.jp": true, "miyama.fukuoka.jp": true, "miyawaka.fukuoka.jp": true, "mizumaki.fukuoka.jp": true, "munakata.fukuoka.jp": true, "nakagawa.fukuoka.jp": true, "nakama.fukuoka.jp": true, "nishi.fukuoka.jp": true, "nogata.fukuoka.jp": true, "ogori.fukuoka.jp": true, "okagaki.fukuoka.jp": true, "okawa.fukuoka.jp": true, "oki.fukuoka.jp": true, "omuta.fukuoka.jp": true, "onga.fukuoka.jp": true, "onojo.fukuoka.jp": true, "oto.fukuoka.jp": true, "saigawa.fukuoka.jp": true, "sasaguri.fukuoka.jp": true, "shingu.fukuoka.jp": true, "shinyoshitomi.fukuoka.jp": true, "shonai.fukuoka.jp": true, "soeda.fukuoka.jp": true, "sue.fukuoka.jp": true, "tachiarai.fukuoka.jp": true, "tagawa.fukuoka.jp": true, "takata.fukuoka.jp": true, "toho.fukuoka.jp": true, "toyotsu.fukuoka.jp": true, "tsuiki.fukuoka.jp": true, "ukiha.fukuoka.jp": true, "umi.fukuoka.jp": true, "usui.fukuoka.jp": true, "yamada.fukuoka.jp": true, "yame.fukuoka.jp": true, "yanagawa.fukuoka.jp": true, "yukuhashi.fukuoka.jp": true, "aizubange.fukushima.jp": true, "aizumisato.fukushima.jp": true, "aizuwakamatsu.fukushima.jp": true, "asakawa.fukushima.jp": true, "bandai.fukushima.jp": true, "date.fukushima.jp": true, "fukushima.fukushima.jp": true, "furudono.fukushima.jp": true, "futaba.fukushima.jp": true, "hanawa.fukushima.jp": true, "higashi.fukushima.jp": true, "hirata.fukushima.jp": true, "hirono.fukushima.jp": true, "iitate.fukushima.jp": true, "inawashiro.fukushima.jp": true, "ishikawa.fukushima.jp": true, "iwaki.fukushima.jp": true, "izumizaki.fukushima.jp": true, "kagamiishi.fukushima.jp": true, "kaneyama.fukushima.jp": true, "kawamata.fukushima.jp": true, "kitakata.fukushima.jp": true, "kitashiobara.fukushima.jp": true, "koori.fukushima.jp": true, "koriyama.fukushima.jp": true, "kunimi.fukushima.jp": true, "miharu.fukushima.jp": true, "mishima.fukushima.jp": true, "namie.fukushima.jp": true, "nango.fukushima.jp": true, "nishiaizu.fukushima.jp": true, "nishigo.fukushima.jp": true, "okuma.fukushima.jp": true, "omotego.fukushima.jp": true, "ono.fukushima.jp": true, "otama.fukushima.jp": true, "samegawa.fukushima.jp": true, "shimogo.fukushima.jp": true, "shirakawa.fukushima.jp": true, "showa.fukushima.jp": true, "soma.fukushima.jp": true, "sukagawa.fukushima.jp": true, "taishin.fukushima.jp": true, "tamakawa.fukushima.jp": true, "tanagura.fukushima.jp": true, "tenei.fukushima.jp": true, "yabuki.fukushima.jp": true, "yamato.fukushima.jp": true, "yamatsuri.fukushima.jp": true, "yanaizu.fukushima.jp": true, "yugawa.fukushima.jp": true, "anpachi.gifu.jp": true, "ena.gifu.jp": true, "gifu.gifu.jp": true, "ginan.gifu.jp": true, "godo.gifu.jp": true, "gujo.gifu.jp": true, "hashima.gifu.jp": true, "hichiso.gifu.jp": true, "hida.gifu.jp": true, "higashishirakawa.gifu.jp": true, "ibigawa.gifu.jp": true, "ikeda.gifu.jp": true, "kakamigahara.gifu.jp": true, "kani.gifu.jp": true, "kasahara.gifu.jp": true, "kasamatsu.gifu.jp": true, "kawaue.gifu.jp": true, "kitagata.gifu.jp": true, "mino.gifu.jp": true, "minokamo.gifu.jp": true, "mitake.gifu.jp": true, "mizunami.gifu.jp": true, "motosu.gifu.jp": true, "nakatsugawa.gifu.jp": true, "ogaki.gifu.jp": true, "sakahogi.gifu.jp": true, "seki.gifu.jp": true, "sekigahara.gifu.jp": true, "shirakawa.gifu.jp": true, "tajimi.gifu.jp": true, "takayama.gifu.jp": true, "tarui.gifu.jp": true, "toki.gifu.jp": true, "tomika.gifu.jp": true, "wanouchi.gifu.jp": true, "yamagata.gifu.jp": true, "yaotsu.gifu.jp": true, "yoro.gifu.jp": true, "annaka.gunma.jp": true, "chiyoda.gunma.jp": true, "fujioka.gunma.jp": true, "higashiagatsuma.gunma.jp": true, "isesaki.gunma.jp": true, "itakura.gunma.jp": true, "kanna.gunma.jp": true, "kanra.gunma.jp": true, "katashina.gunma.jp": true, "kawaba.gunma.jp": true, "kiryu.gunma.jp": true, "kusatsu.gunma.jp": true, "maebashi.gunma.jp": true, "meiwa.gunma.jp": true, "midori.gunma.jp": true, "minakami.gunma.jp": true, "naganohara.gunma.jp": true, "nakanojo.gunma.jp": true, "nanmoku.gunma.jp": true, "numata.gunma.jp": true, "oizumi.gunma.jp": true, "ora.gunma.jp": true, "ota.gunma.jp": true, "shibukawa.gunma.jp": true, "shimonita.gunma.jp": true, "shinto.gunma.jp": true, "showa.gunma.jp": true, "takasaki.gunma.jp": true, "takayama.gunma.jp": true, "tamamura.gunma.jp": true, "tatebayashi.gunma.jp": true, "tomioka.gunma.jp": true, "tsukiyono.gunma.jp": true, "tsumagoi.gunma.jp": true, "ueno.gunma.jp": true, "yoshioka.gunma.jp": true, "asaminami.hiroshima.jp": true, "daiwa.hiroshima.jp": true, "etajima.hiroshima.jp": true, "fuchu.hiroshima.jp": true, "fukuyama.hiroshima.jp": true, "hatsukaichi.hiroshima.jp": true, "higashihiroshima.hiroshima.jp": true, "hongo.hiroshima.jp": true, "jinsekikogen.hiroshima.jp": true, "kaita.hiroshima.jp": true, "kui.hiroshima.jp": true, "kumano.hiroshima.jp": true, "kure.hiroshima.jp": true, "mihara.hiroshima.jp": true, "miyoshi.hiroshima.jp": true, "naka.hiroshima.jp": true, "onomichi.hiroshima.jp": true, "osakikamijima.hiroshima.jp": true, "otake.hiroshima.jp": true, "saka.hiroshima.jp": true, "sera.hiroshima.jp": true, "seranishi.hiroshima.jp": true, "shinichi.hiroshima.jp": true, "shobara.hiroshima.jp": true, "takehara.hiroshima.jp": true, "abashiri.hokkaido.jp": true, "abira.hokkaido.jp": true, "aibetsu.hokkaido.jp": true, "akabira.hokkaido.jp": true, "akkeshi.hokkaido.jp": true, "asahikawa.hokkaido.jp": true, "ashibetsu.hokkaido.jp": true, "ashoro.hokkaido.jp": true, "assabu.hokkaido.jp": true, "atsuma.hokkaido.jp": true, "bibai.hokkaido.jp": true, "biei.hokkaido.jp": true, "bifuka.hokkaido.jp": true, "bihoro.hokkaido.jp": true, "biratori.hokkaido.jp": true, "chippubetsu.hokkaido.jp": true, "chitose.hokkaido.jp": true, "date.hokkaido.jp": true, "ebetsu.hokkaido.jp": true, "embetsu.hokkaido.jp": true, "eniwa.hokkaido.jp": true, "erimo.hokkaido.jp": true, "esan.hokkaido.jp": true, "esashi.hokkaido.jp": true, "fukagawa.hokkaido.jp": true, "fukushima.hokkaido.jp": true, "furano.hokkaido.jp": true, "furubira.hokkaido.jp": true, "haboro.hokkaido.jp": true, "hakodate.hokkaido.jp": true, "hamatonbetsu.hokkaido.jp": true, "hidaka.hokkaido.jp": true, "higashikagura.hokkaido.jp": true, "higashikawa.hokkaido.jp": true, "hiroo.hokkaido.jp": true, "hokuryu.hokkaido.jp": true, "hokuto.hokkaido.jp": true, "honbetsu.hokkaido.jp": true, "horokanai.hokkaido.jp": true, "horonobe.hokkaido.jp": true, "ikeda.hokkaido.jp": true, "imakane.hokkaido.jp": true, "ishikari.hokkaido.jp": true, "iwamizawa.hokkaido.jp": true, "iwanai.hokkaido.jp": true, "kamifurano.hokkaido.jp": true, "kamikawa.hokkaido.jp": true, "kamishihoro.hokkaido.jp": true, "kamisunagawa.hokkaido.jp": true, "kamoenai.hokkaido.jp": true, "kayabe.hokkaido.jp": true, "kembuchi.hokkaido.jp": true, "kikonai.hokkaido.jp": true, "kimobetsu.hokkaido.jp": true, "kitahiroshima.hokkaido.jp": true, "kitami.hokkaido.jp": true, "kiyosato.hokkaido.jp": true, "koshimizu.hokkaido.jp": true, "kunneppu.hokkaido.jp": true, "kuriyama.hokkaido.jp": true, "kuromatsunai.hokkaido.jp": true, "kushiro.hokkaido.jp": true, "kutchan.hokkaido.jp": true, "kyowa.hokkaido.jp": true, "mashike.hokkaido.jp": true, "matsumae.hokkaido.jp": true, "mikasa.hokkaido.jp": true, "minamifurano.hokkaido.jp": true, "mombetsu.hokkaido.jp": true, "moseushi.hokkaido.jp": true, "mukawa.hokkaido.jp": true, "muroran.hokkaido.jp": true, "naie.hokkaido.jp": true, "nakagawa.hokkaido.jp": true, "nakasatsunai.hokkaido.jp": true, "nakatombetsu.hokkaido.jp": true, "nanae.hokkaido.jp": true, "nanporo.hokkaido.jp": true, "nayoro.hokkaido.jp": true, "nemuro.hokkaido.jp": true, "niikappu.hokkaido.jp": true, "niki.hokkaido.jp": true, "nishiokoppe.hokkaido.jp": true, "noboribetsu.hokkaido.jp": true, "numata.hokkaido.jp": true, "obihiro.hokkaido.jp": true, "obira.hokkaido.jp": true, "oketo.hokkaido.jp": true, "okoppe.hokkaido.jp": true, "otaru.hokkaido.jp": true, "otobe.hokkaido.jp": true, "otofuke.hokkaido.jp": true, "otoineppu.hokkaido.jp": true, "oumu.hokkaido.jp": true, "ozora.hokkaido.jp": true, "pippu.hokkaido.jp": true, "rankoshi.hokkaido.jp": true, "rebun.hokkaido.jp": true, "rikubetsu.hokkaido.jp": true, "rishiri.hokkaido.jp": true, "rishirifuji.hokkaido.jp": true, "saroma.hokkaido.jp": true, "sarufutsu.hokkaido.jp": true, "shakotan.hokkaido.jp": true, "shari.hokkaido.jp": true, "shibecha.hokkaido.jp": true, "shibetsu.hokkaido.jp": true, "shikabe.hokkaido.jp": true, "shikaoi.hokkaido.jp": true, "shimamaki.hokkaido.jp": true, "shimizu.hokkaido.jp": true, "shimokawa.hokkaido.jp": true, "shinshinotsu.hokkaido.jp": true, "shintoku.hokkaido.jp": true, "shiranuka.hokkaido.jp": true, "shiraoi.hokkaido.jp": true, "shiriuchi.hokkaido.jp": true, "sobetsu.hokkaido.jp": true, "sunagawa.hokkaido.jp": true, "taiki.hokkaido.jp": true, "takasu.hokkaido.jp": true, "takikawa.hokkaido.jp": true, "takinoue.hokkaido.jp": true, "teshikaga.hokkaido.jp": true, "tobetsu.hokkaido.jp": true, "tohma.hokkaido.jp": true, "tomakomai.hokkaido.jp": true, "tomari.hokkaido.jp": true, "toya.hokkaido.jp": true, "toyako.hokkaido.jp": true, "toyotomi.hokkaido.jp": true, "toyoura.hokkaido.jp": true, "tsubetsu.hokkaido.jp": true, "tsukigata.hokkaido.jp": true, "urakawa.hokkaido.jp": true, "urausu.hokkaido.jp": true, "uryu.hokkaido.jp": true, "utashinai.hokkaido.jp": true, "wakkanai.hokkaido.jp": true, "wassamu.hokkaido.jp": true, "yakumo.hokkaido.jp": true, "yoichi.hokkaido.jp": true, "aioi.hyogo.jp": true, "akashi.hyogo.jp": true, "ako.hyogo.jp": true, "amagasaki.hyogo.jp": true, "aogaki.hyogo.jp": true, "asago.hyogo.jp": true, "ashiya.hyogo.jp": true, "awaji.hyogo.jp": true, "fukusaki.hyogo.jp": true, "goshiki.hyogo.jp": true, "harima.hyogo.jp": true, "himeji.hyogo.jp": true, "ichikawa.hyogo.jp": true, "inagawa.hyogo.jp": true, "itami.hyogo.jp": true, "kakogawa.hyogo.jp": true, "kamigori.hyogo.jp": true, "kamikawa.hyogo.jp": true, "kasai.hyogo.jp": true, "kasuga.hyogo.jp": true, "kawanishi.hyogo.jp": true, "miki.hyogo.jp": true, "minamiawaji.hyogo.jp": true, "nishinomiya.hyogo.jp": true, "nishiwaki.hyogo.jp": true, "ono.hyogo.jp": true, "sanda.hyogo.jp": true, "sannan.hyogo.jp": true, "sasayama.hyogo.jp": true, "sayo.hyogo.jp": true, "shingu.hyogo.jp": true, "shinonsen.hyogo.jp": true, "shiso.hyogo.jp": true, "sumoto.hyogo.jp": true, "taishi.hyogo.jp": true, "taka.hyogo.jp": true, "takarazuka.hyogo.jp": true, "takasago.hyogo.jp": true, "takino.hyogo.jp": true, "tamba.hyogo.jp": true, "tatsuno.hyogo.jp": true, "toyooka.hyogo.jp": true, "yabu.hyogo.jp": true, "yashiro.hyogo.jp": true, "yoka.hyogo.jp": true, "yokawa.hyogo.jp": true, "ami.ibaraki.jp": true, "asahi.ibaraki.jp": true, "bando.ibaraki.jp": true, "chikusei.ibaraki.jp": true, "daigo.ibaraki.jp": true, "fujishiro.ibaraki.jp": true, "hitachi.ibaraki.jp": true, "hitachinaka.ibaraki.jp": true, "hitachiomiya.ibaraki.jp": true, "hitachiota.ibaraki.jp": true, "ibaraki.ibaraki.jp": true, "ina.ibaraki.jp": true, "inashiki.ibaraki.jp": true, "itako.ibaraki.jp": true, "iwama.ibaraki.jp": true, "joso.ibaraki.jp": true, "kamisu.ibaraki.jp": true, "kasama.ibaraki.jp": true, "kashima.ibaraki.jp": true, "kasumigaura.ibaraki.jp": true, "koga.ibaraki.jp": true, "miho.ibaraki.jp": true, "mito.ibaraki.jp": true, "moriya.ibaraki.jp": true, "naka.ibaraki.jp": true, "namegata.ibaraki.jp": true, "oarai.ibaraki.jp": true, "ogawa.ibaraki.jp": true, "omitama.ibaraki.jp": true, "ryugasaki.ibaraki.jp": true, "sakai.ibaraki.jp": true, "sakuragawa.ibaraki.jp": true, "shimodate.ibaraki.jp": true, "shimotsuma.ibaraki.jp": true, "shirosato.ibaraki.jp": true, "sowa.ibaraki.jp": true, "suifu.ibaraki.jp": true, "takahagi.ibaraki.jp": true, "tamatsukuri.ibaraki.jp": true, "tokai.ibaraki.jp": true, "tomobe.ibaraki.jp": true, "tone.ibaraki.jp": true, "toride.ibaraki.jp": true, "tsuchiura.ibaraki.jp": true, "tsukuba.ibaraki.jp": true, "uchihara.ibaraki.jp": true, "ushiku.ibaraki.jp": true, "yachiyo.ibaraki.jp": true, "yamagata.ibaraki.jp": true, "yawara.ibaraki.jp": true, "yuki.ibaraki.jp": true, "anamizu.ishikawa.jp": true, "hakui.ishikawa.jp": true, "hakusan.ishikawa.jp": true, "kaga.ishikawa.jp": true, "kahoku.ishikawa.jp": true, "kanazawa.ishikawa.jp": true, "kawakita.ishikawa.jp": true, "komatsu.ishikawa.jp": true, "nakanoto.ishikawa.jp": true, "nanao.ishikawa.jp": true, "nomi.ishikawa.jp": true, "nonoichi.ishikawa.jp": true, "noto.ishikawa.jp": true, "shika.ishikawa.jp": true, "suzu.ishikawa.jp": true, "tsubata.ishikawa.jp": true, "tsurugi.ishikawa.jp": true, "uchinada.ishikawa.jp": true, "wajima.ishikawa.jp": true, "fudai.iwate.jp": true, "fujisawa.iwate.jp": true, "hanamaki.iwate.jp": true, "hiraizumi.iwate.jp": true, "hirono.iwate.jp": true, "ichinohe.iwate.jp": true, "ichinoseki.iwate.jp": true, "iwaizumi.iwate.jp": true, "iwate.iwate.jp": true, "joboji.iwate.jp": true, "kamaishi.iwate.jp": true, "kanegasaki.iwate.jp": true, "karumai.iwate.jp": true, "kawai.iwate.jp": true, "kitakami.iwate.jp": true, "kuji.iwate.jp": true, "kunohe.iwate.jp": true, "kuzumaki.iwate.jp": true, "miyako.iwate.jp": true, "mizusawa.iwate.jp": true, "morioka.iwate.jp": true, "ninohe.iwate.jp": true, "noda.iwate.jp": true, "ofunato.iwate.jp": true, "oshu.iwate.jp": true, "otsuchi.iwate.jp": true, "rikuzentakata.iwate.jp": true, "shiwa.iwate.jp": true, "shizukuishi.iwate.jp": true, "sumita.iwate.jp": true, "tanohata.iwate.jp": true, "tono.iwate.jp": true, "yahaba.iwate.jp": true, "yamada.iwate.jp": true, "ayagawa.kagawa.jp": true, "higashikagawa.kagawa.jp": true, "kanonji.kagawa.jp": true, "kotohira.kagawa.jp": true, "manno.kagawa.jp": true, "marugame.kagawa.jp": true, "mitoyo.kagawa.jp": true, "naoshima.kagawa.jp": true, "sanuki.kagawa.jp": true, "tadotsu.kagawa.jp": true, "takamatsu.kagawa.jp": true, "tonosho.kagawa.jp": true, "uchinomi.kagawa.jp": true, "utazu.kagawa.jp": true, "zentsuji.kagawa.jp": true, "akune.kagoshima.jp": true, "amami.kagoshima.jp": true, "hioki.kagoshima.jp": true, "isa.kagoshima.jp": true, "isen.kagoshima.jp": true, "izumi.kagoshima.jp": true, "kagoshima.kagoshima.jp": true, "kanoya.kagoshima.jp": true, "kawanabe.kagoshima.jp": true, "kinko.kagoshima.jp": true, "kouyama.kagoshima.jp": true, "makurazaki.kagoshima.jp": true, "matsumoto.kagoshima.jp": true, "minamitane.kagoshima.jp": true, "nakatane.kagoshima.jp": true, "nishinoomote.kagoshima.jp": true, "satsumasendai.kagoshima.jp": true, "soo.kagoshima.jp": true, "tarumizu.kagoshima.jp": true, "yusui.kagoshima.jp": true, "aikawa.kanagawa.jp": true, "atsugi.kanagawa.jp": true, "ayase.kanagawa.jp": true, "chigasaki.kanagawa.jp": true, "ebina.kanagawa.jp": true, "fujisawa.kanagawa.jp": true, "hadano.kanagawa.jp": true, "hakone.kanagawa.jp": true, "hiratsuka.kanagawa.jp": true, "isehara.kanagawa.jp": true, "kaisei.kanagawa.jp": true, "kamakura.kanagawa.jp": true, "kiyokawa.kanagawa.jp": true, "matsuda.kanagawa.jp": true, "minamiashigara.kanagawa.jp": true, "miura.kanagawa.jp": true, "nakai.kanagawa.jp": true, "ninomiya.kanagawa.jp": true, "odawara.kanagawa.jp": true, "oi.kanagawa.jp": true, "oiso.kanagawa.jp": true, "sagamihara.kanagawa.jp": true, "samukawa.kanagawa.jp": true, "tsukui.kanagawa.jp": true, "yamakita.kanagawa.jp": true, "yamato.kanagawa.jp": true, "yokosuka.kanagawa.jp": true, "yugawara.kanagawa.jp": true, "zama.kanagawa.jp": true, "zushi.kanagawa.jp": true, "aki.kochi.jp": true, "geisei.kochi.jp": true, "hidaka.kochi.jp": true, "higashitsuno.kochi.jp": true, "ino.kochi.jp": true, "kagami.kochi.jp": true, "kami.kochi.jp": true, "kitagawa.kochi.jp": true, "kochi.kochi.jp": true, "mihara.kochi.jp": true, "motoyama.kochi.jp": true, "muroto.kochi.jp": true, "nahari.kochi.jp": true, "nakamura.kochi.jp": true, "nankoku.kochi.jp": true, "nishitosa.kochi.jp": true, "niyodogawa.kochi.jp": true, "ochi.kochi.jp": true, "okawa.kochi.jp": true, "otoyo.kochi.jp": true, "otsuki.kochi.jp": true, "sakawa.kochi.jp": true, "sukumo.kochi.jp": true, "susaki.kochi.jp": true, "tosa.kochi.jp": true, "tosashimizu.kochi.jp": true, "toyo.kochi.jp": true, "tsuno.kochi.jp": true, "umaji.kochi.jp": true, "yasuda.kochi.jp": true, "yusuhara.kochi.jp": true, "amakusa.kumamoto.jp": true, "arao.kumamoto.jp": true, "aso.kumamoto.jp": true, "choyo.kumamoto.jp": true, "gyokuto.kumamoto.jp": true, "kamiamakusa.kumamoto.jp": true, "kikuchi.kumamoto.jp": true, "kumamoto.kumamoto.jp": true, "mashiki.kumamoto.jp": true, "mifune.kumamoto.jp": true, "minamata.kumamoto.jp": true, "minamioguni.kumamoto.jp": true, "nagasu.kumamoto.jp": true, "nishihara.kumamoto.jp": true, "oguni.kumamoto.jp": true, "ozu.kumamoto.jp": true, "sumoto.kumamoto.jp": true, "takamori.kumamoto.jp": true, "uki.kumamoto.jp": true, "uto.kumamoto.jp": true, "yamaga.kumamoto.jp": true, "yamato.kumamoto.jp": true, "yatsushiro.kumamoto.jp": true, "ayabe.kyoto.jp": true, "fukuchiyama.kyoto.jp": true, "higashiyama.kyoto.jp": true, "ide.kyoto.jp": true, "ine.kyoto.jp": true, "joyo.kyoto.jp": true, "kameoka.kyoto.jp": true, "kamo.kyoto.jp": true, "kita.kyoto.jp": true, "kizu.kyoto.jp": true, "kumiyama.kyoto.jp": true, "kyotamba.kyoto.jp": true, "kyotanabe.kyoto.jp": true, "kyotango.kyoto.jp": true, "maizuru.kyoto.jp": true, "minami.kyoto.jp": true, "minamiyamashiro.kyoto.jp": true, "miyazu.kyoto.jp": true, "muko.kyoto.jp": true, "nagaokakyo.kyoto.jp": true, "nakagyo.kyoto.jp": true, "nantan.kyoto.jp": true, "oyamazaki.kyoto.jp": true, "sakyo.kyoto.jp": true, "seika.kyoto.jp": true, "tanabe.kyoto.jp": true, "uji.kyoto.jp": true, "ujitawara.kyoto.jp": true, "wazuka.kyoto.jp": true, "yamashina.kyoto.jp": true, "yawata.kyoto.jp": true, "asahi.mie.jp": true, "inabe.mie.jp": true, "ise.mie.jp": true, "kameyama.mie.jp": true, "kawagoe.mie.jp": true, "kiho.mie.jp": true, "kisosaki.mie.jp": true, "kiwa.mie.jp": true, "komono.mie.jp": true, "kumano.mie.jp": true, "kuwana.mie.jp": true, "matsusaka.mie.jp": true, "meiwa.mie.jp": true, "mihama.mie.jp": true, "minamiise.mie.jp": true, "misugi.mie.jp": true, "miyama.mie.jp": true, "nabari.mie.jp": true, "shima.mie.jp": true, "suzuka.mie.jp": true, "tado.mie.jp": true, "taiki.mie.jp": true, "taki.mie.jp": true, "tamaki.mie.jp": true, "toba.mie.jp": true, "tsu.mie.jp": true, "udono.mie.jp": true, "ureshino.mie.jp": true, "watarai.mie.jp": true, "yokkaichi.mie.jp": true, "furukawa.miyagi.jp": true, "higashimatsushima.miyagi.jp": true, "ishinomaki.miyagi.jp": true, "iwanuma.miyagi.jp": true, "kakuda.miyagi.jp": true, "kami.miyagi.jp": true, "kawasaki.miyagi.jp": true, "marumori.miyagi.jp": true, "matsushima.miyagi.jp": true, "minamisanriku.miyagi.jp": true, "misato.miyagi.jp": true, "murata.miyagi.jp": true, "natori.miyagi.jp": true, "ogawara.miyagi.jp": true, "ohira.miyagi.jp": true, "onagawa.miyagi.jp": true, "osaki.miyagi.jp": true, "rifu.miyagi.jp": true, "semine.miyagi.jp": true, "shibata.miyagi.jp": true, "shichikashuku.miyagi.jp": true, "shikama.miyagi.jp": true, "shiogama.miyagi.jp": true, "shiroishi.miyagi.jp": true, "tagajo.miyagi.jp": true, "taiwa.miyagi.jp": true, "tome.miyagi.jp": true, "tomiya.miyagi.jp": true, "wakuya.miyagi.jp": true, "watari.miyagi.jp": true, "yamamoto.miyagi.jp": true, "zao.miyagi.jp": true, "aya.miyazaki.jp": true, "ebino.miyazaki.jp": true, "gokase.miyazaki.jp": true, "hyuga.miyazaki.jp": true, "kadogawa.miyazaki.jp": true, "kawaminami.miyazaki.jp": true, "kijo.miyazaki.jp": true, "kitagawa.miyazaki.jp": true, "kitakata.miyazaki.jp": true, "kitaura.miyazaki.jp": true, "kobayashi.miyazaki.jp": true, "kunitomi.miyazaki.jp": true, "kushima.miyazaki.jp": true, "mimata.miyazaki.jp": true, "miyakonojo.miyazaki.jp": true, "miyazaki.miyazaki.jp": true, "morotsuka.miyazaki.jp": true, "nichinan.miyazaki.jp": true, "nishimera.miyazaki.jp": true, "nobeoka.miyazaki.jp": true, "saito.miyazaki.jp": true, "shiiba.miyazaki.jp": true, "shintomi.miyazaki.jp": true, "takaharu.miyazaki.jp": true, "takanabe.miyazaki.jp": true, "takazaki.miyazaki.jp": true, "tsuno.miyazaki.jp": true, "achi.nagano.jp": true, "agematsu.nagano.jp": true, "anan.nagano.jp": true, "aoki.nagano.jp": true, "asahi.nagano.jp": true, "azumino.nagano.jp": true, "chikuhoku.nagano.jp": true, "chikuma.nagano.jp": true, "chino.nagano.jp": true, "fujimi.nagano.jp": true, "hakuba.nagano.jp": true, "hara.nagano.jp": true, "hiraya.nagano.jp": true, "iida.nagano.jp": true, "iijima.nagano.jp": true, "iiyama.nagano.jp": true, "iizuna.nagano.jp": true, "ikeda.nagano.jp": true, "ikusaka.nagano.jp": true, "ina.nagano.jp": true, "karuizawa.nagano.jp": true, "kawakami.nagano.jp": true, "kiso.nagano.jp": true, "kisofukushima.nagano.jp": true, "kitaaiki.nagano.jp": true, "komagane.nagano.jp": true, "komoro.nagano.jp": true, "matsukawa.nagano.jp": true, "matsumoto.nagano.jp": true, "miasa.nagano.jp": true, "minamiaiki.nagano.jp": true, "minamimaki.nagano.jp": true, "minamiminowa.nagano.jp": true, "minowa.nagano.jp": true, "miyada.nagano.jp": true, "miyota.nagano.jp": true, "mochizuki.nagano.jp": true, "nagano.nagano.jp": true, "nagawa.nagano.jp": true, "nagiso.nagano.jp": true, "nakagawa.nagano.jp": true, "nakano.nagano.jp": true, "nozawaonsen.nagano.jp": true, "obuse.nagano.jp": true, "ogawa.nagano.jp": true, "okaya.nagano.jp": true, "omachi.nagano.jp": true, "omi.nagano.jp": true, "ookuwa.nagano.jp": true, "ooshika.nagano.jp": true, "otaki.nagano.jp": true, "otari.nagano.jp": true, "sakae.nagano.jp": true, "sakaki.nagano.jp": true, "saku.nagano.jp": true, "sakuho.nagano.jp": true, "shimosuwa.nagano.jp": true, "shinanomachi.nagano.jp": true, "shiojiri.nagano.jp": true, "suwa.nagano.jp": true, "suzaka.nagano.jp": true, "takagi.nagano.jp": true, "takamori.nagano.jp": true, "takayama.nagano.jp": true, "tateshina.nagano.jp": true, "tatsuno.nagano.jp": true, "togakushi.nagano.jp": true, "togura.nagano.jp": true, "tomi.nagano.jp": true, "ueda.nagano.jp": true, "wada.nagano.jp": true, "yamagata.nagano.jp": true, "yamanouchi.nagano.jp": true, "yasaka.nagano.jp": true, "yasuoka.nagano.jp": true, "chijiwa.nagasaki.jp": true, "futsu.nagasaki.jp": true, "goto.nagasaki.jp": true, "hasami.nagasaki.jp": true, "hirado.nagasaki.jp": true, "iki.nagasaki.jp": true, "isahaya.nagasaki.jp": true, "kawatana.nagasaki.jp": true, "kuchinotsu.nagasaki.jp": true, "matsuura.nagasaki.jp": true, "nagasaki.nagasaki.jp": true, "obama.nagasaki.jp": true, "omura.nagasaki.jp": true, "oseto.nagasaki.jp": true, "saikai.nagasaki.jp": true, "sasebo.nagasaki.jp": true, "seihi.nagasaki.jp": true, "shimabara.nagasaki.jp": true, "shinkamigoto.nagasaki.jp": true, "togitsu.nagasaki.jp": true, "tsushima.nagasaki.jp": true, "unzen.nagasaki.jp": true, "ando.nara.jp": true, "gose.nara.jp": true, "heguri.nara.jp": true, "higashiyoshino.nara.jp": true, "ikaruga.nara.jp": true, "ikoma.nara.jp": true, "kamikitayama.nara.jp": true, "kanmaki.nara.jp": true, "kashiba.nara.jp": true, "kashihara.nara.jp": true, "katsuragi.nara.jp": true, "kawai.nara.jp": true, "kawakami.nara.jp": true, "kawanishi.nara.jp": true, "koryo.nara.jp": true, "kurotaki.nara.jp": true, "mitsue.nara.jp": true, "miyake.nara.jp": true, "nara.nara.jp": true, "nosegawa.nara.jp": true, "oji.nara.jp": true, "ouda.nara.jp": true, "oyodo.nara.jp": true, "sakurai.nara.jp": true, "sango.nara.jp": true, "shimoichi.nara.jp": true, "shimokitayama.nara.jp": true, "shinjo.nara.jp": true, "soni.nara.jp": true, "takatori.nara.jp": true, "tawaramoto.nara.jp": true, "tenkawa.nara.jp": true, "tenri.nara.jp": true, "uda.nara.jp": true, "yamatokoriyama.nara.jp": true, "yamatotakada.nara.jp": true, "yamazoe.nara.jp": true, "yoshino.nara.jp": true, "aga.niigata.jp": true, "agano.niigata.jp": true, "gosen.niigata.jp": true, "itoigawa.niigata.jp": true, "izumozaki.niigata.jp": true, "joetsu.niigata.jp": true, "kamo.niigata.jp": true, "kariwa.niigata.jp": true, "kashiwazaki.niigata.jp": true, "minamiuonuma.niigata.jp": true, "mitsuke.niigata.jp": true, "muika.niigata.jp": true, "murakami.niigata.jp": true, "myoko.niigata.jp": true, "nagaoka.niigata.jp": true, "niigata.niigata.jp": true, "ojiya.niigata.jp": true, "omi.niigata.jp": true, "sado.niigata.jp": true, "sanjo.niigata.jp": true, "seiro.niigata.jp": true, "seirou.niigata.jp": true, "sekikawa.niigata.jp": true, "shibata.niigata.jp": true, "tagami.niigata.jp": true, "tainai.niigata.jp": true, "tochio.niigata.jp": true, "tokamachi.niigata.jp": true, "tsubame.niigata.jp": true, "tsunan.niigata.jp": true, "uonuma.niigata.jp": true, "yahiko.niigata.jp": true, "yoita.niigata.jp": true, "yuzawa.niigata.jp": true, "beppu.oita.jp": true, "bungoono.oita.jp": true, "bungotakada.oita.jp": true, "hasama.oita.jp": true, "hiji.oita.jp": true, "himeshima.oita.jp": true, "hita.oita.jp": true, "kamitsue.oita.jp": true, "kokonoe.oita.jp": true, "kuju.oita.jp": true, "kunisaki.oita.jp": true, "kusu.oita.jp": true, "oita.oita.jp": true, "saiki.oita.jp": true, "taketa.oita.jp": true, "tsukumi.oita.jp": true, "usa.oita.jp": true, "usuki.oita.jp": true, "yufu.oita.jp": true, "akaiwa.okayama.jp": true, "asakuchi.okayama.jp": true, "bizen.okayama.jp": true, "hayashima.okayama.jp": true, "ibara.okayama.jp": true, "kagamino.okayama.jp": true, "kasaoka.okayama.jp": true, "kibichuo.okayama.jp": true, "kumenan.okayama.jp": true, "kurashiki.okayama.jp": true, "maniwa.okayama.jp": true, "misaki.okayama.jp": true, "nagi.okayama.jp": true, "niimi.okayama.jp": true, "nishiawakura.okayama.jp": true, "okayama.okayama.jp": true, "satosho.okayama.jp": true, "setouchi.okayama.jp": true, "shinjo.okayama.jp": true, "shoo.okayama.jp": true, "soja.okayama.jp": true, "takahashi.okayama.jp": true, "tamano.okayama.jp": true, "tsuyama.okayama.jp": true, "wake.okayama.jp": true, "yakage.okayama.jp": true, "aguni.okinawa.jp": true, "ginowan.okinawa.jp": true, "ginoza.okinawa.jp": true, "gushikami.okinawa.jp": true, "haebaru.okinawa.jp": true, "higashi.okinawa.jp": true, "hirara.okinawa.jp": true, "iheya.okinawa.jp": true, "ishigaki.okinawa.jp": true, "ishikawa.okinawa.jp": true, "itoman.okinawa.jp": true, "izena.okinawa.jp": true, "kadena.okinawa.jp": true, "kin.okinawa.jp": true, "kitadaito.okinawa.jp": true, "kitanakagusuku.okinawa.jp": true, "kumejima.okinawa.jp": true, "kunigami.okinawa.jp": true, "minamidaito.okinawa.jp": true, "motobu.okinawa.jp": true, "nago.okinawa.jp": true, "naha.okinawa.jp": true, "nakagusuku.okinawa.jp": true, "nakijin.okinawa.jp": true, "nanjo.okinawa.jp": true, "nishihara.okinawa.jp": true, "ogimi.okinawa.jp": true, "okinawa.okinawa.jp": true, "onna.okinawa.jp": true, "shimoji.okinawa.jp": true, "taketomi.okinawa.jp": true, "tarama.okinawa.jp": true, "tokashiki.okinawa.jp": true, "tomigusuku.okinawa.jp": true, "tonaki.okinawa.jp": true, "urasoe.okinawa.jp": true, "uruma.okinawa.jp": true, "yaese.okinawa.jp": true, "yomitan.okinawa.jp": true, "yonabaru.okinawa.jp": true, "yonaguni.okinawa.jp": true, "zamami.okinawa.jp": true, "abeno.osaka.jp": true, "chihayaakasaka.osaka.jp": true, "chuo.osaka.jp": true, "daito.osaka.jp": true, "fujiidera.osaka.jp": true, "habikino.osaka.jp": true, "hannan.osaka.jp": true, "higashiosaka.osaka.jp": true, "higashisumiyoshi.osaka.jp": true, "higashiyodogawa.osaka.jp": true, "hirakata.osaka.jp": true, "ibaraki.osaka.jp": true, "ikeda.osaka.jp": true, "izumi.osaka.jp": true, "izumiotsu.osaka.jp": true, "izumisano.osaka.jp": true, "kadoma.osaka.jp": true, "kaizuka.osaka.jp": true, "kanan.osaka.jp": true, "kashiwara.osaka.jp": true, "katano.osaka.jp": true, "kawachinagano.osaka.jp": true, "kishiwada.osaka.jp": true, "kita.osaka.jp": true, "kumatori.osaka.jp": true, "matsubara.osaka.jp": true, "minato.osaka.jp": true, "minoh.osaka.jp": true, "misaki.osaka.jp": true, "moriguchi.osaka.jp": true, "neyagawa.osaka.jp": true, "nishi.osaka.jp": true, "nose.osaka.jp": true, "osakasayama.osaka.jp": true, "sakai.osaka.jp": true, "sayama.osaka.jp": true, "sennan.osaka.jp": true, "settsu.osaka.jp": true, "shijonawate.osaka.jp": true, "shimamoto.osaka.jp": true, "suita.osaka.jp": true, "tadaoka.osaka.jp": true, "taishi.osaka.jp": true, "tajiri.osaka.jp": true, "takaishi.osaka.jp": true, "takatsuki.osaka.jp": true, "tondabayashi.osaka.jp": true, "toyonaka.osaka.jp": true, "toyono.osaka.jp": true, "yao.osaka.jp": true, "ariake.saga.jp": true, "arita.saga.jp": true, "fukudomi.saga.jp": true, "genkai.saga.jp": true, "hamatama.saga.jp": true, "hizen.saga.jp": true, "imari.saga.jp": true, "kamimine.saga.jp": true, "kanzaki.saga.jp": true, "karatsu.saga.jp": true, "kashima.saga.jp": true, "kitagata.saga.jp": true, "kitahata.saga.jp": true, "kiyama.saga.jp": true, "kouhoku.saga.jp": true, "kyuragi.saga.jp": true, "nishiarita.saga.jp": true, "ogi.saga.jp": true, "omachi.saga.jp": true, "ouchi.saga.jp": true, "saga.saga.jp": true, "shiroishi.saga.jp": true, "taku.saga.jp": true, "tara.saga.jp": true, "tosu.saga.jp": true, "yoshinogari.saga.jp": true, "arakawa.saitama.jp": true, "asaka.saitama.jp": true, "chichibu.saitama.jp": true, "fujimi.saitama.jp": true, "fujimino.saitama.jp": true, "fukaya.saitama.jp": true, "hanno.saitama.jp": true, "hanyu.saitama.jp": true, "hasuda.saitama.jp": true, "hatogaya.saitama.jp": true, "hatoyama.saitama.jp": true, "hidaka.saitama.jp": true, "higashichichibu.saitama.jp": true, "higashimatsuyama.saitama.jp": true, "honjo.saitama.jp": true, "ina.saitama.jp": true, "iruma.saitama.jp": true, "iwatsuki.saitama.jp": true, "kamiizumi.saitama.jp": true, "kamikawa.saitama.jp": true, "kamisato.saitama.jp": true, "kasukabe.saitama.jp": true, "kawagoe.saitama.jp": true, "kawaguchi.saitama.jp": true, "kawajima.saitama.jp": true, "kazo.saitama.jp": true, "kitamoto.saitama.jp": true, "koshigaya.saitama.jp": true, "kounosu.saitama.jp": true, "kuki.saitama.jp": true, "kumagaya.saitama.jp": true, "matsubushi.saitama.jp": true, "minano.saitama.jp": true, "misato.saitama.jp": true, "miyashiro.saitama.jp": true, "miyoshi.saitama.jp": true, "moroyama.saitama.jp": true, "nagatoro.saitama.jp": true, "namegawa.saitama.jp": true, "niiza.saitama.jp": true, "ogano.saitama.jp": true, "ogawa.saitama.jp": true, "ogose.saitama.jp": true, "okegawa.saitama.jp": true, "omiya.saitama.jp": true, "otaki.saitama.jp": true, "ranzan.saitama.jp": true, "ryokami.saitama.jp": true, "saitama.saitama.jp": true, "sakado.saitama.jp": true, "satte.saitama.jp": true, "sayama.saitama.jp": true, "shiki.saitama.jp": true, "shiraoka.saitama.jp": true, "soka.saitama.jp": true, "sugito.saitama.jp": true, "toda.saitama.jp": true, "tokigawa.saitama.jp": true, "tokorozawa.saitama.jp": true, "tsurugashima.saitama.jp": true, "urawa.saitama.jp": true, "warabi.saitama.jp": true, "yashio.saitama.jp": true, "yokoze.saitama.jp": true, "yono.saitama.jp": true, "yorii.saitama.jp": true, "yoshida.saitama.jp": true, "yoshikawa.saitama.jp": true, "yoshimi.saitama.jp": true, "aisho.shiga.jp": true, "gamo.shiga.jp": true, "higashiomi.shiga.jp": true, "hikone.shiga.jp": true, "koka.shiga.jp": true, "konan.shiga.jp": true, "kosei.shiga.jp": true, "koto.shiga.jp": true, "kusatsu.shiga.jp": true, "maibara.shiga.jp": true, "moriyama.shiga.jp": true, "nagahama.shiga.jp": true, "nishiazai.shiga.jp": true, "notogawa.shiga.jp": true, "omihachiman.shiga.jp": true, "otsu.shiga.jp": true, "ritto.shiga.jp": true, "ryuoh.shiga.jp": true, "takashima.shiga.jp": true, "takatsuki.shiga.jp": true, "torahime.shiga.jp": true, "toyosato.shiga.jp": true, "yasu.shiga.jp": true, "akagi.shimane.jp": true, "ama.shimane.jp": true, "gotsu.shimane.jp": true, "hamada.shimane.jp": true, "higashiizumo.shimane.jp": true, "hikawa.shimane.jp": true, "hikimi.shimane.jp": true, "izumo.shimane.jp": true, "kakinoki.shimane.jp": true, "masuda.shimane.jp": true, "matsue.shimane.jp": true, "misato.shimane.jp": true, "nishinoshima.shimane.jp": true, "ohda.shimane.jp": true, "okinoshima.shimane.jp": true, "okuizumo.shimane.jp": true, "shimane.shimane.jp": true, "tamayu.shimane.jp": true, "tsuwano.shimane.jp": true, "unnan.shimane.jp": true, "yakumo.shimane.jp": true, "yasugi.shimane.jp": true, "yatsuka.shimane.jp": true, "arai.shizuoka.jp": true, "atami.shizuoka.jp": true, "fuji.shizuoka.jp": true, "fujieda.shizuoka.jp": true, "fujikawa.shizuoka.jp": true, "fujinomiya.shizuoka.jp": true, "fukuroi.shizuoka.jp": true, "gotemba.shizuoka.jp": true, "haibara.shizuoka.jp": true, "hamamatsu.shizuoka.jp": true, "higashiizu.shizuoka.jp": true, "ito.shizuoka.jp": true, "iwata.shizuoka.jp": true, "izu.shizuoka.jp": true, "izunokuni.shizuoka.jp": true, "kakegawa.shizuoka.jp": true, "kannami.shizuoka.jp": true, "kawanehon.shizuoka.jp": true, "kawazu.shizuoka.jp": true, "kikugawa.shizuoka.jp": true, "kosai.shizuoka.jp": true, "makinohara.shizuoka.jp": true, "matsuzaki.shizuoka.jp": true, "minamiizu.shizuoka.jp": true, "mishima.shizuoka.jp": true, "morimachi.shizuoka.jp": true, "nishiizu.shizuoka.jp": true, "numazu.shizuoka.jp": true, "omaezaki.shizuoka.jp": true, "shimada.shizuoka.jp": true, "shimizu.shizuoka.jp": true, "shimoda.shizuoka.jp": true, "shizuoka.shizuoka.jp": true, "susono.shizuoka.jp": true, "yaizu.shizuoka.jp": true, "yoshida.shizuoka.jp": true, "ashikaga.tochigi.jp": true, "bato.tochigi.jp": true, "haga.tochigi.jp": true, "ichikai.tochigi.jp": true, "iwafune.tochigi.jp": true, "kaminokawa.tochigi.jp": true, "kanuma.tochigi.jp": true, "karasuyama.tochigi.jp": true, "kuroiso.tochigi.jp": true, "mashiko.tochigi.jp": true, "mibu.tochigi.jp": true, "moka.tochigi.jp": true, "motegi.tochigi.jp": true, "nasu.tochigi.jp": true, "nasushiobara.tochigi.jp": true, "nikko.tochigi.jp": true, "nishikata.tochigi.jp": true, "nogi.tochigi.jp": true, "ohira.tochigi.jp": true, "ohtawara.tochigi.jp": true, "oyama.tochigi.jp": true, "sakura.tochigi.jp": true, "sano.tochigi.jp": true, "shimotsuke.tochigi.jp": true, "shioya.tochigi.jp": true, "takanezawa.tochigi.jp": true, "tochigi.tochigi.jp": true, "tsuga.tochigi.jp": true, "ujiie.tochigi.jp": true, "utsunomiya.tochigi.jp": true, "yaita.tochigi.jp": true, "aizumi.tokushima.jp": true, "anan.tokushima.jp": true, "ichiba.tokushima.jp": true, "itano.tokushima.jp": true, "kainan.tokushima.jp": true, "komatsushima.tokushima.jp": true, "matsushige.tokushima.jp": true, "mima.tokushima.jp": true, "minami.tokushima.jp": true, "miyoshi.tokushima.jp": true, "mugi.tokushima.jp": true, "nakagawa.tokushima.jp": true, "naruto.tokushima.jp": true, "sanagochi.tokushima.jp": true, "shishikui.tokushima.jp": true, "tokushima.tokushima.jp": true, "wajiki.tokushima.jp": true, "adachi.tokyo.jp": true, "akiruno.tokyo.jp": true, "akishima.tokyo.jp": true, "aogashima.tokyo.jp": true, "arakawa.tokyo.jp": true, "bunkyo.tokyo.jp": true, "chiyoda.tokyo.jp": true, "chofu.tokyo.jp": true, "chuo.tokyo.jp": true, "edogawa.tokyo.jp": true, "fuchu.tokyo.jp": true, "fussa.tokyo.jp": true, "hachijo.tokyo.jp": true, "hachioji.tokyo.jp": true, "hamura.tokyo.jp": true, "higashikurume.tokyo.jp": true, "higashimurayama.tokyo.jp": true, "higashiyamato.tokyo.jp": true, "hino.tokyo.jp": true, "hinode.tokyo.jp": true, "hinohara.tokyo.jp": true, "inagi.tokyo.jp": true, "itabashi.tokyo.jp": true, "katsushika.tokyo.jp": true, "kita.tokyo.jp": true, "kiyose.tokyo.jp": true, "kodaira.tokyo.jp": true, "koganei.tokyo.jp": true, "kokubunji.tokyo.jp": true, "komae.tokyo.jp": true, "koto.tokyo.jp": true, "kouzushima.tokyo.jp": true, "kunitachi.tokyo.jp": true, "machida.tokyo.jp": true, "meguro.tokyo.jp": true, "minato.tokyo.jp": true, "mitaka.tokyo.jp": true, "mizuho.tokyo.jp": true, "musashimurayama.tokyo.jp": true, "musashino.tokyo.jp": true, "nakano.tokyo.jp": true, "nerima.tokyo.jp": true, "ogasawara.tokyo.jp": true, "okutama.tokyo.jp": true, "ome.tokyo.jp": true, "oshima.tokyo.jp": true, "ota.tokyo.jp": true, "setagaya.tokyo.jp": true, "shibuya.tokyo.jp": true, "shinagawa.tokyo.jp": true, "shinjuku.tokyo.jp": true, "suginami.tokyo.jp": true, "sumida.tokyo.jp": true, "tachikawa.tokyo.jp": true, "taito.tokyo.jp": true, "tama.tokyo.jp": true, "toshima.tokyo.jp": true, "chizu.tottori.jp": true, "hino.tottori.jp": true, "kawahara.tottori.jp": true, "koge.tottori.jp": true, "kotoura.tottori.jp": true, "misasa.tottori.jp": true, "nanbu.tottori.jp": true, "nichinan.tottori.jp": true, "sakaiminato.tottori.jp": true, "tottori.tottori.jp": true, "wakasa.tottori.jp": true, "yazu.tottori.jp": true, "yonago.tottori.jp": true, "asahi.toyama.jp": true, "fuchu.toyama.jp": true, "fukumitsu.toyama.jp": true, "funahashi.toyama.jp": true, "himi.toyama.jp": true, "imizu.toyama.jp": true, "inami.toyama.jp": true, "johana.toyama.jp": true, "kamiichi.toyama.jp": true, "kurobe.toyama.jp": true, "nakaniikawa.toyama.jp": true, "namerikawa.toyama.jp": true, "nanto.toyama.jp": true, "nyuzen.toyama.jp": true, "oyabe.toyama.jp": true, "taira.toyama.jp": true, "takaoka.toyama.jp": true, "tateyama.toyama.jp": true, "toga.toyama.jp": true, "tonami.toyama.jp": true, "toyama.toyama.jp": true, "unazuki.toyama.jp": true, "uozu.toyama.jp": true, "yamada.toyama.jp": true, "arida.wakayama.jp": true, "aridagawa.wakayama.jp": true, "gobo.wakayama.jp": true, "hashimoto.wakayama.jp": true, "hidaka.wakayama.jp": true, "hirogawa.wakayama.jp": true, "inami.wakayama.jp": true, "iwade.wakayama.jp": true, "kainan.wakayama.jp": true, "kamitonda.wakayama.jp": true, "katsuragi.wakayama.jp": true, "kimino.wakayama.jp": true, "kinokawa.wakayama.jp": true, "kitayama.wakayama.jp": true, "koya.wakayama.jp": true, "koza.wakayama.jp": true, "kozagawa.wakayama.jp": true, "kudoyama.wakayama.jp": true, "kushimoto.wakayama.jp": true, "mihama.wakayama.jp": true, "misato.wakayama.jp": true, "nachikatsuura.wakayama.jp": true, "shingu.wakayama.jp": true, "shirahama.wakayama.jp": true, "taiji.wakayama.jp": true, "tanabe.wakayama.jp": true, "wakayama.wakayama.jp": true, "yuasa.wakayama.jp": true, "yura.wakayama.jp": true, "asahi.yamagata.jp": true, "funagata.yamagata.jp": true, "higashine.yamagata.jp": true, "iide.yamagata.jp": true, "kahoku.yamagata.jp": true, "kaminoyama.yamagata.jp": true, "kaneyama.yamagata.jp": true, "kawanishi.yamagata.jp": true, "mamurogawa.yamagata.jp": true, "mikawa.yamagata.jp": true, "murayama.yamagata.jp": true, "nagai.yamagata.jp": true, "nakayama.yamagata.jp": true, "nanyo.yamagata.jp": true, "nishikawa.yamagata.jp": true, "obanazawa.yamagata.jp": true, "oe.yamagata.jp": true, "oguni.yamagata.jp": true, "ohkura.yamagata.jp": true, "oishida.yamagata.jp": true, "sagae.yamagata.jp": true, "sakata.yamagata.jp": true, "sakegawa.yamagata.jp": true, "shinjo.yamagata.jp": true, "shirataka.yamagata.jp": true, "shonai.yamagata.jp": true, "takahata.yamagata.jp": true, "tendo.yamagata.jp": true, "tozawa.yamagata.jp": true, "tsuruoka.yamagata.jp": true, "yamagata.yamagata.jp": true, "yamanobe.yamagata.jp": true, "yonezawa.yamagata.jp": true, "yuza.yamagata.jp": true, "abu.yamaguchi.jp": true, "hagi.yamaguchi.jp": true, "hikari.yamaguchi.jp": true, "hofu.yamaguchi.jp": true, "iwakuni.yamaguchi.jp": true, "kudamatsu.yamaguchi.jp": true, "mitou.yamaguchi.jp": true, "nagato.yamaguchi.jp": true, "oshima.yamaguchi.jp": true, "shimonoseki.yamaguchi.jp": true, "shunan.yamaguchi.jp": true, "tabuse.yamaguchi.jp": true, "tokuyama.yamaguchi.jp": true, "toyota.yamaguchi.jp": true, "ube.yamaguchi.jp": true, "yuu.yamaguchi.jp": true, "chuo.yamanashi.jp": true, "doshi.yamanashi.jp": true, "fuefuki.yamanashi.jp": true, "fujikawa.yamanashi.jp": true, "fujikawaguchiko.yamanashi.jp": true, "fujiyoshida.yamanashi.jp": true, "hayakawa.yamanashi.jp": true, "hokuto.yamanashi.jp": true, "ichikawamisato.yamanashi.jp": true, "kai.yamanashi.jp": true, "kofu.yamanashi.jp": true, "koshu.yamanashi.jp": true, "kosuge.yamanashi.jp": true, "minami-alps.yamanashi.jp": true, "minobu.yamanashi.jp": true, "nakamichi.yamanashi.jp": true, "nanbu.yamanashi.jp": true, "narusawa.yamanashi.jp": true, "nirasaki.yamanashi.jp": true, "nishikatsura.yamanashi.jp": true, "oshino.yamanashi.jp": true, "otsuki.yamanashi.jp": true, "showa.yamanashi.jp": true, "tabayama.yamanashi.jp": true, "tsuru.yamanashi.jp": true, "uenohara.yamanashi.jp": true, "yamanakako.yamanashi.jp": true, "yamanashi.yamanashi.jp": true, "*.ke": true, "kg": true, "org.kg": true, "net.kg": true, "com.kg": true, "edu.kg": true, "gov.kg": true, "mil.kg": true, "*.kh": true, "ki": true, "edu.ki": true, "biz.ki": true, "net.ki": true, "org.ki": true, "gov.ki": true, "info.ki": true, "com.ki": true, "km": true, "org.km": true, "nom.km": true, "gov.km": true, "prd.km": true, "tm.km": true, "edu.km": true, "mil.km": true, "ass.km": true, "com.km": true, "coop.km": true, "asso.km": true, "presse.km": true, "medecin.km": true, "notaires.km": true, "pharmaciens.km": true, "veterinaire.km": true, "gouv.km": true, "kn": true, "net.kn": true, "org.kn": true, "edu.kn": true, "gov.kn": true, "kp": true, "com.kp": true, "edu.kp": true, "gov.kp": true, "org.kp": true, "rep.kp": true, "tra.kp": true, "kr": true, "ac.kr": true, "co.kr": true, "es.kr": true, "go.kr": true, "hs.kr": true, "kg.kr": true, "mil.kr": true, "ms.kr": true, "ne.kr": true, "or.kr": true, "pe.kr": true, "re.kr": true, "sc.kr": true, "busan.kr": true, "chungbuk.kr": true, "chungnam.kr": true, "daegu.kr": true, "daejeon.kr": true, "gangwon.kr": true, "gwangju.kr": true, "gyeongbuk.kr": true, "gyeonggi.kr": true, "gyeongnam.kr": true, "incheon.kr": true, "jeju.kr": true, "jeonbuk.kr": true, "jeonnam.kr": true, "seoul.kr": true, "ulsan.kr": true, "*.kw": true, "ky": true, "edu.ky": true, "gov.ky": true, "com.ky": true, "org.ky": true, "net.ky": true, "kz": true, "org.kz": true, "edu.kz": true, "net.kz": true, "gov.kz": true, "mil.kz": true, "com.kz": true, "la": true, "int.la": true, "net.la": true, "info.la": true, "edu.la": true, "gov.la": true, "per.la": true, "com.la": true, "org.la": true, "lb": true, "com.lb": true, "edu.lb": true, "gov.lb": true, "net.lb": true, "org.lb": true, "lc": true, "com.lc": true, "net.lc": true, "co.lc": true, "org.lc": true, "edu.lc": true, "gov.lc": true, "li": true, "lk": true, "gov.lk": true, "sch.lk": true, "net.lk": true, "int.lk": true, "com.lk": true, "org.lk": true, "edu.lk": true, "ngo.lk": true, "soc.lk": true, "web.lk": true, "ltd.lk": true, "assn.lk": true, "grp.lk": true, "hotel.lk": true, "ac.lk": true, "lr": true, "com.lr": true, "edu.lr": true, "gov.lr": true, "org.lr": true, "net.lr": true, "ls": true, "co.ls": true, "org.ls": true, "lt": true, "gov.lt": true, "lu": true, "lv": true, "com.lv": true, "edu.lv": true, "gov.lv": true, "org.lv": true, "mil.lv": true, "id.lv": true, "net.lv": true, "asn.lv": true, "conf.lv": true, "ly": true, "com.ly": true, "net.ly": true, "gov.ly": true, "plc.ly": true, "edu.ly": true, "sch.ly": true, "med.ly": true, "org.ly": true, "id.ly": true, "ma": true, "co.ma": true, "net.ma": true, "gov.ma": true, "org.ma": true, "ac.ma": true, "press.ma": true, "mc": true, "tm.mc": true, "asso.mc": true, "md": true, "me": true, "co.me": true, "net.me": true, "org.me": true, "edu.me": true, "ac.me": true, "gov.me": true, "its.me": true, "priv.me": true, "mg": true, "org.mg": true, "nom.mg": true, "gov.mg": true, "prd.mg": true, "tm.mg": true, "edu.mg": true, "mil.mg": true, "com.mg": true, "co.mg": true, "mh": true, "mil": true, "mk": true, "com.mk": true, "org.mk": true, "net.mk": true, "edu.mk": true, "gov.mk": true, "inf.mk": true, "name.mk": true, "ml": true, "com.ml": true, "edu.ml": true, "gouv.ml": true, "gov.ml": true, "net.ml": true, "org.ml": true, "presse.ml": true, "*.mm": true, "mn": true, "gov.mn": true, "edu.mn": true, "org.mn": true, "mo": true, "com.mo": true, "net.mo": true, "org.mo": true, "edu.mo": true, "gov.mo": true, "mobi": true, "mp": true, "mq": true, "mr": true, "gov.mr": true, "ms": true, "com.ms": true, "edu.ms": true, "gov.ms": true, "net.ms": true, "org.ms": true, "mt": true, "com.mt": true, "edu.mt": true, "net.mt": true, "org.mt": true, "mu": true, "com.mu": true, "net.mu": true, "org.mu": true, "gov.mu": true, "ac.mu": true, "co.mu": true, "or.mu": true, "museum": true, "academy.museum": true, "agriculture.museum": true, "air.museum": true, "airguard.museum": true, "alabama.museum": true, "alaska.museum": true, "amber.museum": true, "ambulance.museum": true, "american.museum": true, "americana.museum": true, "americanantiques.museum": true, "americanart.museum": true, "amsterdam.museum": true, "and.museum": true, "annefrank.museum": true, "anthro.museum": true, "anthropology.museum": true, "antiques.museum": true, "aquarium.museum": true, "arboretum.museum": true, "archaeological.museum": true, "archaeology.museum": true, "architecture.museum": true, "art.museum": true, "artanddesign.museum": true, "artcenter.museum": true, "artdeco.museum": true, "arteducation.museum": true, "artgallery.museum": true, "arts.museum": true, "artsandcrafts.museum": true, "asmatart.museum": true, "assassination.museum": true, "assisi.museum": true, "association.museum": true, "astronomy.museum": true, "atlanta.museum": true, "austin.museum": true, "australia.museum": true, "automotive.museum": true, "aviation.museum": true, "axis.museum": true, "badajoz.museum": true, "baghdad.museum": true, "bahn.museum": true, "bale.museum": true, "baltimore.museum": true, "barcelona.museum": true, "baseball.museum": true, "basel.museum": true, "baths.museum": true, "bauern.museum": true, "beauxarts.museum": true, "beeldengeluid.museum": true, "bellevue.museum": true, "bergbau.museum": true, "berkeley.museum": true, "berlin.museum": true, "bern.museum": true, "bible.museum": true, "bilbao.museum": true, "bill.museum": true, "birdart.museum": true, "birthplace.museum": true, "bonn.museum": true, "boston.museum": true, "botanical.museum": true, "botanicalgarden.museum": true, "botanicgarden.museum": true, "botany.museum": true, "brandywinevalley.museum": true, "brasil.museum": true, "bristol.museum": true, "british.museum": true, "britishcolumbia.museum": true, "broadcast.museum": true, "brunel.museum": true, "brussel.museum": true, "brussels.museum": true, "bruxelles.museum": true, "building.museum": true, "burghof.museum": true, "bus.museum": true, "bushey.museum": true, "cadaques.museum": true, "california.museum": true, "cambridge.museum": true, "can.museum": true, "canada.museum": true, "capebreton.museum": true, "carrier.museum": true, "cartoonart.museum": true, "casadelamoneda.museum": true, "castle.museum": true, "castres.museum": true, "celtic.museum": true, "center.museum": true, "chattanooga.museum": true, "cheltenham.museum": true, "chesapeakebay.museum": true, "chicago.museum": true, "children.museum": true, "childrens.museum": true, "childrensgarden.museum": true, "chiropractic.museum": true, "chocolate.museum": true, "christiansburg.museum": true, "cincinnati.museum": true, "cinema.museum": true, "circus.museum": true, "civilisation.museum": true, "civilization.museum": true, "civilwar.museum": true, "clinton.museum": true, "clock.museum": true, "coal.museum": true, "coastaldefence.museum": true, "cody.museum": true, "coldwar.museum": true, "collection.museum": true, "colonialwilliamsburg.museum": true, "coloradoplateau.museum": true, "columbia.museum": true, "columbus.museum": true, "communication.museum": true, "communications.museum": true, "community.museum": true, "computer.museum": true, "computerhistory.museum": true, "xn--comunicaes-v6a2o.museum": true, "contemporary.museum": true, "contemporaryart.museum": true, "convent.museum": true, "copenhagen.museum": true, "corporation.museum": true, "xn--correios-e-telecomunicaes-ghc29a.museum": true, "corvette.museum": true, "costume.museum": true, "countryestate.museum": true, "county.museum": true, "crafts.museum": true, "cranbrook.museum": true, "creation.museum": true, "cultural.museum": true, "culturalcenter.museum": true, "culture.museum": true, "cyber.museum": true, "cymru.museum": true, "dali.museum": true, "dallas.museum": true, "database.museum": true, "ddr.museum": true, "decorativearts.museum": true, "delaware.museum": true, "delmenhorst.museum": true, "denmark.museum": true, "depot.museum": true, "design.museum": true, "detroit.museum": true, "dinosaur.museum": true, "discovery.museum": true, "dolls.museum": true, "donostia.museum": true, "durham.museum": true, "eastafrica.museum": true, "eastcoast.museum": true, "education.museum": true, "educational.museum": true, "egyptian.museum": true, "eisenbahn.museum": true, "elburg.museum": true, "elvendrell.museum": true, "embroidery.museum": true, "encyclopedic.museum": true, "england.museum": true, "entomology.museum": true, "environment.museum": true, "environmentalconservation.museum": true, "epilepsy.museum": true, "essex.museum": true, "estate.museum": true, "ethnology.museum": true, "exeter.museum": true, "exhibition.museum": true, "family.museum": true, "farm.museum": true, "farmequipment.museum": true, "farmers.museum": true, "farmstead.museum": true, "field.museum": true, "figueres.museum": true, "filatelia.museum": true, "film.museum": true, "fineart.museum": true, "finearts.museum": true, "finland.museum": true, "flanders.museum": true, "florida.museum": true, "force.museum": true, "fortmissoula.museum": true, "fortworth.museum": true, "foundation.museum": true, "francaise.museum": true, "frankfurt.museum": true, "franziskaner.museum": true, "freemasonry.museum": true, "freiburg.museum": true, "fribourg.museum": true, "frog.museum": true, "fundacio.museum": true, "furniture.museum": true, "gallery.museum": true, "garden.museum": true, "gateway.museum": true, "geelvinck.museum": true, "gemological.museum": true, "geology.museum": true, "georgia.museum": true, "giessen.museum": true, "glas.museum": true, "glass.museum": true, "gorge.museum": true, "grandrapids.museum": true, "graz.museum": true, "guernsey.museum": true, "halloffame.museum": true, "hamburg.museum": true, "handson.museum": true, "harvestcelebration.museum": true, "hawaii.museum": true, "health.museum": true, "heimatunduhren.museum": true, "hellas.museum": true, "helsinki.museum": true, "hembygdsforbund.museum": true, "heritage.museum": true, "histoire.museum": true, "historical.museum": true, "historicalsociety.museum": true, "historichouses.museum": true, "historisch.museum": true, "historisches.museum": true, "history.museum": true, "historyofscience.museum": true, "horology.museum": true, "house.museum": true, "humanities.museum": true, "illustration.museum": true, "imageandsound.museum": true, "indian.museum": true, "indiana.museum": true, "indianapolis.museum": true, "indianmarket.museum": true, "intelligence.museum": true, "interactive.museum": true, "iraq.museum": true, "iron.museum": true, "isleofman.museum": true, "jamison.museum": true, "jefferson.museum": true, "jerusalem.museum": true, "jewelry.museum": true, "jewish.museum": true, "jewishart.museum": true, "jfk.museum": true, "journalism.museum": true, "judaica.museum": true, "judygarland.museum": true, "juedisches.museum": true, "juif.museum": true, "karate.museum": true, "karikatur.museum": true, "kids.museum": true, "koebenhavn.museum": true, "koeln.museum": true, "kunst.museum": true, "kunstsammlung.museum": true, "kunstunddesign.museum": true, "labor.museum": true, "labour.museum": true, "lajolla.museum": true, "lancashire.museum": true, "landes.museum": true, "lans.museum": true, "xn--lns-qla.museum": true, "larsson.museum": true, "lewismiller.museum": true, "lincoln.museum": true, "linz.museum": true, "living.museum": true, "livinghistory.museum": true, "localhistory.museum": true, "london.museum": true, "losangeles.museum": true, "louvre.museum": true, "loyalist.museum": true, "lucerne.museum": true, "luxembourg.museum": true, "luzern.museum": true, "mad.museum": true, "madrid.museum": true, "mallorca.museum": true, "manchester.museum": true, "mansion.museum": true, "mansions.museum": true, "manx.museum": true, "marburg.museum": true, "maritime.museum": true, "maritimo.museum": true, "maryland.museum": true, "marylhurst.museum": true, "media.museum": true, "medical.museum": true, "medizinhistorisches.museum": true, "meeres.museum": true, "memorial.museum": true, "mesaverde.museum": true, "michigan.museum": true, "midatlantic.museum": true, "military.museum": true, "mill.museum": true, "miners.museum": true, "mining.museum": true, "minnesota.museum": true, "missile.museum": true, "missoula.museum": true, "modern.museum": true, "moma.museum": true, "money.museum": true, "monmouth.museum": true, "monticello.museum": true, "montreal.museum": true, "moscow.museum": true, "motorcycle.museum": true, "muenchen.museum": true, "muenster.museum": true, "mulhouse.museum": true, "muncie.museum": true, "museet.museum": true, "museumcenter.museum": true, "museumvereniging.museum": true, "music.museum": true, "national.museum": true, "nationalfirearms.museum": true, "nationalheritage.museum": true, "nativeamerican.museum": true, "naturalhistory.museum": true, "naturalhistorymuseum.museum": true, "naturalsciences.museum": true, "nature.museum": true, "naturhistorisches.museum": true, "natuurwetenschappen.museum": true, "naumburg.museum": true, "naval.museum": true, "nebraska.museum": true, "neues.museum": true, "newhampshire.museum": true, "newjersey.museum": true, "newmexico.museum": true, "newport.museum": true, "newspaper.museum": true, "newyork.museum": true, "niepce.museum": true, "norfolk.museum": true, "north.museum": true, "nrw.museum": true, "nuernberg.museum": true, "nuremberg.museum": true, "nyc.museum": true, "nyny.museum": true, "oceanographic.museum": true, "oceanographique.museum": true, "omaha.museum": true, "online.museum": true, "ontario.museum": true, "openair.museum": true, "oregon.museum": true, "oregontrail.museum": true, "otago.museum": true, "oxford.museum": true, "pacific.museum": true, "paderborn.museum": true, "palace.museum": true, "paleo.museum": true, "palmsprings.museum": true, "panama.museum": true, "paris.museum": true, "pasadena.museum": true, "pharmacy.museum": true, "philadelphia.museum": true, "philadelphiaarea.museum": true, "philately.museum": true, "phoenix.museum": true, "photography.museum": true, "pilots.museum": true, "pittsburgh.museum": true, "planetarium.museum": true, "plantation.museum": true, "plants.museum": true, "plaza.museum": true, "portal.museum": true, "portland.museum": true, "portlligat.museum": true, "posts-and-telecommunications.museum": true, "preservation.museum": true, "presidio.museum": true, "press.museum": true, "project.museum": true, "public.museum": true, "pubol.museum": true, "quebec.museum": true, "railroad.museum": true, "railway.museum": true, "research.museum": true, "resistance.museum": true, "riodejaneiro.museum": true, "rochester.museum": true, "rockart.museum": true, "roma.museum": true, "russia.museum": true, "saintlouis.museum": true, "salem.museum": true, "salvadordali.museum": true, "salzburg.museum": true, "sandiego.museum": true, "sanfrancisco.museum": true, "santabarbara.museum": true, "santacruz.museum": true, "santafe.museum": true, "saskatchewan.museum": true, "satx.museum": true, "savannahga.museum": true, "schlesisches.museum": true, "schoenbrunn.museum": true, "schokoladen.museum": true, "school.museum": true, "schweiz.museum": true, "science.museum": true, "scienceandhistory.museum": true, "scienceandindustry.museum": true, "sciencecenter.museum": true, "sciencecenters.museum": true, "science-fiction.museum": true, "sciencehistory.museum": true, "sciences.museum": true, "sciencesnaturelles.museum": true, "scotland.museum": true, "seaport.museum": true, "settlement.museum": true, "settlers.museum": true, "shell.museum": true, "sherbrooke.museum": true, "sibenik.museum": true, "silk.museum": true, "ski.museum": true, "skole.museum": true, "society.museum": true, "sologne.museum": true, "soundandvision.museum": true, "southcarolina.museum": true, "southwest.museum": true, "space.museum": true, "spy.museum": true, "square.museum": true, "stadt.museum": true, "stalbans.museum": true, "starnberg.museum": true, "state.museum": true, "stateofdelaware.museum": true, "station.museum": true, "steam.museum": true, "steiermark.museum": true, "stjohn.museum": true, "stockholm.museum": true, "stpetersburg.museum": true, "stuttgart.museum": true, "suisse.museum": true, "surgeonshall.museum": true, "surrey.museum": true, "svizzera.museum": true, "sweden.museum": true, "sydney.museum": true, "tank.museum": true, "tcm.museum": true, "technology.museum": true, "telekommunikation.museum": true, "television.museum": true, "texas.museum": true, "textile.museum": true, "theater.museum": true, "time.museum": true, "timekeeping.museum": true, "topology.museum": true, "torino.museum": true, "touch.museum": true, "town.museum": true, "transport.museum": true, "tree.museum": true, "trolley.museum": true, "trust.museum": true, "trustee.museum": true, "uhren.museum": true, "ulm.museum": true, "undersea.museum": true, "university.museum": true, "usa.museum": true, "usantiques.museum": true, "usarts.museum": true, "uscountryestate.museum": true, "usculture.museum": true, "usdecorativearts.museum": true, "usgarden.museum": true, "ushistory.museum": true, "ushuaia.museum": true, "uslivinghistory.museum": true, "utah.museum": true, "uvic.museum": true, "valley.museum": true, "vantaa.museum": true, "versailles.museum": true, "viking.museum": true, "village.museum": true, "virginia.museum": true, "virtual.museum": true, "virtuel.museum": true, "vlaanderen.museum": true, "volkenkunde.museum": true, "wales.museum": true, "wallonie.museum": true, "war.museum": true, "washingtondc.museum": true, "watchandclock.museum": true, "watch-and-clock.museum": true, "western.museum": true, "westfalen.museum": true, "whaling.museum": true, "wildlife.museum": true, "williamsburg.museum": true, "windmill.museum": true, "workshop.museum": true, "york.museum": true, "yorkshire.museum": true, "yosemite.museum": true, "youth.museum": true, "zoological.museum": true, "zoology.museum": true, "xn--9dbhblg6di.museum": true, "xn--h1aegh.museum": true, "mv": true, "aero.mv": true, "biz.mv": true, "com.mv": true, "coop.mv": true, "edu.mv": true, "gov.mv": true, "info.mv": true, "int.mv": true, "mil.mv": true, "museum.mv": true, "name.mv": true, "net.mv": true, "org.mv": true, "pro.mv": true, "mw": true, "ac.mw": true, "biz.mw": true, "co.mw": true, "com.mw": true, "coop.mw": true, "edu.mw": true, "gov.mw": true, "int.mw": true, "museum.mw": true, "net.mw": true, "org.mw": true, "mx": true, "com.mx": true, "org.mx": true, "gob.mx": true, "edu.mx": true, "net.mx": true, "my": true, "com.my": true, "net.my": true, "org.my": true, "gov.my": true, "edu.my": true, "mil.my": true, "name.my": true, "mz": true, "ac.mz": true, "adv.mz": true, "co.mz": true, "edu.mz": true, "gov.mz": true, "mil.mz": true, "net.mz": true, "org.mz": true, "na": true, "info.na": true, "pro.na": true, "name.na": true, "school.na": true, "or.na": true, "dr.na": true, "us.na": true, "mx.na": true, "ca.na": true, "in.na": true, "cc.na": true, "tv.na": true, "ws.na": true, "mobi.na": true, "co.na": true, "com.na": true, "org.na": true, "name": true, "nc": true, "asso.nc": true, "ne": true, "net": true, "nf": true, "com.nf": true, "net.nf": true, "per.nf": true, "rec.nf": true, "web.nf": true, "arts.nf": true, "firm.nf": true, "info.nf": true, "other.nf": true, "store.nf": true, "ng": true, "com.ng": true, "edu.ng": true, "gov.ng": true, "i.ng": true, "mil.ng": true, "mobi.ng": true, "name.ng": true, "net.ng": true, "org.ng": true, "sch.ng": true, "com.ni": true, "gob.ni": true, "edu.ni": true, "org.ni": true, "nom.ni": true, "net.ni": true, "mil.ni": true, "co.ni": true, "biz.ni": true, "web.ni": true, "int.ni": true, "ac.ni": true, "in.ni": true, "info.ni": true, "nl": true, "bv.nl": true, "no": true, "fhs.no": true, "vgs.no": true, "fylkesbibl.no": true, "folkebibl.no": true, "museum.no": true, "idrett.no": true, "priv.no": true, "mil.no": true, "stat.no": true, "dep.no": true, "kommune.no": true, "herad.no": true, "aa.no": true, "ah.no": true, "bu.no": true, "fm.no": true, "hl.no": true, "hm.no": true, "jan-mayen.no": true, "mr.no": true, "nl.no": true, "nt.no": true, "of.no": true, "ol.no": true, "oslo.no": true, "rl.no": true, "sf.no": true, "st.no": true, "svalbard.no": true, "tm.no": true, "tr.no": true, "va.no": true, "vf.no": true, "gs.aa.no": true, "gs.ah.no": true, "gs.bu.no": true, "gs.fm.no": true, "gs.hl.no": true, "gs.hm.no": true, "gs.jan-mayen.no": true, "gs.mr.no": true, "gs.nl.no": true, "gs.nt.no": true, "gs.of.no": true, "gs.ol.no": true, "gs.oslo.no": true, "gs.rl.no": true, "gs.sf.no": true, "gs.st.no": true, "gs.svalbard.no": true, "gs.tm.no": true, "gs.tr.no": true, "gs.va.no": true, "gs.vf.no": true, "akrehamn.no": true, "xn--krehamn-dxa.no": true, "algard.no": true, "xn--lgrd-poac.no": true, "arna.no": true, "brumunddal.no": true, "bryne.no": true, "bronnoysund.no": true, "xn--brnnysund-m8ac.no": true, "drobak.no": true, "xn--drbak-wua.no": true, "egersund.no": true, "fetsund.no": true, "floro.no": true, "xn--flor-jra.no": true, "fredrikstad.no": true, "hokksund.no": true, "honefoss.no": true, "xn--hnefoss-q1a.no": true, "jessheim.no": true, "jorpeland.no": true, "xn--jrpeland-54a.no": true, "kirkenes.no": true, "kopervik.no": true, "krokstadelva.no": true, "langevag.no": true, "xn--langevg-jxa.no": true, "leirvik.no": true, "mjondalen.no": true, "xn--mjndalen-64a.no": true, "mo-i-rana.no": true, "mosjoen.no": true, "xn--mosjen-eya.no": true, "nesoddtangen.no": true, "orkanger.no": true, "osoyro.no": true, "xn--osyro-wua.no": true, "raholt.no": true, "xn--rholt-mra.no": true, "sandnessjoen.no": true, "xn--sandnessjen-ogb.no": true, "skedsmokorset.no": true, "slattum.no": true, "spjelkavik.no": true, "stathelle.no": true, "stavern.no": true, "stjordalshalsen.no": true, "xn--stjrdalshalsen-sqb.no": true, "tananger.no": true, "tranby.no": true, "vossevangen.no": true, "afjord.no": true, "xn--fjord-lra.no": true, "agdenes.no": true, "al.no": true, "xn--l-1fa.no": true, "alesund.no": true, "xn--lesund-hua.no": true, "alstahaug.no": true, "alta.no": true, "xn--lt-liac.no": true, "alaheadju.no": true, "xn--laheadju-7ya.no": true, "alvdal.no": true, "amli.no": true, "xn--mli-tla.no": true, "amot.no": true, "xn--mot-tla.no": true, "andebu.no": true, "andoy.no": true, "xn--andy-ira.no": true, "andasuolo.no": true, "ardal.no": true, "xn--rdal-poa.no": true, "aremark.no": true, "arendal.no": true, "xn--s-1fa.no": true, "aseral.no": true, "xn--seral-lra.no": true, "asker.no": true, "askim.no": true, "askvoll.no": true, "askoy.no": true, "xn--asky-ira.no": true, "asnes.no": true, "xn--snes-poa.no": true, "audnedaln.no": true, "aukra.no": true, "aure.no": true, "aurland.no": true, "aurskog-holand.no": true, "xn--aurskog-hland-jnb.no": true, "austevoll.no": true, "austrheim.no": true, "averoy.no": true, "xn--avery-yua.no": true, "balestrand.no": true, "ballangen.no": true, "balat.no": true, "xn--blt-elab.no": true, "balsfjord.no": true, "bahccavuotna.no": true, "xn--bhccavuotna-k7a.no": true, "bamble.no": true, "bardu.no": true, "beardu.no": true, "beiarn.no": true, "bajddar.no": true, "xn--bjddar-pta.no": true, "baidar.no": true, "xn--bidr-5nac.no": true, "berg.no": true, "bergen.no": true, "berlevag.no": true, "xn--berlevg-jxa.no": true, "bearalvahki.no": true, "xn--bearalvhki-y4a.no": true, "bindal.no": true, "birkenes.no": true, "bjarkoy.no": true, "xn--bjarky-fya.no": true, "bjerkreim.no": true, "bjugn.no": true, "bodo.no": true, "xn--bod-2na.no": true, "badaddja.no": true, "xn--bdddj-mrabd.no": true, "budejju.no": true, "bokn.no": true, "bremanger.no": true, "bronnoy.no": true, "xn--brnny-wuac.no": true, "bygland.no": true, "bykle.no": true, "barum.no": true, "xn--brum-voa.no": true, "bo.telemark.no": true, "xn--b-5ga.telemark.no": true, "bo.nordland.no": true, "xn--b-5ga.nordland.no": true, "bievat.no": true, "xn--bievt-0qa.no": true, "bomlo.no": true, "xn--bmlo-gra.no": true, "batsfjord.no": true, "xn--btsfjord-9za.no": true, "bahcavuotna.no": true, "xn--bhcavuotna-s4a.no": true, "dovre.no": true, "drammen.no": true, "drangedal.no": true, "dyroy.no": true, "xn--dyry-ira.no": true, "donna.no": true, "xn--dnna-gra.no": true, "eid.no": true, "eidfjord.no": true, "eidsberg.no": true, "eidskog.no": true, "eidsvoll.no": true, "eigersund.no": true, "elverum.no": true, "enebakk.no": true, "engerdal.no": true, "etne.no": true, "etnedal.no": true, "evenes.no": true, "evenassi.no": true, "xn--eveni-0qa01ga.no": true, "evje-og-hornnes.no": true, "farsund.no": true, "fauske.no": true, "fuossko.no": true, "fuoisku.no": true, "fedje.no": true, "fet.no": true, "finnoy.no": true, "xn--finny-yua.no": true, "fitjar.no": true, "fjaler.no": true, "fjell.no": true, "flakstad.no": true, "flatanger.no": true, "flekkefjord.no": true, "flesberg.no": true, "flora.no": true, "fla.no": true, "xn--fl-zia.no": true, "folldal.no": true, "forsand.no": true, "fosnes.no": true, "frei.no": true, "frogn.no": true, "froland.no": true, "frosta.no": true, "frana.no": true, "xn--frna-woa.no": true, "froya.no": true, "xn--frya-hra.no": true, "fusa.no": true, "fyresdal.no": true, "forde.no": true, "xn--frde-gra.no": true, "gamvik.no": true, "gangaviika.no": true, "xn--ggaviika-8ya47h.no": true, "gaular.no": true, "gausdal.no": true, "gildeskal.no": true, "xn--gildeskl-g0a.no": true, "giske.no": true, "gjemnes.no": true, "gjerdrum.no": true, "gjerstad.no": true, "gjesdal.no": true, "gjovik.no": true, "xn--gjvik-wua.no": true, "gloppen.no": true, "gol.no": true, "gran.no": true, "grane.no": true, "granvin.no": true, "gratangen.no": true, "grimstad.no": true, "grong.no": true, "kraanghke.no": true, "xn--kranghke-b0a.no": true, "grue.no": true, "gulen.no": true, "hadsel.no": true, "halden.no": true, "halsa.no": true, "hamar.no": true, "hamaroy.no": true, "habmer.no": true, "xn--hbmer-xqa.no": true, "hapmir.no": true, "xn--hpmir-xqa.no": true, "hammerfest.no": true, "hammarfeasta.no": true, "xn--hmmrfeasta-s4ac.no": true, "haram.no": true, "hareid.no": true, "harstad.no": true, "hasvik.no": true, "aknoluokta.no": true, "xn--koluokta-7ya57h.no": true, "hattfjelldal.no": true, "aarborte.no": true, "haugesund.no": true, "hemne.no": true, "hemnes.no": true, "hemsedal.no": true, "heroy.more-og-romsdal.no": true, "xn--hery-ira.xn--mre-og-romsdal-qqb.no": true, "heroy.nordland.no": true, "xn--hery-ira.nordland.no": true, "hitra.no": true, "hjartdal.no": true, "hjelmeland.no": true, "hobol.no": true, "xn--hobl-ira.no": true, "hof.no": true, "hol.no": true, "hole.no": true, "holmestrand.no": true, "holtalen.no": true, "xn--holtlen-hxa.no": true, "hornindal.no": true, "horten.no": true, "hurdal.no": true, "hurum.no": true, "hvaler.no": true, "hyllestad.no": true, "hagebostad.no": true, "xn--hgebostad-g3a.no": true, "hoyanger.no": true, "xn--hyanger-q1a.no": true, "hoylandet.no": true, "xn--hylandet-54a.no": true, "ha.no": true, "xn--h-2fa.no": true, "ibestad.no": true, "inderoy.no": true, "xn--indery-fya.no": true, "iveland.no": true, "jevnaker.no": true, "jondal.no": true, "jolster.no": true, "xn--jlster-bya.no": true, "karasjok.no": true, "karasjohka.no": true, "xn--krjohka-hwab49j.no": true, "karlsoy.no": true, "galsa.no": true, "xn--gls-elac.no": true, "karmoy.no": true, "xn--karmy-yua.no": true, "kautokeino.no": true, "guovdageaidnu.no": true, "klepp.no": true, "klabu.no": true, "xn--klbu-woa.no": true, "kongsberg.no": true, "kongsvinger.no": true, "kragero.no": true, "xn--krager-gya.no": true, "kristiansand.no": true, "kristiansund.no": true, "krodsherad.no": true, "xn--krdsherad-m8a.no": true, "kvalsund.no": true, "rahkkeravju.no": true, "xn--rhkkervju-01af.no": true, "kvam.no": true, "kvinesdal.no": true, "kvinnherad.no": true, "kviteseid.no": true, "kvitsoy.no": true, "xn--kvitsy-fya.no": true, "kvafjord.no": true, "xn--kvfjord-nxa.no": true, "giehtavuoatna.no": true, "kvanangen.no": true, "xn--kvnangen-k0a.no": true, "navuotna.no": true, "xn--nvuotna-hwa.no": true, "kafjord.no": true, "xn--kfjord-iua.no": true, "gaivuotna.no": true, "xn--givuotna-8ya.no": true, "larvik.no": true, "lavangen.no": true, "lavagis.no": true, "loabat.no": true, "xn--loabt-0qa.no": true, "lebesby.no": true, "davvesiida.no": true, "leikanger.no": true, "leirfjord.no": true, "leka.no": true, "leksvik.no": true, "lenvik.no": true, "leangaviika.no": true, "xn--leagaviika-52b.no": true, "lesja.no": true, "levanger.no": true, "lier.no": true, "lierne.no": true, "lillehammer.no": true, "lillesand.no": true, "lindesnes.no": true, "lindas.no": true, "xn--linds-pra.no": true, "lom.no": true, "loppa.no": true, "lahppi.no": true, "xn--lhppi-xqa.no": true, "lund.no": true, "lunner.no": true, "luroy.no": true, "xn--lury-ira.no": true, "luster.no": true, "lyngdal.no": true, "lyngen.no": true, "ivgu.no": true, "lardal.no": true, "lerdal.no": true, "xn--lrdal-sra.no": true, "lodingen.no": true, "xn--ldingen-q1a.no": true, "lorenskog.no": true, "xn--lrenskog-54a.no": true, "loten.no": true, "xn--lten-gra.no": true, "malvik.no": true, "masoy.no": true, "xn--msy-ula0h.no": true, "muosat.no": true, "xn--muost-0qa.no": true, "mandal.no": true, "marker.no": true, "marnardal.no": true, "masfjorden.no": true, "meland.no": true, "meldal.no": true, "melhus.no": true, "meloy.no": true, "xn--mely-ira.no": true, "meraker.no": true, "xn--merker-kua.no": true, "moareke.no": true, "xn--moreke-jua.no": true, "midsund.no": true, "midtre-gauldal.no": true, "modalen.no": true, "modum.no": true, "molde.no": true, "moskenes.no": true, "moss.no": true, "mosvik.no": true, "malselv.no": true, "xn--mlselv-iua.no": true, "malatvuopmi.no": true, "xn--mlatvuopmi-s4a.no": true, "namdalseid.no": true, "aejrie.no": true, "namsos.no": true, "namsskogan.no": true, "naamesjevuemie.no": true, "xn--nmesjevuemie-tcba.no": true, "laakesvuemie.no": true, "nannestad.no": true, "narvik.no": true, "narviika.no": true, "naustdal.no": true, "nedre-eiker.no": true, "nes.akershus.no": true, "nes.buskerud.no": true, "nesna.no": true, "nesodden.no": true, "nesseby.no": true, "unjarga.no": true, "xn--unjrga-rta.no": true, "nesset.no": true, "nissedal.no": true, "nittedal.no": true, "nord-aurdal.no": true, "nord-fron.no": true, "nord-odal.no": true, "norddal.no": true, "nordkapp.no": true, "davvenjarga.no": true, "xn--davvenjrga-y4a.no": true, "nordre-land.no": true, "nordreisa.no": true, "raisa.no": true, "xn--risa-5na.no": true, "nore-og-uvdal.no": true, "notodden.no": true, "naroy.no": true, "xn--nry-yla5g.no": true, "notteroy.no": true, "xn--nttery-byae.no": true, "odda.no": true, "oksnes.no": true, "xn--ksnes-uua.no": true, "oppdal.no": true, "oppegard.no": true, "xn--oppegrd-ixa.no": true, "orkdal.no": true, "orland.no": true, "xn--rland-uua.no": true, "orskog.no": true, "xn--rskog-uua.no": true, "orsta.no": true, "xn--rsta-fra.no": true, "os.hedmark.no": true, "os.hordaland.no": true, "osen.no": true, "osteroy.no": true, "xn--ostery-fya.no": true, "ostre-toten.no": true, "xn--stre-toten-zcb.no": true, "overhalla.no": true, "ovre-eiker.no": true, "xn--vre-eiker-k8a.no": true, "oyer.no": true, "xn--yer-zna.no": true, "oygarden.no": true, "xn--ygarden-p1a.no": true, "oystre-slidre.no": true, "xn--ystre-slidre-ujb.no": true, "porsanger.no": true, "porsangu.no": true, "xn--porsgu-sta26f.no": true, "porsgrunn.no": true, "radoy.no": true, "xn--rady-ira.no": true, "rakkestad.no": true, "rana.no": true, "ruovat.no": true, "randaberg.no": true, "rauma.no": true, "rendalen.no": true, "rennebu.no": true, "rennesoy.no": true, "xn--rennesy-v1a.no": true, "rindal.no": true, "ringebu.no": true, "ringerike.no": true, "ringsaker.no": true, "rissa.no": true, "risor.no": true, "xn--risr-ira.no": true, "roan.no": true, "rollag.no": true, "rygge.no": true, "ralingen.no": true, "xn--rlingen-mxa.no": true, "rodoy.no": true, "xn--rdy-0nab.no": true, "romskog.no": true, "xn--rmskog-bya.no": true, "roros.no": true, "xn--rros-gra.no": true, "rost.no": true, "xn--rst-0na.no": true, "royken.no": true, "xn--ryken-vua.no": true, "royrvik.no": true, "xn--ryrvik-bya.no": true, "rade.no": true, "xn--rde-ula.no": true, "salangen.no": true, "siellak.no": true, "saltdal.no": true, "salat.no": true, "xn--slt-elab.no": true, "xn--slat-5na.no": true, "samnanger.no": true, "sande.more-og-romsdal.no": true, "sande.xn--mre-og-romsdal-qqb.no": true, "sande.vestfold.no": true, "sandefjord.no": true, "sandnes.no": true, "sandoy.no": true, "xn--sandy-yua.no": true, "sarpsborg.no": true, "sauda.no": true, "sauherad.no": true, "sel.no": true, "selbu.no": true, "selje.no": true, "seljord.no": true, "sigdal.no": true, "siljan.no": true, "sirdal.no": true, "skaun.no": true, "skedsmo.no": true, "ski.no": true, "skien.no": true, "skiptvet.no": true, "skjervoy.no": true, "xn--skjervy-v1a.no": true, "skierva.no": true, "xn--skierv-uta.no": true, "skjak.no": true, "xn--skjk-soa.no": true, "skodje.no": true, "skanland.no": true, "xn--sknland-fxa.no": true, "skanit.no": true, "xn--sknit-yqa.no": true, "smola.no": true, "xn--smla-hra.no": true, "snillfjord.no": true, "snasa.no": true, "xn--snsa-roa.no": true, "snoasa.no": true, "snaase.no": true, "xn--snase-nra.no": true, "sogndal.no": true, "sokndal.no": true, "sola.no": true, "solund.no": true, "songdalen.no": true, "sortland.no": true, "spydeberg.no": true, "stange.no": true, "stavanger.no": true, "steigen.no": true, "steinkjer.no": true, "stjordal.no": true, "xn--stjrdal-s1a.no": true, "stokke.no": true, "stor-elvdal.no": true, "stord.no": true, "stordal.no": true, "storfjord.no": true, "omasvuotna.no": true, "strand.no": true, "stranda.no": true, "stryn.no": true, "sula.no": true, "suldal.no": true, "sund.no": true, "sunndal.no": true, "surnadal.no": true, "sveio.no": true, "svelvik.no": true, "sykkylven.no": true, "sogne.no": true, "xn--sgne-gra.no": true, "somna.no": true, "xn--smna-gra.no": true, "sondre-land.no": true, "xn--sndre-land-0cb.no": true, "sor-aurdal.no": true, "xn--sr-aurdal-l8a.no": true, "sor-fron.no": true, "xn--sr-fron-q1a.no": true, "sor-odal.no": true, "xn--sr-odal-q1a.no": true, "sor-varanger.no": true, "xn--sr-varanger-ggb.no": true, "matta-varjjat.no": true, "xn--mtta-vrjjat-k7af.no": true, "sorfold.no": true, "xn--srfold-bya.no": true, "sorreisa.no": true, "xn--srreisa-q1a.no": true, "sorum.no": true, "xn--srum-gra.no": true, "tana.no": true, "deatnu.no": true, "time.no": true, "tingvoll.no": true, "tinn.no": true, "tjeldsund.no": true, "dielddanuorri.no": true, "tjome.no": true, "xn--tjme-hra.no": true, "tokke.no": true, "tolga.no": true, "torsken.no": true, "tranoy.no": true, "xn--trany-yua.no": true, "tromso.no": true, "xn--troms-zua.no": true, "tromsa.no": true, "romsa.no": true, "trondheim.no": true, "troandin.no": true, "trysil.no": true, "trana.no": true, "xn--trna-woa.no": true, "trogstad.no": true, "xn--trgstad-r1a.no": true, "tvedestrand.no": true, "tydal.no": true, "tynset.no": true, "tysfjord.no": true, "divtasvuodna.no": true, "divttasvuotna.no": true, "tysnes.no": true, "tysvar.no": true, "xn--tysvr-vra.no": true, "tonsberg.no": true, "xn--tnsberg-q1a.no": true, "ullensaker.no": true, "ullensvang.no": true, "ulvik.no": true, "utsira.no": true, "vadso.no": true, "xn--vads-jra.no": true, "cahcesuolo.no": true, "xn--hcesuolo-7ya35b.no": true, "vaksdal.no": true, "valle.no": true, "vang.no": true, "vanylven.no": true, "vardo.no": true, "xn--vard-jra.no": true, "varggat.no": true, "xn--vrggt-xqad.no": true, "vefsn.no": true, "vaapste.no": true, "vega.no": true, "vegarshei.no": true, "xn--vegrshei-c0a.no": true, "vennesla.no": true, "verdal.no": true, "verran.no": true, "vestby.no": true, "vestnes.no": true, "vestre-slidre.no": true, "vestre-toten.no": true, "vestvagoy.no": true, "xn--vestvgy-ixa6o.no": true, "vevelstad.no": true, "vik.no": true, "vikna.no": true, "vindafjord.no": true, "volda.no": true, "voss.no": true, "varoy.no": true, "xn--vry-yla5g.no": true, "vagan.no": true, "xn--vgan-qoa.no": true, "voagat.no": true, "vagsoy.no": true, "xn--vgsy-qoa0j.no": true, "vaga.no": true, "xn--vg-yiab.no": true, "valer.ostfold.no": true, "xn--vler-qoa.xn--stfold-9xa.no": true, "valer.hedmark.no": true, "xn--vler-qoa.hedmark.no": true, "*.np": true, "nr": true, "biz.nr": true, "info.nr": true, "gov.nr": true, "edu.nr": true, "org.nr": true, "net.nr": true, "com.nr": true, "nu": true, "nz": true, "ac.nz": true, "co.nz": true, "cri.nz": true, "geek.nz": true, "gen.nz": true, "govt.nz": true, "health.nz": true, "iwi.nz": true, "kiwi.nz": true, "maori.nz": true, "mil.nz": true, "xn--mori-qsa.nz": true, "net.nz": true, "org.nz": true, "parliament.nz": true, "school.nz": true, "om": true, "co.om": true, "com.om": true, "edu.om": true, "gov.om": true, "med.om": true, "museum.om": true, "net.om": true, "org.om": true, "pro.om": true, "org": true, "pa": true, "ac.pa": true, "gob.pa": true, "com.pa": true, "org.pa": true, "sld.pa": true, "edu.pa": true, "net.pa": true, "ing.pa": true, "abo.pa": true, "med.pa": true, "nom.pa": true, "pe": true, "edu.pe": true, "gob.pe": true, "nom.pe": true, "mil.pe": true, "org.pe": true, "com.pe": true, "net.pe": true, "pf": true, "com.pf": true, "org.pf": true, "edu.pf": true, "*.pg": true, "ph": true, "com.ph": true, "net.ph": true, "org.ph": true, "gov.ph": true, "edu.ph": true, "ngo.ph": true, "mil.ph": true, "i.ph": true, "pk": true, "com.pk": true, "net.pk": true, "edu.pk": true, "org.pk": true, "fam.pk": true, "biz.pk": true, "web.pk": true, "gov.pk": true, "gob.pk": true, "gok.pk": true, "gon.pk": true, "gop.pk": true, "gos.pk": true, "info.pk": true, "pl": true, "com.pl": true, "net.pl": true, "org.pl": true, "aid.pl": true, "agro.pl": true, "atm.pl": true, "auto.pl": true, "biz.pl": true, "edu.pl": true, "gmina.pl": true, "gsm.pl": true, "info.pl": true, "mail.pl": true, "miasta.pl": true, "media.pl": true, "mil.pl": true, "nieruchomosci.pl": true, "nom.pl": true, "pc.pl": true, "powiat.pl": true, "priv.pl": true, "realestate.pl": true, "rel.pl": true, "sex.pl": true, "shop.pl": true, "sklep.pl": true, "sos.pl": true, "szkola.pl": true, "targi.pl": true, "tm.pl": true, "tourism.pl": true, "travel.pl": true, "turystyka.pl": true, "gov.pl": true, "ap.gov.pl": true, "ic.gov.pl": true, "is.gov.pl": true, "us.gov.pl": true, "kmpsp.gov.pl": true, "kppsp.gov.pl": true, "kwpsp.gov.pl": true, "psp.gov.pl": true, "wskr.gov.pl": true, "kwp.gov.pl": true, "mw.gov.pl": true, "ug.gov.pl": true, "um.gov.pl": true, "umig.gov.pl": true, "ugim.gov.pl": true, "upow.gov.pl": true, "uw.gov.pl": true, "starostwo.gov.pl": true, "pa.gov.pl": true, "po.gov.pl": true, "psse.gov.pl": true, "pup.gov.pl": true, "rzgw.gov.pl": true, "sa.gov.pl": true, "so.gov.pl": true, "sr.gov.pl": true, "wsa.gov.pl": true, "sko.gov.pl": true, "uzs.gov.pl": true, "wiih.gov.pl": true, "winb.gov.pl": true, "pinb.gov.pl": true, "wios.gov.pl": true, "witd.gov.pl": true, "wzmiuw.gov.pl": true, "piw.gov.pl": true, "wiw.gov.pl": true, "griw.gov.pl": true, "wif.gov.pl": true, "oum.gov.pl": true, "sdn.gov.pl": true, "zp.gov.pl": true, "uppo.gov.pl": true, "mup.gov.pl": true, "wuoz.gov.pl": true, "konsulat.gov.pl": true, "oirm.gov.pl": true, "augustow.pl": true, "babia-gora.pl": true, "bedzin.pl": true, "beskidy.pl": true, "bialowieza.pl": true, "bialystok.pl": true, "bielawa.pl": true, "bieszczady.pl": true, "boleslawiec.pl": true, "bydgoszcz.pl": true, "bytom.pl": true, "cieszyn.pl": true, "czeladz.pl": true, "czest.pl": true, "dlugoleka.pl": true, "elblag.pl": true, "elk.pl": true, "glogow.pl": true, "gniezno.pl": true, "gorlice.pl": true, "grajewo.pl": true, "ilawa.pl": true, "jaworzno.pl": true, "jelenia-gora.pl": true, "jgora.pl": true, "kalisz.pl": true, "kazimierz-dolny.pl": true, "karpacz.pl": true, "kartuzy.pl": true, "kaszuby.pl": true, "katowice.pl": true, "kepno.pl": true, "ketrzyn.pl": true, "klodzko.pl": true, "kobierzyce.pl": true, "kolobrzeg.pl": true, "konin.pl": true, "konskowola.pl": true, "kutno.pl": true, "lapy.pl": true, "lebork.pl": true, "legnica.pl": true, "lezajsk.pl": true, "limanowa.pl": true, "lomza.pl": true, "lowicz.pl": true, "lubin.pl": true, "lukow.pl": true, "malbork.pl": true, "malopolska.pl": true, "mazowsze.pl": true, "mazury.pl": true, "mielec.pl": true, "mielno.pl": true, "mragowo.pl": true, "naklo.pl": true, "nowaruda.pl": true, "nysa.pl": true, "olawa.pl": true, "olecko.pl": true, "olkusz.pl": true, "olsztyn.pl": true, "opoczno.pl": true, "opole.pl": true, "ostroda.pl": true, "ostroleka.pl": true, "ostrowiec.pl": true, "ostrowwlkp.pl": true, "pila.pl": true, "pisz.pl": true, "podhale.pl": true, "podlasie.pl": true, "polkowice.pl": true, "pomorze.pl": true, "pomorskie.pl": true, "prochowice.pl": true, "pruszkow.pl": true, "przeworsk.pl": true, "pulawy.pl": true, "radom.pl": true, "rawa-maz.pl": true, "rybnik.pl": true, "rzeszow.pl": true, "sanok.pl": true, "sejny.pl": true, "slask.pl": true, "slupsk.pl": true, "sosnowiec.pl": true, "stalowa-wola.pl": true, "skoczow.pl": true, "starachowice.pl": true, "stargard.pl": true, "suwalki.pl": true, "swidnica.pl": true, "swiebodzin.pl": true, "swinoujscie.pl": true, "szczecin.pl": true, "szczytno.pl": true, "tarnobrzeg.pl": true, "tgory.pl": true, "turek.pl": true, "tychy.pl": true, "ustka.pl": true, "walbrzych.pl": true, "warmia.pl": true, "warszawa.pl": true, "waw.pl": true, "wegrow.pl": true, "wielun.pl": true, "wlocl.pl": true, "wloclawek.pl": true, "wodzislaw.pl": true, "wolomin.pl": true, "wroclaw.pl": true, "zachpomor.pl": true, "zagan.pl": true, "zarow.pl": true, "zgora.pl": true, "zgorzelec.pl": true, "pm": true, "pn": true, "gov.pn": true, "co.pn": true, "org.pn": true, "edu.pn": true, "net.pn": true, "post": true, "pr": true, "com.pr": true, "net.pr": true, "org.pr": true, "gov.pr": true, "edu.pr": true, "isla.pr": true, "pro.pr": true, "biz.pr": true, "info.pr": true, "name.pr": true, "est.pr": true, "prof.pr": true, "ac.pr": true, "pro": true, "aaa.pro": true, "aca.pro": true, "acct.pro": true, "avocat.pro": true, "bar.pro": true, "cpa.pro": true, "eng.pro": true, "jur.pro": true, "law.pro": true, "med.pro": true, "recht.pro": true, "ps": true, "edu.ps": true, "gov.ps": true, "sec.ps": true, "plo.ps": true, "com.ps": true, "org.ps": true, "net.ps": true, "pt": true, "net.pt": true, "gov.pt": true, "org.pt": true, "edu.pt": true, "int.pt": true, "publ.pt": true, "com.pt": true, "nome.pt": true, "pw": true, "co.pw": true, "ne.pw": true, "or.pw": true, "ed.pw": true, "go.pw": true, "belau.pw": true, "py": true, "com.py": true, "coop.py": true, "edu.py": true, "gov.py": true, "mil.py": true, "net.py": true, "org.py": true, "qa": true, "com.qa": true, "edu.qa": true, "gov.qa": true, "mil.qa": true, "name.qa": true, "net.qa": true, "org.qa": true, "sch.qa": true, "re": true, "asso.re": true, "com.re": true, "nom.re": true, "ro": true, "arts.ro": true, "com.ro": true, "firm.ro": true, "info.ro": true, "nom.ro": true, "nt.ro": true, "org.ro": true, "rec.ro": true, "store.ro": true, "tm.ro": true, "www.ro": true, "rs": true, "ac.rs": true, "co.rs": true, "edu.rs": true, "gov.rs": true, "in.rs": true, "org.rs": true, "ru": true, "ac.ru": true, "com.ru": true, "edu.ru": true, "int.ru": true, "net.ru": true, "org.ru": true, "pp.ru": true, "adygeya.ru": true, "altai.ru": true, "amur.ru": true, "arkhangelsk.ru": true, "astrakhan.ru": true, "bashkiria.ru": true, "belgorod.ru": true, "bir.ru": true, "bryansk.ru": true, "buryatia.ru": true, "cbg.ru": true, "chel.ru": true, "chelyabinsk.ru": true, "chita.ru": true, "chukotka.ru": true, "chuvashia.ru": true, "dagestan.ru": true, "dudinka.ru": true, "e-burg.ru": true, "grozny.ru": true, "irkutsk.ru": true, "ivanovo.ru": true, "izhevsk.ru": true, "jar.ru": true, "joshkar-ola.ru": true, "kalmykia.ru": true, "kaluga.ru": true, "kamchatka.ru": true, "karelia.ru": true, "kazan.ru": true, "kchr.ru": true, "kemerovo.ru": true, "khabarovsk.ru": true, "khakassia.ru": true, "khv.ru": true, "kirov.ru": true, "koenig.ru": true, "komi.ru": true, "kostroma.ru": true, "krasnoyarsk.ru": true, "kuban.ru": true, "kurgan.ru": true, "kursk.ru": true, "lipetsk.ru": true, "magadan.ru": true, "mari.ru": true, "mari-el.ru": true, "marine.ru": true, "mordovia.ru": true, "msk.ru": true, "murmansk.ru": true, "nalchik.ru": true, "nnov.ru": true, "nov.ru": true, "novosibirsk.ru": true, "nsk.ru": true, "omsk.ru": true, "orenburg.ru": true, "oryol.ru": true, "palana.ru": true, "penza.ru": true, "perm.ru": true, "ptz.ru": true, "rnd.ru": true, "ryazan.ru": true, "sakhalin.ru": true, "samara.ru": true, "saratov.ru": true, "simbirsk.ru": true, "smolensk.ru": true, "spb.ru": true, "stavropol.ru": true, "stv.ru": true, "surgut.ru": true, "tambov.ru": true, "tatarstan.ru": true, "tom.ru": true, "tomsk.ru": true, "tsaritsyn.ru": true, "tsk.ru": true, "tula.ru": true, "tuva.ru": true, "tver.ru": true, "tyumen.ru": true, "udm.ru": true, "udmurtia.ru": true, "ulan-ude.ru": true, "vladikavkaz.ru": true, "vladimir.ru": true, "vladivostok.ru": true, "volgograd.ru": true, "vologda.ru": true, "voronezh.ru": true, "vrn.ru": true, "vyatka.ru": true, "yakutia.ru": true, "yamal.ru": true, "yaroslavl.ru": true, "yekaterinburg.ru": true, "yuzhno-sakhalinsk.ru": true, "amursk.ru": true, "baikal.ru": true, "cmw.ru": true, "fareast.ru": true, "jamal.ru": true, "kms.ru": true, "k-uralsk.ru": true, "kustanai.ru": true, "kuzbass.ru": true, "mytis.ru": true, "nakhodka.ru": true, "nkz.ru": true, "norilsk.ru": true, "oskol.ru": true, "pyatigorsk.ru": true, "rubtsovsk.ru": true, "snz.ru": true, "syzran.ru": true, "vdonsk.ru": true, "zgrad.ru": true, "gov.ru": true, "mil.ru": true, "test.ru": true, "rw": true, "gov.rw": true, "net.rw": true, "edu.rw": true, "ac.rw": true, "com.rw": true, "co.rw": true, "int.rw": true, "mil.rw": true, "gouv.rw": true, "sa": true, "com.sa": true, "net.sa": true, "org.sa": true, "gov.sa": true, "med.sa": true, "pub.sa": true, "edu.sa": true, "sch.sa": true, "sb": true, "com.sb": true, "edu.sb": true, "gov.sb": true, "net.sb": true, "org.sb": true, "sc": true, "com.sc": true, "gov.sc": true, "net.sc": true, "org.sc": true, "edu.sc": true, "sd": true, "com.sd": true, "net.sd": true, "org.sd": true, "edu.sd": true, "med.sd": true, "tv.sd": true, "gov.sd": true, "info.sd": true, "se": true, "a.se": true, "ac.se": true, "b.se": true, "bd.se": true, "brand.se": true, "c.se": true, "d.se": true, "e.se": true, "f.se": true, "fh.se": true, "fhsk.se": true, "fhv.se": true, "g.se": true, "h.se": true, "i.se": true, "k.se": true, "komforb.se": true, "kommunalforbund.se": true, "komvux.se": true, "l.se": true, "lanbib.se": true, "m.se": true, "n.se": true, "naturbruksgymn.se": true, "o.se": true, "org.se": true, "p.se": true, "parti.se": true, "pp.se": true, "press.se": true, "r.se": true, "s.se": true, "t.se": true, "tm.se": true, "u.se": true, "w.se": true, "x.se": true, "y.se": true, "z.se": true, "sg": true, "com.sg": true, "net.sg": true, "org.sg": true, "gov.sg": true, "edu.sg": true, "per.sg": true, "sh": true, "com.sh": true, "net.sh": true, "gov.sh": true, "org.sh": true, "mil.sh": true, "si": true, "sj": true, "sk": true, "sl": true, "com.sl": true, "net.sl": true, "edu.sl": true, "gov.sl": true, "org.sl": true, "sm": true, "sn": true, "art.sn": true, "com.sn": true, "edu.sn": true, "gouv.sn": true, "org.sn": true, "perso.sn": true, "univ.sn": true, "so": true, "com.so": true, "net.so": true, "org.so": true, "sr": true, "st": true, "co.st": true, "com.st": true, "consulado.st": true, "edu.st": true, "embaixada.st": true, "gov.st": true, "mil.st": true, "net.st": true, "org.st": true, "principe.st": true, "saotome.st": true, "store.st": true, "su": true, "adygeya.su": true, "arkhangelsk.su": true, "balashov.su": true, "bashkiria.su": true, "bryansk.su": true, "dagestan.su": true, "grozny.su": true, "ivanovo.su": true, "kalmykia.su": true, "kaluga.su": true, "karelia.su": true, "khakassia.su": true, "krasnodar.su": true, "kurgan.su": true, "lenug.su": true, "mordovia.su": true, "msk.su": true, "murmansk.su": true, "nalchik.su": true, "nov.su": true, "obninsk.su": true, "penza.su": true, "pokrovsk.su": true, "sochi.su": true, "spb.su": true, "togliatti.su": true, "troitsk.su": true, "tula.su": true, "tuva.su": true, "vladikavkaz.su": true, "vladimir.su": true, "vologda.su": true, "sv": true, "com.sv": true, "edu.sv": true, "gob.sv": true, "org.sv": true, "red.sv": true, "sx": true, "gov.sx": true, "sy": true, "edu.sy": true, "gov.sy": true, "net.sy": true, "mil.sy": true, "com.sy": true, "org.sy": true, "sz": true, "co.sz": true, "ac.sz": true, "org.sz": true, "tc": true, "td": true, "tel": true, "tf": true, "tg": true, "th": true, "ac.th": true, "co.th": true, "go.th": true, "in.th": true, "mi.th": true, "net.th": true, "or.th": true, "tj": true, "ac.tj": true, "biz.tj": true, "co.tj": true, "com.tj": true, "edu.tj": true, "go.tj": true, "gov.tj": true, "int.tj": true, "mil.tj": true, "name.tj": true, "net.tj": true, "nic.tj": true, "org.tj": true, "test.tj": true, "web.tj": true, "tk": true, "tl": true, "gov.tl": true, "tm": true, "com.tm": true, "co.tm": true, "org.tm": true, "net.tm": true, "nom.tm": true, "gov.tm": true, "mil.tm": true, "edu.tm": true, "tn": true, "com.tn": true, "ens.tn": true, "fin.tn": true, "gov.tn": true, "ind.tn": true, "intl.tn": true, "nat.tn": true, "net.tn": true, "org.tn": true, "info.tn": true, "perso.tn": true, "tourism.tn": true, "edunet.tn": true, "rnrt.tn": true, "rns.tn": true, "rnu.tn": true, "mincom.tn": true, "agrinet.tn": true, "defense.tn": true, "turen.tn": true, "to": true, "com.to": true, "gov.to": true, "net.to": true, "org.to": true, "edu.to": true, "mil.to": true, "tr": true, "com.tr": true, "info.tr": true, "biz.tr": true, "net.tr": true, "org.tr": true, "web.tr": true, "gen.tr": true, "tv.tr": true, "av.tr": true, "dr.tr": true, "bbs.tr": true, "name.tr": true, "tel.tr": true, "gov.tr": true, "bel.tr": true, "pol.tr": true, "mil.tr": true, "k12.tr": true, "edu.tr": true, "kep.tr": true, "nc.tr": true, "gov.nc.tr": true, "travel": true, "tt": true, "co.tt": true, "com.tt": true, "org.tt": true, "net.tt": true, "biz.tt": true, "info.tt": true, "pro.tt": true, "int.tt": true, "coop.tt": true, "jobs.tt": true, "mobi.tt": true, "travel.tt": true, "museum.tt": true, "aero.tt": true, "name.tt": true, "gov.tt": true, "edu.tt": true, "tv": true, "tw": true, "edu.tw": true, "gov.tw": true, "mil.tw": true, "com.tw": true, "net.tw": true, "org.tw": true, "idv.tw": true, "game.tw": true, "ebiz.tw": true, "club.tw": true, "xn--zf0ao64a.tw": true, "xn--uc0atv.tw": true, "xn--czrw28b.tw": true, "tz": true, "ac.tz": true, "co.tz": true, "go.tz": true, "hotel.tz": true, "info.tz": true, "me.tz": true, "mil.tz": true, "mobi.tz": true, "ne.tz": true, "or.tz": true, "sc.tz": true, "tv.tz": true, "ua": true, "com.ua": true, "edu.ua": true, "gov.ua": true, "in.ua": true, "net.ua": true, "org.ua": true, "cherkassy.ua": true, "cherkasy.ua": true, "chernigov.ua": true, "chernihiv.ua": true, "chernivtsi.ua": true, "chernovtsy.ua": true, "ck.ua": true, "cn.ua": true, "cr.ua": true, "crimea.ua": true, "cv.ua": true, "dn.ua": true, "dnepropetrovsk.ua": true, "dnipropetrovsk.ua": true, "dominic.ua": true, "donetsk.ua": true, "dp.ua": true, "if.ua": true, "ivano-frankivsk.ua": true, "kh.ua": true, "kharkiv.ua": true, "kharkov.ua": true, "kherson.ua": true, "khmelnitskiy.ua": true, "khmelnytskyi.ua": true, "kiev.ua": true, "kirovograd.ua": true, "km.ua": true, "kr.ua": true, "krym.ua": true, "ks.ua": true, "kv.ua": true, "kyiv.ua": true, "lg.ua": true, "lt.ua": true, "lugansk.ua": true, "lutsk.ua": true, "lv.ua": true, "lviv.ua": true, "mk.ua": true, "mykolaiv.ua": true, "nikolaev.ua": true, "od.ua": true, "odesa.ua": true, "odessa.ua": true, "pl.ua": true, "poltava.ua": true, "rivne.ua": true, "rovno.ua": true, "rv.ua": true, "sb.ua": true, "sebastopol.ua": true, "sevastopol.ua": true, "sm.ua": true, "sumy.ua": true, "te.ua": true, "ternopil.ua": true, "uz.ua": true, "uzhgorod.ua": true, "vinnica.ua": true, "vinnytsia.ua": true, "vn.ua": true, "volyn.ua": true, "yalta.ua": true, "zaporizhzhe.ua": true, "zaporizhzhia.ua": true, "zhitomir.ua": true, "zhytomyr.ua": true, "zp.ua": true, "zt.ua": true, "ug": true, "co.ug": true, "or.ug": true, "ac.ug": true, "sc.ug": true, "go.ug": true, "ne.ug": true, "com.ug": true, "org.ug": true, "uk": true, "ac.uk": true, "co.uk": true, "gov.uk": true, "ltd.uk": true, "me.uk": true, "net.uk": true, "nhs.uk": true, "org.uk": true, "plc.uk": true, "police.uk": true, "*.sch.uk": true, "us": true, "dni.us": true, "fed.us": true, "isa.us": true, "kids.us": true, "nsn.us": true, "ak.us": true, "al.us": true, "ar.us": true, "as.us": true, "az.us": true, "ca.us": true, "co.us": true, "ct.us": true, "dc.us": true, "de.us": true, "fl.us": true, "ga.us": true, "gu.us": true, "hi.us": true, "ia.us": true, "id.us": true, "il.us": true, "in.us": true, "ks.us": true, "ky.us": true, "la.us": true, "ma.us": true, "md.us": true, "me.us": true, "mi.us": true, "mn.us": true, "mo.us": true, "ms.us": true, "mt.us": true, "nc.us": true, "nd.us": true, "ne.us": true, "nh.us": true, "nj.us": true, "nm.us": true, "nv.us": true, "ny.us": true, "oh.us": true, "ok.us": true, "or.us": true, "pa.us": true, "pr.us": true, "ri.us": true, "sc.us": true, "sd.us": true, "tn.us": true, "tx.us": true, "ut.us": true, "vi.us": true, "vt.us": true, "va.us": true, "wa.us": true, "wi.us": true, "wv.us": true, "wy.us": true, "k12.ak.us": true, "k12.al.us": true, "k12.ar.us": true, "k12.as.us": true, "k12.az.us": true, "k12.ca.us": true, "k12.co.us": true, "k12.ct.us": true, "k12.dc.us": true, "k12.de.us": true, "k12.fl.us": true, "k12.ga.us": true, "k12.gu.us": true, "k12.ia.us": true, "k12.id.us": true, "k12.il.us": true, "k12.in.us": true, "k12.ks.us": true, "k12.ky.us": true, "k12.la.us": true, "k12.ma.us": true, "k12.md.us": true, "k12.me.us": true, "k12.mi.us": true, "k12.mn.us": true, "k12.mo.us": true, "k12.ms.us": true, "k12.mt.us": true, "k12.nc.us": true, "k12.ne.us": true, "k12.nh.us": true, "k12.nj.us": true, "k12.nm.us": true, "k12.nv.us": true, "k12.ny.us": true, "k12.oh.us": true, "k12.ok.us": true, "k12.or.us": true, "k12.pa.us": true, "k12.pr.us": true, "k12.ri.us": true, "k12.sc.us": true, "k12.tn.us": true, "k12.tx.us": true, "k12.ut.us": true, "k12.vi.us": true, "k12.vt.us": true, "k12.va.us": true, "k12.wa.us": true, "k12.wi.us": true, "k12.wy.us": true, "cc.ak.us": true, "cc.al.us": true, "cc.ar.us": true, "cc.as.us": true, "cc.az.us": true, "cc.ca.us": true, "cc.co.us": true, "cc.ct.us": true, "cc.dc.us": true, "cc.de.us": true, "cc.fl.us": true, "cc.ga.us": true, "cc.gu.us": true, "cc.hi.us": true, "cc.ia.us": true, "cc.id.us": true, "cc.il.us": true, "cc.in.us": true, "cc.ks.us": true, "cc.ky.us": true, "cc.la.us": true, "cc.ma.us": true, "cc.md.us": true, "cc.me.us": true, "cc.mi.us": true, "cc.mn.us": true, "cc.mo.us": true, "cc.ms.us": true, "cc.mt.us": true, "cc.nc.us": true, "cc.nd.us": true, "cc.ne.us": true, "cc.nh.us": true, "cc.nj.us": true, "cc.nm.us": true, "cc.nv.us": true, "cc.ny.us": true, "cc.oh.us": true, "cc.ok.us": true, "cc.or.us": true, "cc.pa.us": true, "cc.pr.us": true, "cc.ri.us": true, "cc.sc.us": true, "cc.sd.us": true, "cc.tn.us": true, "cc.tx.us": true, "cc.ut.us": true, "cc.vi.us": true, "cc.vt.us": true, "cc.va.us": true, "cc.wa.us": true, "cc.wi.us": true, "cc.wv.us": true, "cc.wy.us": true, "lib.ak.us": true, "lib.al.us": true, "lib.ar.us": true, "lib.as.us": true, "lib.az.us": true, "lib.ca.us": true, "lib.co.us": true, "lib.ct.us": true, "lib.dc.us": true, "lib.fl.us": true, "lib.ga.us": true, "lib.gu.us": true, "lib.hi.us": true, "lib.ia.us": true, "lib.id.us": true, "lib.il.us": true, "lib.in.us": true, "lib.ks.us": true, "lib.ky.us": true, "lib.la.us": true, "lib.ma.us": true, "lib.md.us": true, "lib.me.us": true, "lib.mi.us": true, "lib.mn.us": true, "lib.mo.us": true, "lib.ms.us": true, "lib.mt.us": true, "lib.nc.us": true, "lib.nd.us": true, "lib.ne.us": true, "lib.nh.us": true, "lib.nj.us": true, "lib.nm.us": true, "lib.nv.us": true, "lib.ny.us": true, "lib.oh.us": true, "lib.ok.us": true, "lib.or.us": true, "lib.pa.us": true, "lib.pr.us": true, "lib.ri.us": true, "lib.sc.us": true, "lib.sd.us": true, "lib.tn.us": true, "lib.tx.us": true, "lib.ut.us": true, "lib.vi.us": true, "lib.vt.us": true, "lib.va.us": true, "lib.wa.us": true, "lib.wi.us": true, "lib.wy.us": true, "pvt.k12.ma.us": true, "chtr.k12.ma.us": true, "paroch.k12.ma.us": true, "uy": true, "com.uy": true, "edu.uy": true, "gub.uy": true, "mil.uy": true, "net.uy": true, "org.uy": true, "uz": true, "co.uz": true, "com.uz": true, "net.uz": true, "org.uz": true, "va": true, "vc": true, "com.vc": true, "net.vc": true, "org.vc": true, "gov.vc": true, "mil.vc": true, "edu.vc": true, "ve": true, "arts.ve": true, "co.ve": true, "com.ve": true, "e12.ve": true, "edu.ve": true, "firm.ve": true, "gob.ve": true, "gov.ve": true, "info.ve": true, "int.ve": true, "mil.ve": true, "net.ve": true, "org.ve": true, "rec.ve": true, "store.ve": true, "tec.ve": true, "web.ve": true, "vg": true, "vi": true, "co.vi": true, "com.vi": true, "k12.vi": true, "net.vi": true, "org.vi": true, "vn": true, "com.vn": true, "net.vn": true, "org.vn": true, "edu.vn": true, "gov.vn": true, "int.vn": true, "ac.vn": true, "biz.vn": true, "info.vn": true, "name.vn": true, "pro.vn": true, "health.vn": true, "vu": true, "com.vu": true, "edu.vu": true, "net.vu": true, "org.vu": true, "wf": true, "ws": true, "com.ws": true, "net.ws": true, "org.ws": true, "gov.ws": true, "edu.ws": true, "yt": true, "xn--mgbaam7a8h": true, "xn--y9a3aq": true, "xn--54b7fta0cc": true, "xn--90ais": true, "xn--fiqs8s": true, "xn--fiqz9s": true, "xn--lgbbat1ad8j": true, "xn--wgbh1c": true, "xn--e1a4c": true, "xn--node": true, "xn--qxam": true, "xn--j6w193g": true, "xn--h2brj9c": true, "xn--mgbbh1a71e": true, "xn--fpcrj9c3d": true, "xn--gecrj9c": true, "xn--s9brj9c": true, "xn--45brj9c": true, "xn--xkc2dl3a5ee0h": true, "xn--mgba3a4f16a": true, "xn--mgba3a4fra": true, "xn--mgbtx2b": true, "xn--mgbayh7gpa": true, "xn--3e0b707e": true, "xn--80ao21a": true, "xn--fzc2c9e2c": true, "xn--xkc2al3hye2a": true, "xn--mgbc0a9azcg": true, "xn--d1alf": true, "xn--l1acc": true, "xn--mix891f": true, "xn--mix082f": true, "xn--mgbx4cd0ab": true, "xn--mgb9awbf": true, "xn--mgbai9azgqp6j": true, "xn--mgbai9a5eva00b": true, "xn--ygbi2ammx": true, "xn--90a3ac": true, "xn--o1ac.xn--90a3ac": true, "xn--c1avg.xn--90a3ac": true, "xn--90azh.xn--90a3ac": true, "xn--d1at.xn--90a3ac": true, "xn--o1ach.xn--90a3ac": true, "xn--80au.xn--90a3ac": true, "xn--p1ai": true, "xn--wgbl6a": true, "xn--mgberp4a5d4ar": true, "xn--mgberp4a5d4a87g": true, "xn--mgbqly7c0a67fbc": true, "xn--mgbqly7cvafr": true, "xn--mgbpl2fh": true, "xn--yfro4i67o": true, "xn--clchc0ea0b2g2a9gcd": true, "xn--ogbpf8fl": true, "xn--mgbtf8fl": true, "xn--o3cw4h": true, "xn--pgbs0dh": true, "xn--kpry57d": true, "xn--kprw13d": true, "xn--nnx388a": true, "xn--j1amh": true, "xn--mgb2ddes": true, "xxx": true, "*.ye": true, "ac.za": true, "agric.za": true, "alt.za": true, "co.za": true, "edu.za": true, "gov.za": true, "grondar.za": true, "law.za": true, "mil.za": true, "net.za": true, "ngo.za": true, "nis.za": true, "nom.za": true, "org.za": true, "school.za": true, "tm.za": true, "web.za": true, "zm": true, "ac.zm": true, "biz.zm": true, "co.zm": true, "com.zm": true, "edu.zm": true, "gov.zm": true, "info.zm": true, "mil.zm": true, "net.zm": true, "org.zm": true, "sch.zm": true, "*.zw": true, "aaa": true, "aarp": true, "abarth": true, "abb": true, "abbott": true, "abbvie": true, "abc": true, "able": true, "abogado": true, "abudhabi": true, "academy": true, "accenture": true, "accountant": true, "accountants": true, "aco": true, "active": true, "actor": true, "adac": true, "ads": true, "adult": true, "aeg": true, "aetna": true, "afamilycompany": true, "afl": true, "africa": true, "agakhan": true, "agency": true, "aig": true, "aigo": true, "airbus": true, "airforce": true, "airtel": true, "akdn": true, "alfaromeo": true, "alibaba": true, "alipay": true, "allfinanz": true, "allstate": true, "ally": true, "alsace": true, "alstom": true, "americanexpress": true, "americanfamily": true, "amex": true, "amfam": true, "amica": true, "amsterdam": true, "analytics": true, "android": true, "anquan": true, "anz": true, "aol": true, "apartments": true, "app": true, "apple": true, "aquarelle": true, "arab": true, "aramco": true, "archi": true, "army": true, "art": true, "arte": true, "asda": true, "associates": true, "athleta": true, "attorney": true, "auction": true, "audi": true, "audible": true, "audio": true, "auspost": true, "author": true, "auto": true, "autos": true, "avianca": true, "aws": true, "axa": true, "azure": true, "baby": true, "baidu": true, "banamex": true, "bananarepublic": true, "band": true, "bank": true, "bar": true, "barcelona": true, "barclaycard": true, "barclays": true, "barefoot": true, "bargains": true, "baseball": true, "basketball": true, "bauhaus": true, "bayern": true, "bbc": true, "bbt": true, "bbva": true, "bcg": true, "bcn": true, "beats": true, "beauty": true, "beer": true, "bentley": true, "berlin": true, "best": true, "bestbuy": true, "bet": true, "bharti": true, "bible": true, "bid": true, "bike": true, "bing": true, "bingo": true, "bio": true, "black": true, "blackfriday": true, "blanco": true, "blockbuster": true, "blog": true, "bloomberg": true, "blue": true, "bms": true, "bmw": true, "bnl": true, "bnpparibas": true, "boats": true, "boehringer": true, "bofa": true, "bom": true, "bond": true, "boo": true, "book": true, "booking": true, "boots": true, "bosch": true, "bostik": true, "boston": true, "bot": true, "boutique": true, "box": true, "bradesco": true, "bridgestone": true, "broadway": true, "broker": true, "brother": true, "brussels": true, "budapest": true, "bugatti": true, "build": true, "builders": true, "business": true, "buy": true, "buzz": true, "bzh": true, "cab": true, "cafe": true, "cal": true, "call": true, "calvinklein": true, "cam": true, "camera": true, "camp": true, "cancerresearch": true, "canon": true, "capetown": true, "capital": true, "capitalone": true, "car": true, "caravan": true, "cards": true, "care": true, "career": true, "careers": true, "cars": true, "cartier": true, "casa": true, "case": true, "caseih": true, "cash": true, "casino": true, "catering": true, "catholic": true, "cba": true, "cbn": true, "cbre": true, "cbs": true, "ceb": true, "center": true, "ceo": true, "cern": true, "cfa": true, "cfd": true, "chanel": true, "channel": true, "chase": true, "chat": true, "cheap": true, "chintai": true, "chloe": true, "christmas": true, "chrome": true, "chrysler": true, "church": true, "cipriani": true, "circle": true, "cisco": true, "citadel": true, "citi": true, "citic": true, "city": true, "cityeats": true, "claims": true, "cleaning": true, "click": true, "clinic": true, "clinique": true, "clothing": true, "cloud": true, "club": true, "clubmed": true, "coach": true, "codes": true, "coffee": true, "college": true, "cologne": true, "comcast": true, "commbank": true, "community": true, "company": true, "compare": true, "computer": true, "comsec": true, "condos": true, "construction": true, "consulting": true, "contact": true, "contractors": true, "cooking": true, "cookingchannel": true, "cool": true, "corsica": true, "country": true, "coupon": true, "coupons": true, "courses": true, "credit": true, "creditcard": true, "creditunion": true, "cricket": true, "crown": true, "crs": true, "cruise": true, "cruises": true, "csc": true, "cuisinella": true, "cymru": true, "cyou": true, "dabur": true, "dad": true, "dance": true, "data": true, "date": true, "dating": true, "datsun": true, "day": true, "dclk": true, "dds": true, "deal": true, "dealer": true, "deals": true, "degree": true, "delivery": true, "dell": true, "deloitte": true, "delta": true, "democrat": true, "dental": true, "dentist": true, "desi": true, "design": true, "dev": true, "dhl": true, "diamonds": true, "diet": true, "digital": true, "direct": true, "directory": true, "discount": true, "discover": true, "dish": true, "diy": true, "dnp": true, "docs": true, "doctor": true, "dodge": true, "dog": true, "doha": true, "domains": true, "dot": true, "download": true, "drive": true, "dtv": true, "dubai": true, "duck": true, "dunlop": true, "duns": true, "dupont": true, "durban": true, "dvag": true, "dvr": true, "dwg": true, "earth": true, "eat": true, "eco": true, "edeka": true, "education": true, "email": true, "emerck": true, "emerson": true, "energy": true, "engineer": true, "engineering": true, "enterprises": true, "epost": true, "epson": true, "equipment": true, "ericsson": true, "erni": true, "esq": true, "estate": true, "esurance": true, "etisalat": true, "eurovision": true, "eus": true, "events": true, "everbank": true, "exchange": true, "expert": true, "exposed": true, "express": true, "extraspace": true, "fage": true, "fail": true, "fairwinds": true, "faith": true, "family": true, "fan": true, "fans": true, "farm": true, "farmers": true, "fashion": true, "fast": true, "fedex": true, "feedback": true, "ferrari": true, "ferrero": true, "fiat": true, "fidelity": true, "fido": true, "film": true, "final": true, "finance": true, "financial": true, "fire": true, "firestone": true, "firmdale": true, "fish": true, "fishing": true, "fit": true, "fitness": true, "flickr": true, "flights": true, "flir": true, "florist": true, "flowers": true, "fly": true, "foo": true, "food": true, "foodnetwork": true, "football": true, "ford": true, "forex": true, "forsale": true, "forum": true, "foundation": true, "fox": true, "free": true, "fresenius": true, "frl": true, "frogans": true, "frontdoor": true, "frontier": true, "ftr": true, "fujitsu": true, "fujixerox": true, "fun": true, "fund": true, "furniture": true, "futbol": true, "fyi": true, "gal": true, "gallery": true, "gallo": true, "gallup": true, "game": true, "games": true, "gap": true, "garden": true, "gbiz": true, "gdn": true, "gea": true, "gent": true, "genting": true, "george": true, "ggee": true, "gift": true, "gifts": true, "gives": true, "giving": true, "glade": true, "glass": true, "gle": true, "global": true, "globo": true, "gmail": true, "gmbh": true, "gmo": true, "gmx": true, "godaddy": true, "gold": true, "goldpoint": true, "golf": true, "goo": true, "goodhands": true, "goodyear": true, "goog": true, "google": true, "gop": true, "got": true, "grainger": true, "graphics": true, "gratis": true, "green": true, "gripe": true, "grocery": true, "group": true, "guardian": true, "gucci": true, "guge": true, "guide": true, "guitars": true, "guru": true, "hair": true, "hamburg": true, "hangout": true, "haus": true, "hbo": true, "hdfc": true, "hdfcbank": true, "health": true, "healthcare": true, "help": true, "helsinki": true, "here": true, "hermes": true, "hgtv": true, "hiphop": true, "hisamitsu": true, "hitachi": true, "hiv": true, "hkt": true, "hockey": true, "holdings": true, "holiday": true, "homedepot": true, "homegoods": true, "homes": true, "homesense": true, "honda": true, "honeywell": true, "horse": true, "host": true, "hosting": true, "hot": true, "hoteles": true, "hotels": true, "hotmail": true, "house": true, "how": true, "hsbc": true, "htc": true, "hughes": true, "hyatt": true, "hyundai": true, "ibm": true, "icbc": true, "ice": true, "icu": true, "ieee": true, "ifm": true, "iinet": true, "ikano": true, "imamat": true, "imdb": true, "immo": true, "immobilien": true, "industries": true, "infiniti": true, "ing": true, "ink": true, "institute": true, "insurance": true, "insure": true, "intel": true, "international": true, "intuit": true, "investments": true, "ipiranga": true, "irish": true, "iselect": true, "ismaili": true, "ist": true, "istanbul": true, "itau": true, "itv": true, "iveco": true, "iwc": true, "jaguar": true, "java": true, "jcb": true, "jcp": true, "jeep": true, "jetzt": true, "jewelry": true, "jio": true, "jlc": true, "jll": true, "jmp": true, "jnj": true, "joburg": true, "jot": true, "joy": true, "jpmorgan": true, "jprs": true, "juegos": true, "juniper": true, "kaufen": true, "kddi": true, "kerryhotels": true, "kerrylogistics": true, "kerryproperties": true, "kfh": true, "kia": true, "kim": true, "kinder": true, "kindle": true, "kitchen": true, "kiwi": true, "koeln": true, "komatsu": true, "kosher": true, "kpmg": true, "kpn": true, "krd": true, "kred": true, "kuokgroup": true, "kyoto": true, "lacaixa": true, "ladbrokes": true, "lamborghini": true, "lamer": true, "lancaster": true, "lancia": true, "lancome": true, "land": true, "landrover": true, "lanxess": true, "lasalle": true, "lat": true, "latino": true, "latrobe": true, "law": true, "lawyer": true, "lds": true, "lease": true, "leclerc": true, "lefrak": true, "legal": true, "lego": true, "lexus": true, "lgbt": true, "liaison": true, "lidl": true, "life": true, "lifeinsurance": true, "lifestyle": true, "lighting": true, "like": true, "lilly": true, "limited": true, "limo": true, "lincoln": true, "linde": true, "link": true, "lipsy": true, "live": true, "living": true, "lixil": true, "loan": true, "loans": true, "locker": true, "locus": true, "loft": true, "lol": true, "london": true, "lotte": true, "lotto": true, "love": true, "lpl": true, "lplfinancial": true, "ltd": true, "ltda": true, "lundbeck": true, "lupin": true, "luxe": true, "luxury": true, "macys": true, "madrid": true, "maif": true, "maison": true, "makeup": true, "man": true, "management": true, "mango": true, "map": true, "market": true, "marketing": true, "markets": true, "marriott": true, "marshalls": true, "maserati": true, "mattel": true, "mba": true, "mcd": true, "mcdonalds": true, "mckinsey": true, "med": true, "media": true, "meet": true, "melbourne": true, "meme": true, "memorial": true, "men": true, "menu": true, "meo": true, "merckmsd": true, "metlife": true, "miami": true, "microsoft": true, "mini": true, "mint": true, "mit": true, "mitsubishi": true, "mlb": true, "mls": true, "mma": true, "mobile": true, "mobily": true, "moda": true, "moe": true, "moi": true, "mom": true, "monash": true, "money": true, "monster": true, "montblanc": true, "mopar": true, "mormon": true, "mortgage": true, "moscow": true, "moto": true, "motorcycles": true, "mov": true, "movie": true, "movistar": true, "msd": true, "mtn": true, "mtpc": true, "mtr": true, "mutual": true, "mutuelle": true, "nab": true, "nadex": true, "nagoya": true, "nationwide": true, "natura": true, "navy": true, "nba": true, "nec": true, "netbank": true, "netflix": true, "network": true, "neustar": true, "new": true, "newholland": true, "news": true, "next": true, "nextdirect": true, "nexus": true, "nfl": true, "ngo": true, "nhk": true, "nico": true, "nike": true, "nikon": true, "ninja": true, "nissan": true, "nissay": true, "nokia": true, "northwesternmutual": true, "norton": true, "now": true, "nowruz": true, "nowtv": true, "nra": true, "nrw": true, "ntt": true, "nyc": true, "obi": true, "observer": true, "off": true, "office": true, "okinawa": true, "olayan": true, "olayangroup": true, "oldnavy": true, "ollo": true, "omega": true, "one": true, "ong": true, "onl": true, "online": true, "onyourside": true, "ooo": true, "open": true, "oracle": true, "orange": true, "organic": true, "orientexpress": true, "origins": true, "osaka": true, "otsuka": true, "ott": true, "ovh": true, "page": true, "pamperedchef": true, "panasonic": true, "panerai": true, "paris": true, "pars": true, "partners": true, "parts": true, "party": true, "passagens": true, "pay": true, "pccw": true, "pet": true, "pfizer": true, "pharmacy": true, "phd": true, "philips": true, "phone": true, "photo": true, "photography": true, "photos": true, "physio": true, "piaget": true, "pics": true, "pictet": true, "pictures": true, "pid": true, "pin": true, "ping": true, "pink": true, "pioneer": true, "pizza": true, "place": true, "play": true, "playstation": true, "plumbing": true, "plus": true, "pnc": true, "pohl": true, "poker": true, "politie": true, "porn": true, "pramerica": true, "praxi": true, "press": true, "prime": true, "prod": true, "productions": true, "prof": true, "progressive": true, "promo": true, "properties": true, "property": true, "protection": true, "pru": true, "prudential": true, "pub": true, "pwc": true, "qpon": true, "quebec": true, "quest": true, "qvc": true, "racing": true, "radio": true, "raid": true, "read": true, "realestate": true, "realtor": true, "realty": true, "recipes": true, "red": true, "redstone": true, "redumbrella": true, "rehab": true, "reise": true, "reisen": true, "reit": true, "reliance": true, "ren": true, "rent": true, "rentals": true, "repair": true, "report": true, "republican": true, "rest": true, "restaurant": true, "review": true, "reviews": true, "rexroth": true, "rich": true, "richardli": true, "ricoh": true, "rightathome": true, "ril": true, "rio": true, "rip": true, "rmit": true, "rocher": true, "rocks": true, "rodeo": true, "rogers": true, "room": true, "rsvp": true, "ruhr": true, "run": true, "rwe": true, "ryukyu": true, "saarland": true, "safe": true, "safety": true, "sakura": true, "sale": true, "salon": true, "samsclub": true, "samsung": true, "sandvik": true, "sandvikcoromant": true, "sanofi": true, "sap": true, "sapo": true, "sarl": true, "sas": true, "save": true, "saxo": true, "sbi": true, "sbs": true, "sca": true, "scb": true, "schaeffler": true, "schmidt": true, "scholarships": true, "school": true, "schule": true, "schwarz": true, "science": true, "scjohnson": true, "scor": true, "scot": true, "search": true, "seat": true, "secure": true, "security": true, "seek": true, "select": true, "sener": true, "services": true, "ses": true, "seven": true, "sew": true, "sex": true, "sexy": true, "sfr": true, "shangrila": true, "sharp": true, "shaw": true, "shell": true, "shia": true, "shiksha": true, "shoes": true, "shop": true, "shopping": true, "shouji": true, "show": true, "showtime": true, "shriram": true, "silk": true, "sina": true, "singles": true, "site": true, "ski": true, "skin": true, "sky": true, "skype": true, "sling": true, "smart": true, "smile": true, "sncf": true, "soccer": true, "social": true, "softbank": true, "software": true, "sohu": true, "solar": true, "solutions": true, "song": true, "sony": true, "soy": true, "space": true, "spiegel": true, "spot": true, "spreadbetting": true, "srl": true, "srt": true, "stada": true, "staples": true, "star": true, "starhub": true, "statebank": true, "statefarm": true, "statoil": true, "stc": true, "stcgroup": true, "stockholm": true, "storage": true, "store": true, "stream": true, "studio": true, "study": true, "style": true, "sucks": true, "supplies": true, "supply": true, "support": true, "surf": true, "surgery": true, "suzuki": true, "swatch": true, "swiftcover": true, "swiss": true, "sydney": true, "symantec": true, "systems": true, "tab": true, "taipei": true, "talk": true, "taobao": true, "target": true, "tatamotors": true, "tatar": true, "tattoo": true, "tax": true, "taxi": true, "tci": true, "tdk": true, "team": true, "tech": true, "technology": true, "telecity": true, "telefonica": true, "temasek": true, "tennis": true, "teva": true, "thd": true, "theater": true, "theatre": true, "theguardian": true, "tiaa": true, "tickets": true, "tienda": true, "tiffany": true, "tips": true, "tires": true, "tirol": true, "tjmaxx": true, "tjx": true, "tkmaxx": true, "tmall": true, "today": true, "tokyo": true, "tools": true, "top": true, "toray": true, "toshiba": true, "total": true, "tours": true, "town": true, "toyota": true, "toys": true, "trade": true, "trading": true, "training": true, "travelchannel": true, "travelers": true, "travelersinsurance": true, "trust": true, "trv": true, "tube": true, "tui": true, "tunes": true, "tushu": true, "tvs": true, "ubank": true, "ubs": true, "uconnect": true, "unicom": true, "university": true, "uno": true, "uol": true, "ups": true, "vacations": true, "vana": true, "vanguard": true, "vegas": true, "ventures": true, "verisign": true, "versicherung": true, "vet": true, "viajes": true, "video": true, "vig": true, "viking": true, "villas": true, "vin": true, "vip": true, "virgin": true, "visa": true, "vision": true, "vista": true, "vistaprint": true, "viva": true, "vivo": true, "vlaanderen": true, "vodka": true, "volkswagen": true, "volvo": true, "vote": true, "voting": true, "voto": true, "voyage": true, "vuelos": true, "wales": true, "walmart": true, "walter": true, "wang": true, "wanggou": true, "warman": true, "watch": true, "watches": true, "weather": true, "weatherchannel": true, "webcam": true, "weber": true, "website": true, "wed": true, "wedding": true, "weibo": true, "weir": true, "whoswho": true, "wien": true, "wiki": true, "williamhill": true, "win": true, "windows": true, "wine": true, "winners": true, "wme": true, "wolterskluwer": true, "woodside": true, "work": true, "works": true, "world": true, "wow": true, "wtc": true, "wtf": true, "xbox": true, "xerox": true, "xfinity": true, "xihuan": true, "xin": true, "xn--11b4c3d": true, "xn--1ck2e1b": true, "xn--1qqw23a": true, "xn--30rr7y": true, "xn--3bst00m": true, "xn--3ds443g": true, "xn--3oq18vl8pn36a": true, "xn--3pxu8k": true, "xn--42c2d9a": true, "xn--45q11c": true, "xn--4gbrim": true, "xn--4gq48lf9j": true, "xn--55qw42g": true, "xn--55qx5d": true, "xn--5su34j936bgsg": true, "xn--5tzm5g": true, "xn--6frz82g": true, "xn--6qq986b3xl": true, "xn--80adxhks": true, "xn--80aqecdr1a": true, "xn--80asehdb": true, "xn--80aswg": true, "xn--8y0a063a": true, "xn--9dbq2a": true, "xn--9et52u": true, "xn--9krt00a": true, "xn--b4w605ferd": true, "xn--bck1b9a5dre4c": true, "xn--c1avg": true, "xn--c2br7g": true, "xn--cck2b3b": true, "xn--cg4bki": true, "xn--czr694b": true, "xn--czrs0t": true, "xn--czru2d": true, "xn--d1acj3b": true, "xn--eckvdtc9d": true, "xn--efvy88h": true, "xn--estv75g": true, "xn--fct429k": true, "xn--fhbei": true, "xn--fiq228c5hs": true, "xn--fiq64b": true, "xn--fjq720a": true, "xn--flw351e": true, "xn--fzys8d69uvgm": true, "xn--g2xx48c": true, "xn--gckr3f0f": true, "xn--gk3at1e": true, "xn--hxt814e": true, "xn--i1b6b1a6a2e": true, "xn--imr513n": true, "xn--io0a7i": true, "xn--j1aef": true, "xn--jlq61u9w7b": true, "xn--jvr189m": true, "xn--kcrx77d1x4a": true, "xn--kpu716f": true, "xn--kput3i": true, "xn--mgba3a3ejt": true, "xn--mgba7c0bbn0a": true, "xn--mgbaakc7dvf": true, "xn--mgbab2bd": true, "xn--mgbb9fbpob": true, "xn--mgbca7dzdo": true, "xn--mgbi4ecexp": true, "xn--mgbt3dhd": true, "xn--mk1bu44c": true, "xn--mxtq1m": true, "xn--ngbc5azd": true, "xn--ngbe9e0a": true, "xn--ngbrx": true, "xn--nqv7f": true, "xn--nqv7fs00ema": true, "xn--nyqy26a": true, "xn--p1acf": true, "xn--pbt977c": true, "xn--pssy2u": true, "xn--q9jyb4c": true, "xn--qcka1pmc": true, "xn--rhqv96g": true, "xn--rovu88b": true, "xn--ses554g": true, "xn--t60b56a": true, "xn--tckwe": true, "xn--tiq49xqyj": true, "xn--unup4y": true, "xn--vermgensberater-ctb": true, "xn--vermgensberatung-pwb": true, "xn--vhquv": true, "xn--vuq861b": true, "xn--w4r85el8fhu5dnra": true, "xn--w4rs40l": true, "xn--xhq521b": true, "xn--zfr164b": true, "xperia": true, "xyz": true, "yachts": true, "yahoo": true, "yamaxun": true, "yandex": true, "yodobashi": true, "yoga": true, "yokohama": true, "you": true, "youtube": true, "yun": true, "zappos": true, "zara": true, "zero": true, "zip": true, "zippo": true, "zone": true, "zuerich": true, "beep.pl": true, "*.compute.estate": true, "*.alces.network": true, "*.alwaysdata.net": true, "cloudfront.net": true, "compute.amazonaws.com": true, "ap-northeast-1.compute.amazonaws.com": true, "ap-northeast-2.compute.amazonaws.com": true, "ap-southeast-1.compute.amazonaws.com": true, "ap-southeast-2.compute.amazonaws.com": true, "eu-central-1.compute.amazonaws.com": true, "eu-west-1.compute.amazonaws.com": true, "sa-east-1.compute.amazonaws.com": true, "us-gov-west-1.compute.amazonaws.com": true, "us-west-1.compute.amazonaws.com": true, "us-west-2.compute.amazonaws.com": true, "compute-1.amazonaws.com": true, "z-1.compute-1.amazonaws.com": true, "z-2.compute-1.amazonaws.com": true, "us-east-1.amazonaws.com": true, "compute.amazonaws.com.cn": true, "cn-north-1.compute.amazonaws.com.cn": true, "elasticbeanstalk.com": true, "elb.amazonaws.com": true, "s3.amazonaws.com": true, "s3-ap-northeast-1.amazonaws.com": true, "s3-ap-northeast-2.amazonaws.com": true, "s3-ap-southeast-1.amazonaws.com": true, "s3-ap-southeast-2.amazonaws.com": true, "s3-eu-central-1.amazonaws.com": true, "s3-eu-west-1.amazonaws.com": true, "s3-external-1.amazonaws.com": true, "s3-external-2.amazonaws.com": true, "s3-fips-us-gov-west-1.amazonaws.com": true, "s3-sa-east-1.amazonaws.com": true, "s3-us-gov-west-1.amazonaws.com": true, "s3-us-west-1.amazonaws.com": true, "s3-us-west-2.amazonaws.com": true, "s3.ap-northeast-2.amazonaws.com": true, "s3.cn-north-1.amazonaws.com.cn": true, "s3.eu-central-1.amazonaws.com": true, "on-aptible.com": true, "pimienta.org": true, "poivron.org": true, "potager.org": true, "sweetpepper.org": true, "myasustor.com": true, "myfritz.net": true, "backplaneapp.io": true, "betainabox.com": true, "bnr.la": true, "boxfuse.io": true, "browsersafetymark.io": true, "mycd.eu": true, "ae.org": true, "ar.com": true, "br.com": true, "cn.com": true, "com.de": true, "com.se": true, "de.com": true, "eu.com": true, "gb.com": true, "gb.net": true, "hu.com": true, "hu.net": true, "jp.net": true, "jpn.com": true, "kr.com": true, "mex.com": true, "no.com": true, "qc.com": true, "ru.com": true, "sa.com": true, "se.com": true, "se.net": true, "uk.com": true, "uk.net": true, "us.com": true, "uy.com": true, "za.bz": true, "za.com": true, "africa.com": true, "gr.com": true, "in.net": true, "us.org": true, "co.com": true, "c.la": true, "certmgr.org": true, "xenapponazure.com": true, "virtueeldomein.nl": true, "cloudcontrolled.com": true, "cloudcontrolapp.com": true, "co.ca": true, "co.cz": true, "c.cdn77.org": true, "cdn77-ssl.net": true, "r.cdn77.net": true, "rsc.cdn77.org": true, "ssl.origin.cdn77-secure.org": true, "cloudns.asia": true, "cloudns.biz": true, "cloudns.club": true, "cloudns.cc": true, "cloudns.eu": true, "cloudns.in": true, "cloudns.info": true, "cloudns.org": true, "cloudns.pro": true, "cloudns.pw": true, "cloudns.us": true, "co.nl": true, "co.no": true, "*.platform.sh": true, "realm.cz": true, "*.cryptonomic.net": true, "cupcake.is": true, "cyon.link": true, "cyon.site": true, "daplie.me": true, "biz.dk": true, "co.dk": true, "firm.dk": true, "reg.dk": true, "store.dk": true, "dedyn.io": true, "dnshome.de": true, "dreamhosters.com": true, "mydrobo.com": true, "drud.io": true, "drud.us": true, "duckdns.org": true, "dy.fi": true, "tunk.org": true, "dyndns-at-home.com": true, "dyndns-at-work.com": true, "dyndns-blog.com": true, "dyndns-free.com": true, "dyndns-home.com": true, "dyndns-ip.com": true, "dyndns-mail.com": true, "dyndns-office.com": true, "dyndns-pics.com": true, "dyndns-remote.com": true, "dyndns-server.com": true, "dyndns-web.com": true, "dyndns-wiki.com": true, "dyndns-work.com": true, "dyndns.biz": true, "dyndns.info": true, "dyndns.org": true, "dyndns.tv": true, "at-band-camp.net": true, "ath.cx": true, "barrel-of-knowledge.info": true, "barrell-of-knowledge.info": true, "better-than.tv": true, "blogdns.com": true, "blogdns.net": true, "blogdns.org": true, "blogsite.org": true, "boldlygoingnowhere.org": true, "broke-it.net": true, "buyshouses.net": true, "cechire.com": true, "dnsalias.com": true, "dnsalias.net": true, "dnsalias.org": true, "dnsdojo.com": true, "dnsdojo.net": true, "dnsdojo.org": true, "does-it.net": true, "doesntexist.com": true, "doesntexist.org": true, "dontexist.com": true, "dontexist.net": true, "dontexist.org": true, "doomdns.com": true, "doomdns.org": true, "dvrdns.org": true, "dyn-o-saur.com": true, "dynalias.com": true, "dynalias.net": true, "dynalias.org": true, "dynathome.net": true, "dyndns.ws": true, "endofinternet.net": true, "endofinternet.org": true, "endoftheinternet.org": true, "est-a-la-maison.com": true, "est-a-la-masion.com": true, "est-le-patron.com": true, "est-mon-blogueur.com": true, "for-better.biz": true, "for-more.biz": true, "for-our.info": true, "for-some.biz": true, "for-the.biz": true, "forgot.her.name": true, "forgot.his.name": true, "from-ak.com": true, "from-al.com": true, "from-ar.com": true, "from-az.net": true, "from-ca.com": true, "from-co.net": true, "from-ct.com": true, "from-dc.com": true, "from-de.com": true, "from-fl.com": true, "from-ga.com": true, "from-hi.com": true, "from-ia.com": true, "from-id.com": true, "from-il.com": true, "from-in.com": true, "from-ks.com": true, "from-ky.com": true, "from-la.net": true, "from-ma.com": true, "from-md.com": true, "from-me.org": true, "from-mi.com": true, "from-mn.com": true, "from-mo.com": true, "from-ms.com": true, "from-mt.com": true, "from-nc.com": true, "from-nd.com": true, "from-ne.com": true, "from-nh.com": true, "from-nj.com": true, "from-nm.com": true, "from-nv.com": true, "from-ny.net": true, "from-oh.com": true, "from-ok.com": true, "from-or.com": true, "from-pa.com": true, "from-pr.com": true, "from-ri.com": true, "from-sc.com": true, "from-sd.com": true, "from-tn.com": true, "from-tx.com": true, "from-ut.com": true, "from-va.com": true, "from-vt.com": true, "from-wa.com": true, "from-wi.com": true, "from-wv.com": true, "from-wy.com": true, "ftpaccess.cc": true, "fuettertdasnetz.de": true, "game-host.org": true, "game-server.cc": true, "getmyip.com": true, "gets-it.net": true, "go.dyndns.org": true, "gotdns.com": true, "gotdns.org": true, "groks-the.info": true, "groks-this.info": true, "ham-radio-op.net": true, "here-for-more.info": true, "hobby-site.com": true, "hobby-site.org": true, "home.dyndns.org": true, "homedns.org": true, "homeftp.net": true, "homeftp.org": true, "homeip.net": true, "homelinux.com": true, "homelinux.net": true, "homelinux.org": true, "homeunix.com": true, "homeunix.net": true, "homeunix.org": true, "iamallama.com": true, "in-the-band.net": true, "is-a-anarchist.com": true, "is-a-blogger.com": true, "is-a-bookkeeper.com": true, "is-a-bruinsfan.org": true, "is-a-bulls-fan.com": true, "is-a-candidate.org": true, "is-a-caterer.com": true, "is-a-celticsfan.org": true, "is-a-chef.com": true, "is-a-chef.net": true, "is-a-chef.org": true, "is-a-conservative.com": true, "is-a-cpa.com": true, "is-a-cubicle-slave.com": true, "is-a-democrat.com": true, "is-a-designer.com": true, "is-a-doctor.com": true, "is-a-financialadvisor.com": true, "is-a-geek.com": true, "is-a-geek.net": true, "is-a-geek.org": true, "is-a-green.com": true, "is-a-guru.com": true, "is-a-hard-worker.com": true, "is-a-hunter.com": true, "is-a-knight.org": true, "is-a-landscaper.com": true, "is-a-lawyer.com": true, "is-a-liberal.com": true, "is-a-libertarian.com": true, "is-a-linux-user.org": true, "is-a-llama.com": true, "is-a-musician.com": true, "is-a-nascarfan.com": true, "is-a-nurse.com": true, "is-a-painter.com": true, "is-a-patsfan.org": true, "is-a-personaltrainer.com": true, "is-a-photographer.com": true, "is-a-player.com": true, "is-a-republican.com": true, "is-a-rockstar.com": true, "is-a-socialist.com": true, "is-a-soxfan.org": true, "is-a-student.com": true, "is-a-teacher.com": true, "is-a-techie.com": true, "is-a-therapist.com": true, "is-an-accountant.com": true, "is-an-actor.com": true, "is-an-actress.com": true, "is-an-anarchist.com": true, "is-an-artist.com": true, "is-an-engineer.com": true, "is-an-entertainer.com": true, "is-by.us": true, "is-certified.com": true, "is-found.org": true, "is-gone.com": true, "is-into-anime.com": true, "is-into-cars.com": true, "is-into-cartoons.com": true, "is-into-games.com": true, "is-leet.com": true, "is-lost.org": true, "is-not-certified.com": true, "is-saved.org": true, "is-slick.com": true, "is-uberleet.com": true, "is-very-bad.org": true, "is-very-evil.org": true, "is-very-good.org": true, "is-very-nice.org": true, "is-very-sweet.org": true, "is-with-theband.com": true, "isa-geek.com": true, "isa-geek.net": true, "isa-geek.org": true, "isa-hockeynut.com": true, "issmarterthanyou.com": true, "isteingeek.de": true, "istmein.de": true, "kicks-ass.net": true, "kicks-ass.org": true, "knowsitall.info": true, "land-4-sale.us": true, "lebtimnetz.de": true, "leitungsen.de": true, "likes-pie.com": true, "likescandy.com": true, "merseine.nu": true, "mine.nu": true, "misconfused.org": true, "mypets.ws": true, "myphotos.cc": true, "neat-url.com": true, "office-on-the.net": true, "on-the-web.tv": true, "podzone.net": true, "podzone.org": true, "readmyblog.org": true, "saves-the-whales.com": true, "scrapper-site.net": true, "scrapping.cc": true, "selfip.biz": true, "selfip.com": true, "selfip.info": true, "selfip.net": true, "selfip.org": true, "sells-for-less.com": true, "sells-for-u.com": true, "sells-it.net": true, "sellsyourhome.org": true, "servebbs.com": true, "servebbs.net": true, "servebbs.org": true, "serveftp.net": true, "serveftp.org": true, "servegame.org": true, "shacknet.nu": true, "simple-url.com": true, "space-to-rent.com": true, "stuff-4-sale.org": true, "stuff-4-sale.us": true, "teaches-yoga.com": true, "thruhere.net": true, "traeumtgerade.de": true, "webhop.biz": true, "webhop.info": true, "webhop.net": true, "webhop.org": true, "worse-than.tv": true, "writesthisblog.com": true, "ddnss.de": true, "dyn.ddnss.de": true, "dyndns.ddnss.de": true, "dyndns1.de": true, "dyn-ip24.de": true, "home-webserver.de": true, "dyn.home-webserver.de": true, "myhome-server.de": true, "ddnss.org": true, "dynv6.net": true, "e4.cz": true, "eu.org": true, "al.eu.org": true, "asso.eu.org": true, "at.eu.org": true, "au.eu.org": true, "be.eu.org": true, "bg.eu.org": true, "ca.eu.org": true, "cd.eu.org": true, "ch.eu.org": true, "cn.eu.org": true, "cy.eu.org": true, "cz.eu.org": true, "de.eu.org": true, "dk.eu.org": true, "edu.eu.org": true, "ee.eu.org": true, "es.eu.org": true, "fi.eu.org": true, "fr.eu.org": true, "gr.eu.org": true, "hr.eu.org": true, "hu.eu.org": true, "ie.eu.org": true, "il.eu.org": true, "in.eu.org": true, "int.eu.org": true, "is.eu.org": true, "it.eu.org": true, "jp.eu.org": true, "kr.eu.org": true, "lt.eu.org": true, "lu.eu.org": true, "lv.eu.org": true, "mc.eu.org": true, "me.eu.org": true, "mk.eu.org": true, "mt.eu.org": true, "my.eu.org": true, "net.eu.org": true, "ng.eu.org": true, "nl.eu.org": true, "no.eu.org": true, "nz.eu.org": true, "paris.eu.org": true, "pl.eu.org": true, "pt.eu.org": true, "q-a.eu.org": true, "ro.eu.org": true, "ru.eu.org": true, "se.eu.org": true, "si.eu.org": true, "sk.eu.org": true, "tr.eu.org": true, "uk.eu.org": true, "us.eu.org": true, "eu-1.evennode.com": true, "eu-2.evennode.com": true, "us-1.evennode.com": true, "us-2.evennode.com": true, "apps.fbsbx.com": true, "a.ssl.fastly.net": true, "b.ssl.fastly.net": true, "global.ssl.fastly.net": true, "a.prod.fastly.net": true, "global.prod.fastly.net": true, "fhapp.xyz": true, "firebaseapp.com": true, "flynnhub.com": true, "freebox-os.com": true, "freeboxos.com": true, "fbx-os.fr": true, "fbxos.fr": true, "freebox-os.fr": true, "freeboxos.fr": true, "myfusion.cloud": true, "futuremailing.at": true, "*.ex.ortsinfo.at": true, "*.kunden.ortsinfo.at": true, "service.gov.uk": true, "github.io": true, "githubusercontent.com": true, "githubcloud.com": true, "*.api.githubcloud.com": true, "*.ext.githubcloud.com": true, "gist.githubcloud.com": true, "*.githubcloudusercontent.com": true, "gitlab.io": true, "ro.com": true, "ro.im": true, "shop.ro": true, "goip.de": true, "*.0emm.com": true, "appspot.com": true, "blogspot.ae": true, "blogspot.al": true, "blogspot.am": true, "blogspot.ba": true, "blogspot.be": true, "blogspot.bg": true, "blogspot.bj": true, "blogspot.ca": true, "blogspot.cf": true, "blogspot.ch": true, "blogspot.cl": true, "blogspot.co.at": true, "blogspot.co.id": true, "blogspot.co.il": true, "blogspot.co.ke": true, "blogspot.co.nz": true, "blogspot.co.uk": true, "blogspot.co.za": true, "blogspot.com": true, "blogspot.com.ar": true, "blogspot.com.au": true, "blogspot.com.br": true, "blogspot.com.by": true, "blogspot.com.co": true, "blogspot.com.cy": true, "blogspot.com.ee": true, "blogspot.com.eg": true, "blogspot.com.es": true, "blogspot.com.mt": true, "blogspot.com.ng": true, "blogspot.com.tr": true, "blogspot.com.uy": true, "blogspot.cv": true, "blogspot.cz": true, "blogspot.de": true, "blogspot.dk": true, "blogspot.fi": true, "blogspot.fr": true, "blogspot.gr": true, "blogspot.hk": true, "blogspot.hr": true, "blogspot.hu": true, "blogspot.ie": true, "blogspot.in": true, "blogspot.is": true, "blogspot.it": true, "blogspot.jp": true, "blogspot.kr": true, "blogspot.li": true, "blogspot.lt": true, "blogspot.lu": true, "blogspot.md": true, "blogspot.mk": true, "blogspot.mr": true, "blogspot.mx": true, "blogspot.my": true, "blogspot.nl": true, "blogspot.no": true, "blogspot.pe": true, "blogspot.pt": true, "blogspot.qa": true, "blogspot.re": true, "blogspot.ro": true, "blogspot.rs": true, "blogspot.ru": true, "blogspot.se": true, "blogspot.sg": true, "blogspot.si": true, "blogspot.sk": true, "blogspot.sn": true, "blogspot.td": true, "blogspot.tw": true, "blogspot.ug": true, "blogspot.vn": true, "cloudfunctions.net": true, "codespot.com": true, "googleapis.com": true, "googlecode.com": true, "pagespeedmobilizer.com": true, "publishproxy.com": true, "withgoogle.com": true, "withyoutube.com": true, "hashbang.sh": true, "hasura-app.io": true, "hepforge.org": true, "herokuapp.com": true, "herokussl.com": true, "iki.fi": true, "biz.at": true, "info.at": true, "ac.leg.br": true, "al.leg.br": true, "am.leg.br": true, "ap.leg.br": true, "ba.leg.br": true, "ce.leg.br": true, "df.leg.br": true, "es.leg.br": true, "go.leg.br": true, "ma.leg.br": true, "mg.leg.br": true, "ms.leg.br": true, "mt.leg.br": true, "pa.leg.br": true, "pb.leg.br": true, "pe.leg.br": true, "pi.leg.br": true, "pr.leg.br": true, "rj.leg.br": true, "rn.leg.br": true, "ro.leg.br": true, "rr.leg.br": true, "rs.leg.br": true, "sc.leg.br": true, "se.leg.br": true, "sp.leg.br": true, "to.leg.br": true, "*.triton.zone": true, "*.cns.joyent.com": true, "js.org": true, "keymachine.de": true, "knightpoint.systems": true, "co.krd": true, "edu.krd": true, "*.magentosite.cloud": true, "meteorapp.com": true, "eu.meteorapp.com": true, "co.pl": true, "azurewebsites.net": true, "azure-mobile.net": true, "cloudapp.net": true, "bmoattachments.org": true, "4u.com": true, "ngrok.io": true, "nfshost.com": true, "nsupdate.info": true, "nerdpol.ovh": true, "blogsyte.com": true, "brasilia.me": true, "cable-modem.org": true, "ciscofreak.com": true, "collegefan.org": true, "couchpotatofries.org": true, "damnserver.com": true, "ddns.me": true, "ditchyourip.com": true, "dnsfor.me": true, "dnsiskinky.com": true, "dvrcam.info": true, "dynns.com": true, "eating-organic.net": true, "fantasyleague.cc": true, "geekgalaxy.com": true, "golffan.us": true, "health-carereform.com": true, "homesecuritymac.com": true, "homesecuritypc.com": true, "hopto.me": true, "ilovecollege.info": true, "loginto.me": true, "mlbfan.org": true, "mmafan.biz": true, "myactivedirectory.com": true, "mydissent.net": true, "myeffect.net": true, "mymediapc.net": true, "mypsx.net": true, "mysecuritycamera.com": true, "mysecuritycamera.net": true, "mysecuritycamera.org": true, "net-freaks.com": true, "nflfan.org": true, "nhlfan.net": true, "no-ip.ca": true, "no-ip.co.uk": true, "no-ip.net": true, "noip.us": true, "onthewifi.com": true, "pgafan.net": true, "point2this.com": true, "pointto.us": true, "privatizehealthinsurance.net": true, "quicksytes.com": true, "read-books.org": true, "securitytactics.com": true, "serveexchange.com": true, "servehumour.com": true, "servep2p.com": true, "servesarcasm.com": true, "stufftoread.com": true, "ufcfan.org": true, "unusualperson.com": true, "workisboring.com": true, "3utilities.com": true, "bounceme.net": true, "ddns.net": true, "ddnsking.com": true, "gotdns.ch": true, "hopto.org": true, "myftp.biz": true, "myftp.org": true, "myvnc.com": true, "no-ip.biz": true, "no-ip.info": true, "no-ip.org": true, "noip.me": true, "redirectme.net": true, "servebeer.com": true, "serveblog.net": true, "servecounterstrike.com": true, "serveftp.com": true, "servegame.com": true, "servehalflife.com": true, "servehttp.com": true, "serveirc.com": true, "serveminecraft.net": true, "servemp3.com": true, "servepics.com": true, "servequake.com": true, "sytes.net": true, "webhop.me": true, "zapto.org": true, "nyc.mn": true, "nid.io": true, "opencraft.hosting": true, "operaunite.com": true, "outsystemscloud.com": true, "ownprovider.com": true, "oy.lc": true, "pgfog.com": true, "pagefrontapp.com": true, "art.pl": true, "gliwice.pl": true, "krakow.pl": true, "poznan.pl": true, "wroc.pl": true, "zakopane.pl": true, "pantheonsite.io": true, "gotpantheon.com": true, "mypep.link": true, "xen.prgmr.com": true, "priv.at": true, "protonet.io": true, "chirurgiens-dentistes-en-france.fr": true, "qa2.com": true, "dev-myqnapcloud.com": true, "alpha-myqnapcloud.com": true, "myqnapcloud.com": true, "rackmaze.com": true, "rackmaze.net": true, "rhcloud.com": true, "hzc.io": true, "wellbeingzone.eu": true, "ptplus.fit": true, "wellbeingzone.co.uk": true, "sandcats.io": true, "logoip.de": true, "logoip.com": true, "firewall-gateway.com": true, "firewall-gateway.de": true, "my-gateway.de": true, "my-router.de": true, "spdns.de": true, "spdns.eu": true, "firewall-gateway.net": true, "my-firewall.org": true, "myfirewall.org": true, "spdns.org": true, "biz.ua": true, "co.ua": true, "pp.ua": true, "shiftedit.io": true, "myshopblocks.com": true, "1kapp.com": true, "appchizi.com": true, "applinzi.com": true, "sinaapp.com": true, "vipsinaapp.com": true, "bounty-full.com": true, "alpha.bounty-full.com": true, "beta.bounty-full.com": true, "static.land": true, "dev.static.land": true, "sites.static.land": true, "apps.lair.io": true, "*.stolos.io": true, "spacekit.io": true, "stackspace.space": true, "diskstation.me": true, "dscloud.biz": true, "dscloud.me": true, "dscloud.mobi": true, "dsmynas.com": true, "dsmynas.net": true, "dsmynas.org": true, "familyds.com": true, "familyds.net": true, "familyds.org": true, "i234.me": true, "myds.me": true, "synology.me": true, "taifun-dns.de": true, "gda.pl": true, "gdansk.pl": true, "gdynia.pl": true, "med.pl": true, "sopot.pl": true, "bloxcms.com": true, "townnews-staging.com": true, "*.transurl.be": true, "*.transurl.eu": true, "*.transurl.nl": true, "tuxfamily.org": true, "hk.com": true, "hk.org": true, "ltd.hk": true, "inc.hk": true, "lib.de.us": true, "router.management": true, "wmflabs.org": true, "yolasite.com": true, "za.net": true, "za.org": true, "now.sh": true });
}
,
/* tough-cookie/lib/store */ function _(require, module, exports) {
    /*jshint unused:false */
    function Store() {
    }
    exports.Store = Store;
    // Stores may be synchronous, but are still required to use a
    // Continuation-Passing Style API.  The CookieJar itself will expose a "*Sync"
    // API that converts from synchronous-callbacks to imperative style.
    Store.prototype.synchronous = false;
    Store.prototype.findCookie = function (domain, path, key, cb) {
        throw new Error('findCookie is not implemented');
    };
    Store.prototype.findCookies = function (domain, path, cb) {
        throw new Error('findCookies is not implemented');
    };
    Store.prototype.putCookie = function (cookie, cb) {
        throw new Error('putCookie is not implemented');
    };
    Store.prototype.updateCookie = function (oldCookie, newCookie, cb) {
        // recommended default implementation:
        // return this.putCookie(newCookie, cb);
        throw new Error('updateCookie is not implemented');
    };
    Store.prototype.removeCookie = function (domain, path, key, cb) {
        throw new Error('removeCookie is not implemented');
    };
    Store.prototype.removeCookies = function (domain, path, cb) {
        throw new Error('removeCookies is not implemented');
    };
    Store.prototype.getAllCookies = function (cb) {
        throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
    };
}
,
/* tough-cookie/package.json */ function _(require, module, exports) {
    {
        "_args";
        [
            [
                "tough-cookie@2.3.3",
                "/home/travis/build/bokeh/bokeh/bokehjs"
            ]
        ],
            "_development";
        true,
            "_from";
        "tough-cookie@2.3.3",
            "_id";
        "tough-cookie@2.3.3",
            "_inBundle";
        false,
            "_integrity";
        "sha1-C2GKVWW23qkL80JdBNVe3EdadWE=",
            "_location";
        "/tough-cookie",
            "_phantomChildren";
        { }
        "_requested";
        {
            "type";
            "version",
                "registry";
            true,
                "raw";
            "tough-cookie@2.3.3",
                "name";
            "tough-cookie",
                "escapedName";
            "tough-cookie",
                "rawSpec";
            "2.3.3",
                "saveSpec";
            null,
                "fetchSpec";
            "2.3.3";
        }
        "_requiredBy";
        [
            "/jsdom"
        ],
            "_resolved";
        "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.3.tgz",
            "_spec";
        "2.3.3",
            "_where";
        "/home/travis/build/bokeh/bokeh/bokehjs",
            "author";
        {
            "name";
            "Jeremy Stashewsky",
                "email";
            "jstashewsky@salesforce.com";
        }
        "bugs";
        {
            "url";
            "https://github.com/salesforce/tough-cookie/issues";
        }
        "contributors";
        [
            {
                "name": "Alexander Savin"
            },
            {
                "name": "Ian Livingstone"
            },
            {
                "name": "Ivan Nikulin"
            },
            {
                "name": "Lalit Kapoor"
            },
            {
                "name": "Sam Thompson"
            },
            {
                "name": "Sebastian Mayr"
            }
        ],
            "dependencies";
        {
            "punycode";
            "^1.4.1";
        }
        "description";
        "RFC6265 Cookies and Cookie Jar for node.js",
            "devDependencies";
        {
            "async";
            "^1.4.2",
                "string.prototype.repeat";
            "^0.2.0",
                "vows";
            "^0.8.1";
        }
        "engines";
        {
            "node";
            ">=0.8";
        }
        "files";
        [
            "lib"
        ],
            "homepage";
        "https://github.com/salesforce/tough-cookie",
            "keywords";
        [
            "HTTP",
            "cookie",
            "cookies",
            "set-cookie",
            "cookiejar",
            "jar",
            "RFC6265",
            "RFC2965"
        ],
            "license";
        "BSD-3-Clause",
            "main";
        "./lib/cookie",
            "name";
        "tough-cookie",
            "repository";
        {
            "type";
            "git",
                "url";
            "git://github.com/salesforce/tough-cookie.git";
        }
        "scripts";
        {
            "suffixup";
            "curl -o public_suffix_list.dat https://publicsuffix.org/list/public_suffix_list.dat && ./generate-pubsuffix.js",
                "test";
            "vows test/*_test.js";
        }
        "version";
        "2.3.3";
    }
}
,
/* tunnel-agent/index */ function _(require, module, exports) {
    var net = require('net'), tls = require('tls'), http = require('http'), https = require('https'), events = require('events'), assert = require('assert'), util = require('util'), Buffer = require(311) /* safe-buffer */.Buffer;
    exports.httpOverHttp = httpOverHttp;
    exports.httpsOverHttp = httpsOverHttp;
    exports.httpOverHttps = httpOverHttps;
    exports.httpsOverHttps = httpsOverHttps;
    function httpOverHttp(options) {
        var agent = new TunnelingAgent(options);
        agent.request = http.request;
        return agent;
    }
    function httpsOverHttp(options) {
        var agent = new TunnelingAgent(options);
        agent.request = http.request;
        agent.createSocket = createSecureSocket;
        agent.defaultPort = 443;
        return agent;
    }
    function httpOverHttps(options) {
        var agent = new TunnelingAgent(options);
        agent.request = https.request;
        return agent;
    }
    function httpsOverHttps(options) {
        var agent = new TunnelingAgent(options);
        agent.request = https.request;
        agent.createSocket = createSecureSocket;
        agent.defaultPort = 443;
        return agent;
    }
    function TunnelingAgent(options) {
        var self = this;
        self.options = options || {};
        self.proxyOptions = self.options.proxy || {};
        self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
        self.requests = [];
        self.sockets = [];
        self.on('free', function onFree(socket, host, port) {
            for (var i = 0, len = self.requests.length; i < len; ++i) {
                var pending = self.requests[i];
                if (pending.host === host && pending.port === port) {
                    // Detect the request to connect same origin server,
                    // reuse the connection.
                    self.requests.splice(i, 1);
                    pending.request.onSocket(socket);
                    return;
                }
            }
            socket.destroy();
            self.removeSocket(socket);
        });
    }
    util.inherits(TunnelingAgent, events.EventEmitter);
    TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
        var self = this;
        // Legacy API: addRequest(req, host, port, path)
        if (typeof options === 'string') {
            options = {
                host: options,
                port: arguments[2],
                path: arguments[3]
            };
        }
        if (self.sockets.length >= this.maxSockets) {
            // We are over limit so we'll add it to the queue.
            self.requests.push({ host: options.host, port: options.port, request: req });
            return;
        }
        // If we are under maxSockets create a new one.
        self.createConnection({ host: options.host, port: options.port, request: req });
    };
    TunnelingAgent.prototype.createConnection = function createConnection(pending) {
        var self = this;
        self.createSocket(pending, function (socket) {
            socket.on('free', onFree);
            socket.on('close', onCloseOrRemove);
            socket.on('agentRemove', onCloseOrRemove);
            pending.request.onSocket(socket);
            function onFree() {
                self.emit('free', socket, pending.host, pending.port);
            }
            function onCloseOrRemove(err) {
                self.removeSocket(socket);
                socket.removeListener('free', onFree);
                socket.removeListener('close', onCloseOrRemove);
                socket.removeListener('agentRemove', onCloseOrRemove);
            }
        });
    };
    TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
        var self = this;
        var placeholder = {};
        self.sockets.push(placeholder);
        var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT',
            path: options.host + ':' + options.port,
            agent: false
        });
        if (connectOptions.proxyAuth) {
            connectOptions.headers = connectOptions.headers || {};
            connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
                Buffer.from(connectOptions.proxyAuth).toString('base64');
        }
        debug('making CONNECT request');
        var connectReq = self.request(connectOptions);
        connectReq.useChunkedEncodingByDefault = false; // for v0.6
        connectReq.once('response', onResponse); // for v0.6
        connectReq.once('upgrade', onUpgrade); // for v0.6
        connectReq.once('connect', onConnect); // for v0.7 or later
        connectReq.once('error', onError);
        connectReq.end();
        function onResponse(res) {
            // Very hacky. This is necessary to avoid http-parser leaks.
            res.upgrade = true;
        }
        function onUpgrade(res, socket, head) {
            // Hacky.
            process.nextTick(function () {
                onConnect(res, socket, head);
            });
        }
        function onConnect(res, socket, head) {
            connectReq.removeAllListeners();
            socket.removeAllListeners();
            if (res.statusCode === 200) {
                assert.equal(head.length, 0);
                debug('tunneling connection has established');
                self.sockets[self.sockets.indexOf(placeholder)] = socket;
                cb(socket);
            }
            else {
                debug('tunneling socket could not be established, statusCode=%d', res.statusCode);
                var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode);
                error.code = 'ECONNRESET';
                options.request.emit('error', error);
                self.removeSocket(placeholder);
            }
        }
        function onError(cause) {
            connectReq.removeAllListeners();
            debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack);
            var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message);
            error.code = 'ECONNRESET';
            options.request.emit('error', error);
            self.removeSocket(placeholder);
        }
    };
    TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
        var pos = this.sockets.indexOf(socket);
        if (pos === -1)
            return;
        this.sockets.splice(pos, 1);
        var pending = this.requests.shift();
        if (pending) {
            // If we have pending requests and a socket gets closed a new one
            // needs to be created to take over in the pool for the one that closed.
            this.createConnection(pending);
        }
    };
    function createSecureSocket(options, cb) {
        var self = this;
        TunnelingAgent.prototype.createSocket.call(self, options, function (socket) {
            // 0 is dummy port for v0.6
            var secureSocket = tls.connect(0, mergeOptions({}, self.options, { servername: options.host,
                socket: socket
            }));
            self.sockets[self.sockets.indexOf(socket)] = secureSocket;
            cb(secureSocket);
        });
    }
    function mergeOptions(target) {
        for (var i = 1, len = arguments.length; i < len; ++i) {
            var overrides = arguments[i];
            if (typeof overrides === 'object') {
                var keys = Object.keys(overrides);
                for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
                    var k = keys[j];
                    if (overrides[k] !== undefined) {
                        target[k] = overrides[k];
                    }
                }
            }
        }
        return target;
    }
    var debug;
    if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
        debug = function () {
            var args = Array.prototype.slice.call(arguments);
            if (typeof args[0] === 'string') {
                args[0] = 'TUNNEL: ' + args[0];
            }
            else {
                args.unshift('TUNNEL:');
            }
            console.error.apply(console, args);
        };
    }
    else {
        debug = function () { };
    }
    exports.debug = debug; // for test
}
,
/* tweetnacl/nacl-fast */ function _(require, module, exports) {
    (function (nacl) {
        'use strict';
        // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
        // Public domain.
        //
        // Implementation derived from TweetNaCl version 20140427.
        // See for details: http://tweetnacl.cr.yp.to/
        var gf = function (init) {
            var i, r = new Float64Array(16);
            if (init)
                for (i = 0; i < init.length; i++)
                    r[i] = init[i];
            return r;
        };
        //  Pluggable, initialized in high-level API below.
        var randombytes = function ( /* x, n */) { throw new Error('no PRNG'); };
        var _0 = new Uint8Array(16);
        var _9 = new Uint8Array(32);
        _9[0] = 9;
        var gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
        function ts64(x, i, h, l) {
            x[i] = (h >> 24) & 0xff;
            x[i + 1] = (h >> 16) & 0xff;
            x[i + 2] = (h >> 8) & 0xff;
            x[i + 3] = h & 0xff;
            x[i + 4] = (l >> 24) & 0xff;
            x[i + 5] = (l >> 16) & 0xff;
            x[i + 6] = (l >> 8) & 0xff;
            x[i + 7] = l & 0xff;
        }
        function vn(x, xi, y, yi, n) {
            var i, d = 0;
            for (i = 0; i < n; i++)
                d |= x[xi + i] ^ y[yi + i];
            return (1 & ((d - 1) >>> 8)) - 1;
        }
        function crypto_verify_16(x, xi, y, yi) {
            return vn(x, xi, y, yi, 16);
        }
        function crypto_verify_32(x, xi, y, yi) {
            return vn(x, xi, y, yi, 32);
        }
        function core_salsa20(o, p, k, c) {
            var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24;
            var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
            for (var i = 0; i < 20; i += 2) {
                u = x0 + x12 | 0;
                x4 ^= u << 7 | u >>> (32 - 7);
                u = x4 + x0 | 0;
                x8 ^= u << 9 | u >>> (32 - 9);
                u = x8 + x4 | 0;
                x12 ^= u << 13 | u >>> (32 - 13);
                u = x12 + x8 | 0;
                x0 ^= u << 18 | u >>> (32 - 18);
                u = x5 + x1 | 0;
                x9 ^= u << 7 | u >>> (32 - 7);
                u = x9 + x5 | 0;
                x13 ^= u << 9 | u >>> (32 - 9);
                u = x13 + x9 | 0;
                x1 ^= u << 13 | u >>> (32 - 13);
                u = x1 + x13 | 0;
                x5 ^= u << 18 | u >>> (32 - 18);
                u = x10 + x6 | 0;
                x14 ^= u << 7 | u >>> (32 - 7);
                u = x14 + x10 | 0;
                x2 ^= u << 9 | u >>> (32 - 9);
                u = x2 + x14 | 0;
                x6 ^= u << 13 | u >>> (32 - 13);
                u = x6 + x2 | 0;
                x10 ^= u << 18 | u >>> (32 - 18);
                u = x15 + x11 | 0;
                x3 ^= u << 7 | u >>> (32 - 7);
                u = x3 + x15 | 0;
                x7 ^= u << 9 | u >>> (32 - 9);
                u = x7 + x3 | 0;
                x11 ^= u << 13 | u >>> (32 - 13);
                u = x11 + x7 | 0;
                x15 ^= u << 18 | u >>> (32 - 18);
                u = x0 + x3 | 0;
                x1 ^= u << 7 | u >>> (32 - 7);
                u = x1 + x0 | 0;
                x2 ^= u << 9 | u >>> (32 - 9);
                u = x2 + x1 | 0;
                x3 ^= u << 13 | u >>> (32 - 13);
                u = x3 + x2 | 0;
                x0 ^= u << 18 | u >>> (32 - 18);
                u = x5 + x4 | 0;
                x6 ^= u << 7 | u >>> (32 - 7);
                u = x6 + x5 | 0;
                x7 ^= u << 9 | u >>> (32 - 9);
                u = x7 + x6 | 0;
                x4 ^= u << 13 | u >>> (32 - 13);
                u = x4 + x7 | 0;
                x5 ^= u << 18 | u >>> (32 - 18);
                u = x10 + x9 | 0;
                x11 ^= u << 7 | u >>> (32 - 7);
                u = x11 + x10 | 0;
                x8 ^= u << 9 | u >>> (32 - 9);
                u = x8 + x11 | 0;
                x9 ^= u << 13 | u >>> (32 - 13);
                u = x9 + x8 | 0;
                x10 ^= u << 18 | u >>> (32 - 18);
                u = x15 + x14 | 0;
                x12 ^= u << 7 | u >>> (32 - 7);
                u = x12 + x15 | 0;
                x13 ^= u << 9 | u >>> (32 - 9);
                u = x13 + x12 | 0;
                x14 ^= u << 13 | u >>> (32 - 13);
                u = x14 + x13 | 0;
                x15 ^= u << 18 | u >>> (32 - 18);
            }
            x0 = x0 + j0 | 0;
            x1 = x1 + j1 | 0;
            x2 = x2 + j2 | 0;
            x3 = x3 + j3 | 0;
            x4 = x4 + j4 | 0;
            x5 = x5 + j5 | 0;
            x6 = x6 + j6 | 0;
            x7 = x7 + j7 | 0;
            x8 = x8 + j8 | 0;
            x9 = x9 + j9 | 0;
            x10 = x10 + j10 | 0;
            x11 = x11 + j11 | 0;
            x12 = x12 + j12 | 0;
            x13 = x13 + j13 | 0;
            x14 = x14 + j14 | 0;
            x15 = x15 + j15 | 0;
            o[0] = x0 >>> 0 & 0xff;
            o[1] = x0 >>> 8 & 0xff;
            o[2] = x0 >>> 16 & 0xff;
            o[3] = x0 >>> 24 & 0xff;
            o[4] = x1 >>> 0 & 0xff;
            o[5] = x1 >>> 8 & 0xff;
            o[6] = x1 >>> 16 & 0xff;
            o[7] = x1 >>> 24 & 0xff;
            o[8] = x2 >>> 0 & 0xff;
            o[9] = x2 >>> 8 & 0xff;
            o[10] = x2 >>> 16 & 0xff;
            o[11] = x2 >>> 24 & 0xff;
            o[12] = x3 >>> 0 & 0xff;
            o[13] = x3 >>> 8 & 0xff;
            o[14] = x3 >>> 16 & 0xff;
            o[15] = x3 >>> 24 & 0xff;
            o[16] = x4 >>> 0 & 0xff;
            o[17] = x4 >>> 8 & 0xff;
            o[18] = x4 >>> 16 & 0xff;
            o[19] = x4 >>> 24 & 0xff;
            o[20] = x5 >>> 0 & 0xff;
            o[21] = x5 >>> 8 & 0xff;
            o[22] = x5 >>> 16 & 0xff;
            o[23] = x5 >>> 24 & 0xff;
            o[24] = x6 >>> 0 & 0xff;
            o[25] = x6 >>> 8 & 0xff;
            o[26] = x6 >>> 16 & 0xff;
            o[27] = x6 >>> 24 & 0xff;
            o[28] = x7 >>> 0 & 0xff;
            o[29] = x7 >>> 8 & 0xff;
            o[30] = x7 >>> 16 & 0xff;
            o[31] = x7 >>> 24 & 0xff;
            o[32] = x8 >>> 0 & 0xff;
            o[33] = x8 >>> 8 & 0xff;
            o[34] = x8 >>> 16 & 0xff;
            o[35] = x8 >>> 24 & 0xff;
            o[36] = x9 >>> 0 & 0xff;
            o[37] = x9 >>> 8 & 0xff;
            o[38] = x9 >>> 16 & 0xff;
            o[39] = x9 >>> 24 & 0xff;
            o[40] = x10 >>> 0 & 0xff;
            o[41] = x10 >>> 8 & 0xff;
            o[42] = x10 >>> 16 & 0xff;
            o[43] = x10 >>> 24 & 0xff;
            o[44] = x11 >>> 0 & 0xff;
            o[45] = x11 >>> 8 & 0xff;
            o[46] = x11 >>> 16 & 0xff;
            o[47] = x11 >>> 24 & 0xff;
            o[48] = x12 >>> 0 & 0xff;
            o[49] = x12 >>> 8 & 0xff;
            o[50] = x12 >>> 16 & 0xff;
            o[51] = x12 >>> 24 & 0xff;
            o[52] = x13 >>> 0 & 0xff;
            o[53] = x13 >>> 8 & 0xff;
            o[54] = x13 >>> 16 & 0xff;
            o[55] = x13 >>> 24 & 0xff;
            o[56] = x14 >>> 0 & 0xff;
            o[57] = x14 >>> 8 & 0xff;
            o[58] = x14 >>> 16 & 0xff;
            o[59] = x14 >>> 24 & 0xff;
            o[60] = x15 >>> 0 & 0xff;
            o[61] = x15 >>> 8 & 0xff;
            o[62] = x15 >>> 16 & 0xff;
            o[63] = x15 >>> 24 & 0xff;
        }
        function core_hsalsa20(o, p, k, c) {
            var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24;
            var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
            for (var i = 0; i < 20; i += 2) {
                u = x0 + x12 | 0;
                x4 ^= u << 7 | u >>> (32 - 7);
                u = x4 + x0 | 0;
                x8 ^= u << 9 | u >>> (32 - 9);
                u = x8 + x4 | 0;
                x12 ^= u << 13 | u >>> (32 - 13);
                u = x12 + x8 | 0;
                x0 ^= u << 18 | u >>> (32 - 18);
                u = x5 + x1 | 0;
                x9 ^= u << 7 | u >>> (32 - 7);
                u = x9 + x5 | 0;
                x13 ^= u << 9 | u >>> (32 - 9);
                u = x13 + x9 | 0;
                x1 ^= u << 13 | u >>> (32 - 13);
                u = x1 + x13 | 0;
                x5 ^= u << 18 | u >>> (32 - 18);
                u = x10 + x6 | 0;
                x14 ^= u << 7 | u >>> (32 - 7);
                u = x14 + x10 | 0;
                x2 ^= u << 9 | u >>> (32 - 9);
                u = x2 + x14 | 0;
                x6 ^= u << 13 | u >>> (32 - 13);
                u = x6 + x2 | 0;
                x10 ^= u << 18 | u >>> (32 - 18);
                u = x15 + x11 | 0;
                x3 ^= u << 7 | u >>> (32 - 7);
                u = x3 + x15 | 0;
                x7 ^= u << 9 | u >>> (32 - 9);
                u = x7 + x3 | 0;
                x11 ^= u << 13 | u >>> (32 - 13);
                u = x11 + x7 | 0;
                x15 ^= u << 18 | u >>> (32 - 18);
                u = x0 + x3 | 0;
                x1 ^= u << 7 | u >>> (32 - 7);
                u = x1 + x0 | 0;
                x2 ^= u << 9 | u >>> (32 - 9);
                u = x2 + x1 | 0;
                x3 ^= u << 13 | u >>> (32 - 13);
                u = x3 + x2 | 0;
                x0 ^= u << 18 | u >>> (32 - 18);
                u = x5 + x4 | 0;
                x6 ^= u << 7 | u >>> (32 - 7);
                u = x6 + x5 | 0;
                x7 ^= u << 9 | u >>> (32 - 9);
                u = x7 + x6 | 0;
                x4 ^= u << 13 | u >>> (32 - 13);
                u = x4 + x7 | 0;
                x5 ^= u << 18 | u >>> (32 - 18);
                u = x10 + x9 | 0;
                x11 ^= u << 7 | u >>> (32 - 7);
                u = x11 + x10 | 0;
                x8 ^= u << 9 | u >>> (32 - 9);
                u = x8 + x11 | 0;
                x9 ^= u << 13 | u >>> (32 - 13);
                u = x9 + x8 | 0;
                x10 ^= u << 18 | u >>> (32 - 18);
                u = x15 + x14 | 0;
                x12 ^= u << 7 | u >>> (32 - 7);
                u = x12 + x15 | 0;
                x13 ^= u << 9 | u >>> (32 - 9);
                u = x13 + x12 | 0;
                x14 ^= u << 13 | u >>> (32 - 13);
                u = x14 + x13 | 0;
                x15 ^= u << 18 | u >>> (32 - 18);
            }
            o[0] = x0 >>> 0 & 0xff;
            o[1] = x0 >>> 8 & 0xff;
            o[2] = x0 >>> 16 & 0xff;
            o[3] = x0 >>> 24 & 0xff;
            o[4] = x5 >>> 0 & 0xff;
            o[5] = x5 >>> 8 & 0xff;
            o[6] = x5 >>> 16 & 0xff;
            o[7] = x5 >>> 24 & 0xff;
            o[8] = x10 >>> 0 & 0xff;
            o[9] = x10 >>> 8 & 0xff;
            o[10] = x10 >>> 16 & 0xff;
            o[11] = x10 >>> 24 & 0xff;
            o[12] = x15 >>> 0 & 0xff;
            o[13] = x15 >>> 8 & 0xff;
            o[14] = x15 >>> 16 & 0xff;
            o[15] = x15 >>> 24 & 0xff;
            o[16] = x6 >>> 0 & 0xff;
            o[17] = x6 >>> 8 & 0xff;
            o[18] = x6 >>> 16 & 0xff;
            o[19] = x6 >>> 24 & 0xff;
            o[20] = x7 >>> 0 & 0xff;
            o[21] = x7 >>> 8 & 0xff;
            o[22] = x7 >>> 16 & 0xff;
            o[23] = x7 >>> 24 & 0xff;
            o[24] = x8 >>> 0 & 0xff;
            o[25] = x8 >>> 8 & 0xff;
            o[26] = x8 >>> 16 & 0xff;
            o[27] = x8 >>> 24 & 0xff;
            o[28] = x9 >>> 0 & 0xff;
            o[29] = x9 >>> 8 & 0xff;
            o[30] = x9 >>> 16 & 0xff;
            o[31] = x9 >>> 24 & 0xff;
        }
        function crypto_core_salsa20(out, inp, k, c) {
            core_salsa20(out, inp, k, c);
        }
        function crypto_core_hsalsa20(out, inp, k, c) {
            core_hsalsa20(out, inp, k, c);
        }
        var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
        // "expand 32-byte k"
        function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) {
            var z = new Uint8Array(16), x = new Uint8Array(64);
            var u, i;
            for (i = 0; i < 16; i++)
                z[i] = 0;
            for (i = 0; i < 8; i++)
                z[i] = n[i];
            while (b >= 64) {
                crypto_core_salsa20(x, z, k, sigma);
                for (i = 0; i < 64; i++)
                    c[cpos + i] = m[mpos + i] ^ x[i];
                u = 1;
                for (i = 8; i < 16; i++) {
                    u = u + (z[i] & 0xff) | 0;
                    z[i] = u & 0xff;
                    u >>>= 8;
                }
                b -= 64;
                cpos += 64;
                mpos += 64;
            }
            if (b > 0) {
                crypto_core_salsa20(x, z, k, sigma);
                for (i = 0; i < b; i++)
                    c[cpos + i] = m[mpos + i] ^ x[i];
            }
            return 0;
        }
        function crypto_stream_salsa20(c, cpos, b, n, k) {
            var z = new Uint8Array(16), x = new Uint8Array(64);
            var u, i;
            for (i = 0; i < 16; i++)
                z[i] = 0;
            for (i = 0; i < 8; i++)
                z[i] = n[i];
            while (b >= 64) {
                crypto_core_salsa20(x, z, k, sigma);
                for (i = 0; i < 64; i++)
                    c[cpos + i] = x[i];
                u = 1;
                for (i = 8; i < 16; i++) {
                    u = u + (z[i] & 0xff) | 0;
                    z[i] = u & 0xff;
                    u >>>= 8;
                }
                b -= 64;
                cpos += 64;
            }
            if (b > 0) {
                crypto_core_salsa20(x, z, k, sigma);
                for (i = 0; i < b; i++)
                    c[cpos + i] = x[i];
            }
            return 0;
        }
        function crypto_stream(c, cpos, d, n, k) {
            var s = new Uint8Array(32);
            crypto_core_hsalsa20(s, n, k, sigma);
            var sn = new Uint8Array(8);
            for (var i = 0; i < 8; i++)
                sn[i] = n[i + 16];
            return crypto_stream_salsa20(c, cpos, d, sn, s);
        }
        function crypto_stream_xor(c, cpos, m, mpos, d, n, k) {
            var s = new Uint8Array(32);
            crypto_core_hsalsa20(s, n, k, sigma);
            var sn = new Uint8Array(8);
            for (var i = 0; i < 8; i++)
                sn[i] = n[i + 16];
            return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s);
        }
        /*
        * Port of Andrew Moon's Poly1305-donna-16. Public domain.
        * https://github.com/floodyberry/poly1305-donna
        */
        var poly1305 = function (key) {
            this.buffer = new Uint8Array(16);
            this.r = new Uint16Array(10);
            this.h = new Uint16Array(10);
            this.pad = new Uint16Array(8);
            this.leftover = 0;
            this.fin = 0;
            var t0, t1, t2, t3, t4, t5, t6, t7;
            t0 = key[0] & 0xff | (key[1] & 0xff) << 8;
            this.r[0] = (t0) & 0x1fff;
            t1 = key[2] & 0xff | (key[3] & 0xff) << 8;
            this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
            t2 = key[4] & 0xff | (key[5] & 0xff) << 8;
            this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
            t3 = key[6] & 0xff | (key[7] & 0xff) << 8;
            this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
            t4 = key[8] & 0xff | (key[9] & 0xff) << 8;
            this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
            this.r[5] = ((t4 >>> 1)) & 0x1ffe;
            t5 = key[10] & 0xff | (key[11] & 0xff) << 8;
            this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
            t6 = key[12] & 0xff | (key[13] & 0xff) << 8;
            this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
            t7 = key[14] & 0xff | (key[15] & 0xff) << 8;
            this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
            this.r[9] = ((t7 >>> 5)) & 0x007f;
            this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
            this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
            this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
            this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
            this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
            this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
            this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
            this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
        };
        poly1305.prototype.blocks = function (m, mpos, bytes) {
            var hibit = this.fin ? 0 : (1 << 11);
            var t0, t1, t2, t3, t4, t5, t6, t7, c;
            var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
            var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9];
            var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9];
            while (bytes >= 16) {
                t0 = m[mpos + 0] & 0xff | (m[mpos + 1] & 0xff) << 8;
                h0 += (t0) & 0x1fff;
                t1 = m[mpos + 2] & 0xff | (m[mpos + 3] & 0xff) << 8;
                h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
                t2 = m[mpos + 4] & 0xff | (m[mpos + 5] & 0xff) << 8;
                h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
                t3 = m[mpos + 6] & 0xff | (m[mpos + 7] & 0xff) << 8;
                h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
                t4 = m[mpos + 8] & 0xff | (m[mpos + 9] & 0xff) << 8;
                h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
                h5 += ((t4 >>> 1)) & 0x1fff;
                t5 = m[mpos + 10] & 0xff | (m[mpos + 11] & 0xff) << 8;
                h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
                t6 = m[mpos + 12] & 0xff | (m[mpos + 13] & 0xff) << 8;
                h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
                t7 = m[mpos + 14] & 0xff | (m[mpos + 15] & 0xff) << 8;
                h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
                h9 += ((t7 >>> 5)) | hibit;
                c = 0;
                d0 = c;
                d0 += h0 * r0;
                d0 += h1 * (5 * r9);
                d0 += h2 * (5 * r8);
                d0 += h3 * (5 * r7);
                d0 += h4 * (5 * r6);
                c = (d0 >>> 13);
                d0 &= 0x1fff;
                d0 += h5 * (5 * r5);
                d0 += h6 * (5 * r4);
                d0 += h7 * (5 * r3);
                d0 += h8 * (5 * r2);
                d0 += h9 * (5 * r1);
                c += (d0 >>> 13);
                d0 &= 0x1fff;
                d1 = c;
                d1 += h0 * r1;
                d1 += h1 * r0;
                d1 += h2 * (5 * r9);
                d1 += h3 * (5 * r8);
                d1 += h4 * (5 * r7);
                c = (d1 >>> 13);
                d1 &= 0x1fff;
                d1 += h5 * (5 * r6);
                d1 += h6 * (5 * r5);
                d1 += h7 * (5 * r4);
                d1 += h8 * (5 * r3);
                d1 += h9 * (5 * r2);
                c += (d1 >>> 13);
                d1 &= 0x1fff;
                d2 = c;
                d2 += h0 * r2;
                d2 += h1 * r1;
                d2 += h2 * r0;
                d2 += h3 * (5 * r9);
                d2 += h4 * (5 * r8);
                c = (d2 >>> 13);
                d2 &= 0x1fff;
                d2 += h5 * (5 * r7);
                d2 += h6 * (5 * r6);
                d2 += h7 * (5 * r5);
                d2 += h8 * (5 * r4);
                d2 += h9 * (5 * r3);
                c += (d2 >>> 13);
                d2 &= 0x1fff;
                d3 = c;
                d3 += h0 * r3;
                d3 += h1 * r2;
                d3 += h2 * r1;
                d3 += h3 * r0;
                d3 += h4 * (5 * r9);
                c = (d3 >>> 13);
                d3 &= 0x1fff;
                d3 += h5 * (5 * r8);
                d3 += h6 * (5 * r7);
                d3 += h7 * (5 * r6);
                d3 += h8 * (5 * r5);
                d3 += h9 * (5 * r4);
                c += (d3 >>> 13);
                d3 &= 0x1fff;
                d4 = c;
                d4 += h0 * r4;
                d4 += h1 * r3;
                d4 += h2 * r2;
                d4 += h3 * r1;
                d4 += h4 * r0;
                c = (d4 >>> 13);
                d4 &= 0x1fff;
                d4 += h5 * (5 * r9);
                d4 += h6 * (5 * r8);
                d4 += h7 * (5 * r7);
                d4 += h8 * (5 * r6);
                d4 += h9 * (5 * r5);
                c += (d4 >>> 13);
                d4 &= 0x1fff;
                d5 = c;
                d5 += h0 * r5;
                d5 += h1 * r4;
                d5 += h2 * r3;
                d5 += h3 * r2;
                d5 += h4 * r1;
                c = (d5 >>> 13);
                d5 &= 0x1fff;
                d5 += h5 * r0;
                d5 += h6 * (5 * r9);
                d5 += h7 * (5 * r8);
                d5 += h8 * (5 * r7);
                d5 += h9 * (5 * r6);
                c += (d5 >>> 13);
                d5 &= 0x1fff;
                d6 = c;
                d6 += h0 * r6;
                d6 += h1 * r5;
                d6 += h2 * r4;
                d6 += h3 * r3;
                d6 += h4 * r2;
                c = (d6 >>> 13);
                d6 &= 0x1fff;
                d6 += h5 * r1;
                d6 += h6 * r0;
                d6 += h7 * (5 * r9);
                d6 += h8 * (5 * r8);
                d6 += h9 * (5 * r7);
                c += (d6 >>> 13);
                d6 &= 0x1fff;
                d7 = c;
                d7 += h0 * r7;
                d7 += h1 * r6;
                d7 += h2 * r5;
                d7 += h3 * r4;
                d7 += h4 * r3;
                c = (d7 >>> 13);
                d7 &= 0x1fff;
                d7 += h5 * r2;
                d7 += h6 * r1;
                d7 += h7 * r0;
                d7 += h8 * (5 * r9);
                d7 += h9 * (5 * r8);
                c += (d7 >>> 13);
                d7 &= 0x1fff;
                d8 = c;
                d8 += h0 * r8;
                d8 += h1 * r7;
                d8 += h2 * r6;
                d8 += h3 * r5;
                d8 += h4 * r4;
                c = (d8 >>> 13);
                d8 &= 0x1fff;
                d8 += h5 * r3;
                d8 += h6 * r2;
                d8 += h7 * r1;
                d8 += h8 * r0;
                d8 += h9 * (5 * r9);
                c += (d8 >>> 13);
                d8 &= 0x1fff;
                d9 = c;
                d9 += h0 * r9;
                d9 += h1 * r8;
                d9 += h2 * r7;
                d9 += h3 * r6;
                d9 += h4 * r5;
                c = (d9 >>> 13);
                d9 &= 0x1fff;
                d9 += h5 * r4;
                d9 += h6 * r3;
                d9 += h7 * r2;
                d9 += h8 * r1;
                d9 += h9 * r0;
                c += (d9 >>> 13);
                d9 &= 0x1fff;
                c = (((c << 2) + c)) | 0;
                c = (c + d0) | 0;
                d0 = c & 0x1fff;
                c = (c >>> 13);
                d1 += c;
                h0 = d0;
                h1 = d1;
                h2 = d2;
                h3 = d3;
                h4 = d4;
                h5 = d5;
                h6 = d6;
                h7 = d7;
                h8 = d8;
                h9 = d9;
                mpos += 16;
                bytes -= 16;
            }
            this.h[0] = h0;
            this.h[1] = h1;
            this.h[2] = h2;
            this.h[3] = h3;
            this.h[4] = h4;
            this.h[5] = h5;
            this.h[6] = h6;
            this.h[7] = h7;
            this.h[8] = h8;
            this.h[9] = h9;
        };
        poly1305.prototype.finish = function (mac, macpos) {
            var g = new Uint16Array(10);
            var c, mask, f, i;
            if (this.leftover) {
                i = this.leftover;
                this.buffer[i++] = 1;
                for (; i < 16; i++)
                    this.buffer[i] = 0;
                this.fin = 1;
                this.blocks(this.buffer, 0, 16);
            }
            c = this.h[1] >>> 13;
            this.h[1] &= 0x1fff;
            for (i = 2; i < 10; i++) {
                this.h[i] += c;
                c = this.h[i] >>> 13;
                this.h[i] &= 0x1fff;
            }
            this.h[0] += (c * 5);
            c = this.h[0] >>> 13;
            this.h[0] &= 0x1fff;
            this.h[1] += c;
            c = this.h[1] >>> 13;
            this.h[1] &= 0x1fff;
            this.h[2] += c;
            g[0] = this.h[0] + 5;
            c = g[0] >>> 13;
            g[0] &= 0x1fff;
            for (i = 1; i < 10; i++) {
                g[i] = this.h[i] + c;
                c = g[i] >>> 13;
                g[i] &= 0x1fff;
            }
            g[9] -= (1 << 13);
            mask = (c ^ 1) - 1;
            for (i = 0; i < 10; i++)
                g[i] &= mask;
            mask = ~mask;
            for (i = 0; i < 10; i++)
                this.h[i] = (this.h[i] & mask) | g[i];
            this.h[0] = ((this.h[0]) | (this.h[1] << 13)) & 0xffff;
            this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10)) & 0xffff;
            this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7)) & 0xffff;
            this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4)) & 0xffff;
            this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
            this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11)) & 0xffff;
            this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8)) & 0xffff;
            this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5)) & 0xffff;
            f = this.h[0] + this.pad[0];
            this.h[0] = f & 0xffff;
            for (i = 1; i < 8; i++) {
                f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
                this.h[i] = f & 0xffff;
            }
            mac[macpos + 0] = (this.h[0] >>> 0) & 0xff;
            mac[macpos + 1] = (this.h[0] >>> 8) & 0xff;
            mac[macpos + 2] = (this.h[1] >>> 0) & 0xff;
            mac[macpos + 3] = (this.h[1] >>> 8) & 0xff;
            mac[macpos + 4] = (this.h[2] >>> 0) & 0xff;
            mac[macpos + 5] = (this.h[2] >>> 8) & 0xff;
            mac[macpos + 6] = (this.h[3] >>> 0) & 0xff;
            mac[macpos + 7] = (this.h[3] >>> 8) & 0xff;
            mac[macpos + 8] = (this.h[4] >>> 0) & 0xff;
            mac[macpos + 9] = (this.h[4] >>> 8) & 0xff;
            mac[macpos + 10] = (this.h[5] >>> 0) & 0xff;
            mac[macpos + 11] = (this.h[5] >>> 8) & 0xff;
            mac[macpos + 12] = (this.h[6] >>> 0) & 0xff;
            mac[macpos + 13] = (this.h[6] >>> 8) & 0xff;
            mac[macpos + 14] = (this.h[7] >>> 0) & 0xff;
            mac[macpos + 15] = (this.h[7] >>> 8) & 0xff;
        };
        poly1305.prototype.update = function (m, mpos, bytes) {
            var i, want;
            if (this.leftover) {
                want = (16 - this.leftover);
                if (want > bytes)
                    want = bytes;
                for (i = 0; i < want; i++)
                    this.buffer[this.leftover + i] = m[mpos + i];
                bytes -= want;
                mpos += want;
                this.leftover += want;
                if (this.leftover < 16)
                    return;
                this.blocks(this.buffer, 0, 16);
                this.leftover = 0;
            }
            if (bytes >= 16) {
                want = bytes - (bytes % 16);
                this.blocks(m, mpos, want);
                mpos += want;
                bytes -= want;
            }
            if (bytes) {
                for (i = 0; i < bytes; i++)
                    this.buffer[this.leftover + i] = m[mpos + i];
                this.leftover += bytes;
            }
        };
        function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
            var s = new poly1305(k);
            s.update(m, mpos, n);
            s.finish(out, outpos);
            return 0;
        }
        function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
            var x = new Uint8Array(16);
            crypto_onetimeauth(x, 0, m, mpos, n, k);
            return crypto_verify_16(h, hpos, x, 0);
        }
        function crypto_secretbox(c, m, d, n, k) {
            var i;
            if (d < 32)
                return -1;
            crypto_stream_xor(c, 0, m, 0, d, n, k);
            crypto_onetimeauth(c, 16, c, 32, d - 32, c);
            for (i = 0; i < 16; i++)
                c[i] = 0;
            return 0;
        }
        function crypto_secretbox_open(m, c, d, n, k) {
            var i;
            var x = new Uint8Array(32);
            if (d < 32)
                return -1;
            crypto_stream(x, 0, 32, n, k);
            if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0)
                return -1;
            crypto_stream_xor(m, 0, c, 0, d, n, k);
            for (i = 0; i < 32; i++)
                m[i] = 0;
            return 0;
        }
        function set25519(r, a) {
            var i;
            for (i = 0; i < 16; i++)
                r[i] = a[i] | 0;
        }
        function car25519(o) {
            var i, v, c = 1;
            for (i = 0; i < 16; i++) {
                v = o[i] + c + 65535;
                c = Math.floor(v / 65536);
                o[i] = v - c * 65536;
            }
            o[0] += c - 1 + 37 * (c - 1);
        }
        function sel25519(p, q, b) {
            var t, c = ~(b - 1);
            for (var i = 0; i < 16; i++) {
                t = c & (p[i] ^ q[i]);
                p[i] ^= t;
                q[i] ^= t;
            }
        }
        function pack25519(o, n) {
            var i, j, b;
            var m = gf(), t = gf();
            for (i = 0; i < 16; i++)
                t[i] = n[i];
            car25519(t);
            car25519(t);
            car25519(t);
            for (j = 0; j < 2; j++) {
                m[0] = t[0] - 0xffed;
                for (i = 1; i < 15; i++) {
                    m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
                    m[i - 1] &= 0xffff;
                }
                m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
                b = (m[15] >> 16) & 1;
                m[14] &= 0xffff;
                sel25519(t, m, 1 - b);
            }
            for (i = 0; i < 16; i++) {
                o[2 * i] = t[i] & 0xff;
                o[2 * i + 1] = t[i] >> 8;
            }
        }
        function neq25519(a, b) {
            var c = new Uint8Array(32), d = new Uint8Array(32);
            pack25519(c, a);
            pack25519(d, b);
            return crypto_verify_32(c, 0, d, 0);
        }
        function par25519(a) {
            var d = new Uint8Array(32);
            pack25519(d, a);
            return d[0] & 1;
        }
        function unpack25519(o, n) {
            var i;
            for (i = 0; i < 16; i++)
                o[i] = n[2 * i] + (n[2 * i + 1] << 8);
            o[15] &= 0x7fff;
        }
        function A(o, a, b) {
            for (var i = 0; i < 16; i++)
                o[i] = a[i] + b[i];
        }
        function Z(o, a, b) {
            for (var i = 0; i < 16; i++)
                o[i] = a[i] - b[i];
        }
        function M(o, a, b) {
            var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
            v = a[0];
            t0 += v * b0;
            t1 += v * b1;
            t2 += v * b2;
            t3 += v * b3;
            t4 += v * b4;
            t5 += v * b5;
            t6 += v * b6;
            t7 += v * b7;
            t8 += v * b8;
            t9 += v * b9;
            t10 += v * b10;
            t11 += v * b11;
            t12 += v * b12;
            t13 += v * b13;
            t14 += v * b14;
            t15 += v * b15;
            v = a[1];
            t1 += v * b0;
            t2 += v * b1;
            t3 += v * b2;
            t4 += v * b3;
            t5 += v * b4;
            t6 += v * b5;
            t7 += v * b6;
            t8 += v * b7;
            t9 += v * b8;
            t10 += v * b9;
            t11 += v * b10;
            t12 += v * b11;
            t13 += v * b12;
            t14 += v * b13;
            t15 += v * b14;
            t16 += v * b15;
            v = a[2];
            t2 += v * b0;
            t3 += v * b1;
            t4 += v * b2;
            t5 += v * b3;
            t6 += v * b4;
            t7 += v * b5;
            t8 += v * b6;
            t9 += v * b7;
            t10 += v * b8;
            t11 += v * b9;
            t12 += v * b10;
            t13 += v * b11;
            t14 += v * b12;
            t15 += v * b13;
            t16 += v * b14;
            t17 += v * b15;
            v = a[3];
            t3 += v * b0;
            t4 += v * b1;
            t5 += v * b2;
            t6 += v * b3;
            t7 += v * b4;
            t8 += v * b5;
            t9 += v * b6;
            t10 += v * b7;
            t11 += v * b8;
            t12 += v * b9;
            t13 += v * b10;
            t14 += v * b11;
            t15 += v * b12;
            t16 += v * b13;
            t17 += v * b14;
            t18 += v * b15;
            v = a[4];
            t4 += v * b0;
            t5 += v * b1;
            t6 += v * b2;
            t7 += v * b3;
            t8 += v * b4;
            t9 += v * b5;
            t10 += v * b6;
            t11 += v * b7;
            t12 += v * b8;
            t13 += v * b9;
            t14 += v * b10;
            t15 += v * b11;
            t16 += v * b12;
            t17 += v * b13;
            t18 += v * b14;
            t19 += v * b15;
            v = a[5];
            t5 += v * b0;
            t6 += v * b1;
            t7 += v * b2;
            t8 += v * b3;
            t9 += v * b4;
            t10 += v * b5;
            t11 += v * b6;
            t12 += v * b7;
            t13 += v * b8;
            t14 += v * b9;
            t15 += v * b10;
            t16 += v * b11;
            t17 += v * b12;
            t18 += v * b13;
            t19 += v * b14;
            t20 += v * b15;
            v = a[6];
            t6 += v * b0;
            t7 += v * b1;
            t8 += v * b2;
            t9 += v * b3;
            t10 += v * b4;
            t11 += v * b5;
            t12 += v * b6;
            t13 += v * b7;
            t14 += v * b8;
            t15 += v * b9;
            t16 += v * b10;
            t17 += v * b11;
            t18 += v * b12;
            t19 += v * b13;
            t20 += v * b14;
            t21 += v * b15;
            v = a[7];
            t7 += v * b0;
            t8 += v * b1;
            t9 += v * b2;
            t10 += v * b3;
            t11 += v * b4;
            t12 += v * b5;
            t13 += v * b6;
            t14 += v * b7;
            t15 += v * b8;
            t16 += v * b9;
            t17 += v * b10;
            t18 += v * b11;
            t19 += v * b12;
            t20 += v * b13;
            t21 += v * b14;
            t22 += v * b15;
            v = a[8];
            t8 += v * b0;
            t9 += v * b1;
            t10 += v * b2;
            t11 += v * b3;
            t12 += v * b4;
            t13 += v * b5;
            t14 += v * b6;
            t15 += v * b7;
            t16 += v * b8;
            t17 += v * b9;
            t18 += v * b10;
            t19 += v * b11;
            t20 += v * b12;
            t21 += v * b13;
            t22 += v * b14;
            t23 += v * b15;
            v = a[9];
            t9 += v * b0;
            t10 += v * b1;
            t11 += v * b2;
            t12 += v * b3;
            t13 += v * b4;
            t14 += v * b5;
            t15 += v * b6;
            t16 += v * b7;
            t17 += v * b8;
            t18 += v * b9;
            t19 += v * b10;
            t20 += v * b11;
            t21 += v * b12;
            t22 += v * b13;
            t23 += v * b14;
            t24 += v * b15;
            v = a[10];
            t10 += v * b0;
            t11 += v * b1;
            t12 += v * b2;
            t13 += v * b3;
            t14 += v * b4;
            t15 += v * b5;
            t16 += v * b6;
            t17 += v * b7;
            t18 += v * b8;
            t19 += v * b9;
            t20 += v * b10;
            t21 += v * b11;
            t22 += v * b12;
            t23 += v * b13;
            t24 += v * b14;
            t25 += v * b15;
            v = a[11];
            t11 += v * b0;
            t12 += v * b1;
            t13 += v * b2;
            t14 += v * b3;
            t15 += v * b4;
            t16 += v * b5;
            t17 += v * b6;
            t18 += v * b7;
            t19 += v * b8;
            t20 += v * b9;
            t21 += v * b10;
            t22 += v * b11;
            t23 += v * b12;
            t24 += v * b13;
            t25 += v * b14;
            t26 += v * b15;
            v = a[12];
            t12 += v * b0;
            t13 += v * b1;
            t14 += v * b2;
            t15 += v * b3;
            t16 += v * b4;
            t17 += v * b5;
            t18 += v * b6;
            t19 += v * b7;
            t20 += v * b8;
            t21 += v * b9;
            t22 += v * b10;
            t23 += v * b11;
            t24 += v * b12;
            t25 += v * b13;
            t26 += v * b14;
            t27 += v * b15;
            v = a[13];
            t13 += v * b0;
            t14 += v * b1;
            t15 += v * b2;
            t16 += v * b3;
            t17 += v * b4;
            t18 += v * b5;
            t19 += v * b6;
            t20 += v * b7;
            t21 += v * b8;
            t22 += v * b9;
            t23 += v * b10;
            t24 += v * b11;
            t25 += v * b12;
            t26 += v * b13;
            t27 += v * b14;
            t28 += v * b15;
            v = a[14];
            t14 += v * b0;
            t15 += v * b1;
            t16 += v * b2;
            t17 += v * b3;
            t18 += v * b4;
            t19 += v * b5;
            t20 += v * b6;
            t21 += v * b7;
            t22 += v * b8;
            t23 += v * b9;
            t24 += v * b10;
            t25 += v * b11;
            t26 += v * b12;
            t27 += v * b13;
            t28 += v * b14;
            t29 += v * b15;
            v = a[15];
            t15 += v * b0;
            t16 += v * b1;
            t17 += v * b2;
            t18 += v * b3;
            t19 += v * b4;
            t20 += v * b5;
            t21 += v * b6;
            t22 += v * b7;
            t23 += v * b8;
            t24 += v * b9;
            t25 += v * b10;
            t26 += v * b11;
            t27 += v * b12;
            t28 += v * b13;
            t29 += v * b14;
            t30 += v * b15;
            t0 += 38 * t16;
            t1 += 38 * t17;
            t2 += 38 * t18;
            t3 += 38 * t19;
            t4 += 38 * t20;
            t5 += 38 * t21;
            t6 += 38 * t22;
            t7 += 38 * t23;
            t8 += 38 * t24;
            t9 += 38 * t25;
            t10 += 38 * t26;
            t11 += 38 * t27;
            t12 += 38 * t28;
            t13 += 38 * t29;
            t14 += 38 * t30;
            // t15 left as is
            // first car
            c = 1;
            v = t0 + c + 65535;
            c = Math.floor(v / 65536);
            t0 = v - c * 65536;
            v = t1 + c + 65535;
            c = Math.floor(v / 65536);
            t1 = v - c * 65536;
            v = t2 + c + 65535;
            c = Math.floor(v / 65536);
            t2 = v - c * 65536;
            v = t3 + c + 65535;
            c = Math.floor(v / 65536);
            t3 = v - c * 65536;
            v = t4 + c + 65535;
            c = Math.floor(v / 65536);
            t4 = v - c * 65536;
            v = t5 + c + 65535;
            c = Math.floor(v / 65536);
            t5 = v - c * 65536;
            v = t6 + c + 65535;
            c = Math.floor(v / 65536);
            t6 = v - c * 65536;
            v = t7 + c + 65535;
            c = Math.floor(v / 65536);
            t7 = v - c * 65536;
            v = t8 + c + 65535;
            c = Math.floor(v / 65536);
            t8 = v - c * 65536;
            v = t9 + c + 65535;
            c = Math.floor(v / 65536);
            t9 = v - c * 65536;
            v = t10 + c + 65535;
            c = Math.floor(v / 65536);
            t10 = v - c * 65536;
            v = t11 + c + 65535;
            c = Math.floor(v / 65536);
            t11 = v - c * 65536;
            v = t12 + c + 65535;
            c = Math.floor(v / 65536);
            t12 = v - c * 65536;
            v = t13 + c + 65535;
            c = Math.floor(v / 65536);
            t13 = v - c * 65536;
            v = t14 + c + 65535;
            c = Math.floor(v / 65536);
            t14 = v - c * 65536;
            v = t15 + c + 65535;
            c = Math.floor(v / 65536);
            t15 = v - c * 65536;
            t0 += c - 1 + 37 * (c - 1);
            // second car
            c = 1;
            v = t0 + c + 65535;
            c = Math.floor(v / 65536);
            t0 = v - c * 65536;
            v = t1 + c + 65535;
            c = Math.floor(v / 65536);
            t1 = v - c * 65536;
            v = t2 + c + 65535;
            c = Math.floor(v / 65536);
            t2 = v - c * 65536;
            v = t3 + c + 65535;
            c = Math.floor(v / 65536);
            t3 = v - c * 65536;
            v = t4 + c + 65535;
            c = Math.floor(v / 65536);
            t4 = v - c * 65536;
            v = t5 + c + 65535;
            c = Math.floor(v / 65536);
            t5 = v - c * 65536;
            v = t6 + c + 65535;
            c = Math.floor(v / 65536);
            t6 = v - c * 65536;
            v = t7 + c + 65535;
            c = Math.floor(v / 65536);
            t7 = v - c * 65536;
            v = t8 + c + 65535;
            c = Math.floor(v / 65536);
            t8 = v - c * 65536;
            v = t9 + c + 65535;
            c = Math.floor(v / 65536);
            t9 = v - c * 65536;
            v = t10 + c + 65535;
            c = Math.floor(v / 65536);
            t10 = v - c * 65536;
            v = t11 + c + 65535;
            c = Math.floor(v / 65536);
            t11 = v - c * 65536;
            v = t12 + c + 65535;
            c = Math.floor(v / 65536);
            t12 = v - c * 65536;
            v = t13 + c + 65535;
            c = Math.floor(v / 65536);
            t13 = v - c * 65536;
            v = t14 + c + 65535;
            c = Math.floor(v / 65536);
            t14 = v - c * 65536;
            v = t15 + c + 65535;
            c = Math.floor(v / 65536);
            t15 = v - c * 65536;
            t0 += c - 1 + 37 * (c - 1);
            o[0] = t0;
            o[1] = t1;
            o[2] = t2;
            o[3] = t3;
            o[4] = t4;
            o[5] = t5;
            o[6] = t6;
            o[7] = t7;
            o[8] = t8;
            o[9] = t9;
            o[10] = t10;
            o[11] = t11;
            o[12] = t12;
            o[13] = t13;
            o[14] = t14;
            o[15] = t15;
        }
        function S(o, a) {
            M(o, a, a);
        }
        function inv25519(o, i) {
            var c = gf();
            var a;
            for (a = 0; a < 16; a++)
                c[a] = i[a];
            for (a = 253; a >= 0; a--) {
                S(c, c);
                if (a !== 2 && a !== 4)
                    M(c, c, i);
            }
            for (a = 0; a < 16; a++)
                o[a] = c[a];
        }
        function pow2523(o, i) {
            var c = gf();
            var a;
            for (a = 0; a < 16; a++)
                c[a] = i[a];
            for (a = 250; a >= 0; a--) {
                S(c, c);
                if (a !== 1)
                    M(c, c, i);
            }
            for (a = 0; a < 16; a++)
                o[a] = c[a];
        }
        function crypto_scalarmult(q, n, p) {
            var z = new Uint8Array(32);
            var x = new Float64Array(80), r, i;
            var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf();
            for (i = 0; i < 31; i++)
                z[i] = n[i];
            z[31] = (n[31] & 127) | 64;
            z[0] &= 248;
            unpack25519(x, p);
            for (i = 0; i < 16; i++) {
                b[i] = x[i];
                d[i] = a[i] = c[i] = 0;
            }
            a[0] = d[0] = 1;
            for (i = 254; i >= 0; --i) {
                r = (z[i >>> 3] >>> (i & 7)) & 1;
                sel25519(a, b, r);
                sel25519(c, d, r);
                A(e, a, c);
                Z(a, a, c);
                A(c, b, d);
                Z(b, b, d);
                S(d, e);
                S(f, a);
                M(a, c, a);
                M(c, b, e);
                A(e, a, c);
                Z(a, a, c);
                S(b, a);
                Z(c, d, f);
                M(a, c, _121665);
                A(a, a, d);
                M(c, c, a);
                M(a, d, f);
                M(d, b, x);
                S(b, e);
                sel25519(a, b, r);
                sel25519(c, d, r);
            }
            for (i = 0; i < 16; i++) {
                x[i + 16] = a[i];
                x[i + 32] = c[i];
                x[i + 48] = b[i];
                x[i + 64] = d[i];
            }
            var x32 = x.subarray(32);
            var x16 = x.subarray(16);
            inv25519(x32, x32);
            M(x16, x16, x32);
            pack25519(q, x16);
            return 0;
        }
        function crypto_scalarmult_base(q, n) {
            return crypto_scalarmult(q, n, _9);
        }
        function crypto_box_keypair(y, x) {
            randombytes(x, 32);
            return crypto_scalarmult_base(y, x);
        }
        function crypto_box_beforenm(k, y, x) {
            var s = new Uint8Array(32);
            crypto_scalarmult(s, x, y);
            return crypto_core_hsalsa20(k, _0, s, sigma);
        }
        var crypto_box_afternm = crypto_secretbox;
        var crypto_box_open_afternm = crypto_secretbox_open;
        function crypto_box(c, m, d, n, y, x) {
            var k = new Uint8Array(32);
            crypto_box_beforenm(k, y, x);
            return crypto_box_afternm(c, m, d, n, k);
        }
        function crypto_box_open(m, c, d, n, y, x) {
            var k = new Uint8Array(32);
            crypto_box_beforenm(k, y, x);
            return crypto_box_open_afternm(m, c, d, n, k);
        }
        var K = [
            0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
            0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
            0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
            0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
            0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
            0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
            0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
            0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
            0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
            0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
            0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
            0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
            0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
            0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
            0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
            0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
            0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
            0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
            0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
            0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
            0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
            0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
            0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
            0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
            0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
            0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
            0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
            0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
            0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
            0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
            0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
            0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
            0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
            0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
            0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
            0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
            0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
            0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
            0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
            0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
        ];
        function crypto_hashblocks_hl(hh, hl, m, n) {
            var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d;
            var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7];
            var pos = 0;
            while (n >= 128) {
                for (i = 0; i < 16; i++) {
                    j = 8 * i + pos;
                    wh[i] = (m[j + 0] << 24) | (m[j + 1] << 16) | (m[j + 2] << 8) | m[j + 3];
                    wl[i] = (m[j + 4] << 24) | (m[j + 5] << 16) | (m[j + 6] << 8) | m[j + 7];
                }
                for (i = 0; i < 80; i++) {
                    bh0 = ah0;
                    bh1 = ah1;
                    bh2 = ah2;
                    bh3 = ah3;
                    bh4 = ah4;
                    bh5 = ah5;
                    bh6 = ah6;
                    bh7 = ah7;
                    bl0 = al0;
                    bl1 = al1;
                    bl2 = al2;
                    bl3 = al3;
                    bl4 = al4;
                    bl5 = al5;
                    bl6 = al6;
                    bl7 = al7;
                    // add
                    h = ah7;
                    l = al7;
                    a = l & 0xffff;
                    b = l >>> 16;
                    c = h & 0xffff;
                    d = h >>> 16;
                    // Sigma1
                    h = ((ah4 >>> 14) | (al4 << (32 - 14))) ^ ((ah4 >>> 18) | (al4 << (32 - 18))) ^ ((al4 >>> (41 - 32)) | (ah4 << (32 - (41 - 32))));
                    l = ((al4 >>> 14) | (ah4 << (32 - 14))) ^ ((al4 >>> 18) | (ah4 << (32 - 18))) ^ ((ah4 >>> (41 - 32)) | (al4 << (32 - (41 - 32))));
                    a += l & 0xffff;
                    b += l >>> 16;
                    c += h & 0xffff;
                    d += h >>> 16;
                    // Ch
                    h = (ah4 & ah5) ^ (~ah4 & ah6);
                    l = (al4 & al5) ^ (~al4 & al6);
                    a += l & 0xffff;
                    b += l >>> 16;
                    c += h & 0xffff;
                    d += h >>> 16;
                    // K
                    h = K[i * 2];
                    l = K[i * 2 + 1];
                    a += l & 0xffff;
                    b += l >>> 16;
                    c += h & 0xffff;
                    d += h >>> 16;
                    // w
                    h = wh[i % 16];
                    l = wl[i % 16];
                    a += l & 0xffff;
                    b += l >>> 16;
                    c += h & 0xffff;
                    d += h >>> 16;
                    b += a >>> 16;
                    c += b >>> 16;
                    d += c >>> 16;
                    th = c & 0xffff | d << 16;
                    tl = a & 0xffff | b << 16;
                    // add
                    h = th;
                    l = tl;
                    a = l & 0xffff;
                    b = l >>> 16;
                    c = h & 0xffff;
                    d = h >>> 16;
                    // Sigma0
                    h = ((ah0 >>> 28) | (al0 << (32 - 28))) ^ ((al0 >>> (34 - 32)) | (ah0 << (32 - (34 - 32)))) ^ ((al0 >>> (39 - 32)) | (ah0 << (32 - (39 - 32))));
                    l = ((al0 >>> 28) | (ah0 << (32 - 28))) ^ ((ah0 >>> (34 - 32)) | (al0 << (32 - (34 - 32)))) ^ ((ah0 >>> (39 - 32)) | (al0 << (32 - (39 - 32))));
                    a += l & 0xffff;
                    b += l >>> 16;
                    c += h & 0xffff;
                    d += h >>> 16;
                    // Maj
                    h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
                    l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
                    a += l & 0xffff;
                    b += l >>> 16;
                    c += h & 0xffff;
                    d += h >>> 16;
                    b += a >>> 16;
                    c += b >>> 16;
                    d += c >>> 16;
                    bh7 = (c & 0xffff) | (d << 16);
                    bl7 = (a & 0xffff) | (b << 16);
                    // add
                    h = bh3;
                    l = bl3;
                    a = l & 0xffff;
                    b = l >>> 16;
                    c = h & 0xffff;
                    d = h >>> 16;
                    h = th;
                    l = tl;
                    a += l & 0xffff;
                    b += l >>> 16;
                    c += h & 0xffff;
                    d += h >>> 16;
                    b += a >>> 16;
                    c += b >>> 16;
                    d += c >>> 16;
                    bh3 = (c & 0xffff) | (d << 16);
                    bl3 = (a & 0xffff) | (b << 16);
                    ah1 = bh0;
                    ah2 = bh1;
                    ah3 = bh2;
                    ah4 = bh3;
                    ah5 = bh4;
                    ah6 = bh5;
                    ah7 = bh6;
                    ah0 = bh7;
                    al1 = bl0;
                    al2 = bl1;
                    al3 = bl2;
                    al4 = bl3;
                    al5 = bl4;
                    al6 = bl5;
                    al7 = bl6;
                    al0 = bl7;
                    if (i % 16 === 15) {
                        for (j = 0; j < 16; j++) {
                            // add
                            h = wh[j];
                            l = wl[j];
                            a = l & 0xffff;
                            b = l >>> 16;
                            c = h & 0xffff;
                            d = h >>> 16;
                            h = wh[(j + 9) % 16];
                            l = wl[(j + 9) % 16];
                            a += l & 0xffff;
                            b += l >>> 16;
                            c += h & 0xffff;
                            d += h >>> 16;
                            // sigma0
                            th = wh[(j + 1) % 16];
                            tl = wl[(j + 1) % 16];
                            h = ((th >>> 1) | (tl << (32 - 1))) ^ ((th >>> 8) | (tl << (32 - 8))) ^ (th >>> 7);
                            l = ((tl >>> 1) | (th << (32 - 1))) ^ ((tl >>> 8) | (th << (32 - 8))) ^ ((tl >>> 7) | (th << (32 - 7)));
                            a += l & 0xffff;
                            b += l >>> 16;
                            c += h & 0xffff;
                            d += h >>> 16;
                            // sigma1
                            th = wh[(j + 14) % 16];
                            tl = wl[(j + 14) % 16];
                            h = ((th >>> 19) | (tl << (32 - 19))) ^ ((tl >>> (61 - 32)) | (th << (32 - (61 - 32)))) ^ (th >>> 6);
                            l = ((tl >>> 19) | (th << (32 - 19))) ^ ((th >>> (61 - 32)) | (tl << (32 - (61 - 32)))) ^ ((tl >>> 6) | (th << (32 - 6)));
                            a += l & 0xffff;
                            b += l >>> 16;
                            c += h & 0xffff;
                            d += h >>> 16;
                            b += a >>> 16;
                            c += b >>> 16;
                            d += c >>> 16;
                            wh[j] = (c & 0xffff) | (d << 16);
                            wl[j] = (a & 0xffff) | (b << 16);
                        }
                    }
                }
                // add
                h = ah0;
                l = al0;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[0];
                l = hl[0];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[0] = ah0 = (c & 0xffff) | (d << 16);
                hl[0] = al0 = (a & 0xffff) | (b << 16);
                h = ah1;
                l = al1;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[1];
                l = hl[1];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[1] = ah1 = (c & 0xffff) | (d << 16);
                hl[1] = al1 = (a & 0xffff) | (b << 16);
                h = ah2;
                l = al2;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[2];
                l = hl[2];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[2] = ah2 = (c & 0xffff) | (d << 16);
                hl[2] = al2 = (a & 0xffff) | (b << 16);
                h = ah3;
                l = al3;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[3];
                l = hl[3];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[3] = ah3 = (c & 0xffff) | (d << 16);
                hl[3] = al3 = (a & 0xffff) | (b << 16);
                h = ah4;
                l = al4;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[4];
                l = hl[4];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[4] = ah4 = (c & 0xffff) | (d << 16);
                hl[4] = al4 = (a & 0xffff) | (b << 16);
                h = ah5;
                l = al5;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[5];
                l = hl[5];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[5] = ah5 = (c & 0xffff) | (d << 16);
                hl[5] = al5 = (a & 0xffff) | (b << 16);
                h = ah6;
                l = al6;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[6];
                l = hl[6];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[6] = ah6 = (c & 0xffff) | (d << 16);
                hl[6] = al6 = (a & 0xffff) | (b << 16);
                h = ah7;
                l = al7;
                a = l & 0xffff;
                b = l >>> 16;
                c = h & 0xffff;
                d = h >>> 16;
                h = hh[7];
                l = hl[7];
                a += l & 0xffff;
                b += l >>> 16;
                c += h & 0xffff;
                d += h >>> 16;
                b += a >>> 16;
                c += b >>> 16;
                d += c >>> 16;
                hh[7] = ah7 = (c & 0xffff) | (d << 16);
                hl[7] = al7 = (a & 0xffff) | (b << 16);
                pos += 128;
                n -= 128;
            }
            return n;
        }
        function crypto_hash(out, m, n) {
            var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n;
            hh[0] = 0x6a09e667;
            hh[1] = 0xbb67ae85;
            hh[2] = 0x3c6ef372;
            hh[3] = 0xa54ff53a;
            hh[4] = 0x510e527f;
            hh[5] = 0x9b05688c;
            hh[6] = 0x1f83d9ab;
            hh[7] = 0x5be0cd19;
            hl[0] = 0xf3bcc908;
            hl[1] = 0x84caa73b;
            hl[2] = 0xfe94f82b;
            hl[3] = 0x5f1d36f1;
            hl[4] = 0xade682d1;
            hl[5] = 0x2b3e6c1f;
            hl[6] = 0xfb41bd6b;
            hl[7] = 0x137e2179;
            crypto_hashblocks_hl(hh, hl, m, n);
            n %= 128;
            for (i = 0; i < n; i++)
                x[i] = m[b - n + i];
            x[n] = 128;
            n = 256 - 128 * (n < 112 ? 1 : 0);
            x[n - 9] = 0;
            ts64(x, n - 8, (b / 0x20000000) | 0, b << 3);
            crypto_hashblocks_hl(hh, hl, x, n);
            for (i = 0; i < 8; i++)
                ts64(out, 8 * i, hh[i], hl[i]);
            return 0;
        }
        function add(p, q) {
            var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf();
            Z(a, p[1], p[0]);
            Z(t, q[1], q[0]);
            M(a, a, t);
            A(b, p[0], p[1]);
            A(t, q[0], q[1]);
            M(b, b, t);
            M(c, p[3], q[3]);
            M(c, c, D2);
            M(d, p[2], q[2]);
            A(d, d, d);
            Z(e, b, a);
            Z(f, d, c);
            A(g, d, c);
            A(h, b, a);
            M(p[0], e, f);
            M(p[1], h, g);
            M(p[2], g, f);
            M(p[3], e, h);
        }
        function cswap(p, q, b) {
            var i;
            for (i = 0; i < 4; i++) {
                sel25519(p[i], q[i], b);
            }
        }
        function pack(r, p) {
            var tx = gf(), ty = gf(), zi = gf();
            inv25519(zi, p[2]);
            M(tx, p[0], zi);
            M(ty, p[1], zi);
            pack25519(r, ty);
            r[31] ^= par25519(tx) << 7;
        }
        function scalarmult(p, q, s) {
            var b, i;
            set25519(p[0], gf0);
            set25519(p[1], gf1);
            set25519(p[2], gf1);
            set25519(p[3], gf0);
            for (i = 255; i >= 0; --i) {
                b = (s[(i / 8) | 0] >> (i & 7)) & 1;
                cswap(p, q, b);
                add(q, p);
                add(p, p);
                cswap(p, q, b);
            }
        }
        function scalarbase(p, s) {
            var q = [gf(), gf(), gf(), gf()];
            set25519(q[0], X);
            set25519(q[1], Y);
            set25519(q[2], gf1);
            M(q[3], X, Y);
            scalarmult(p, q, s);
        }
        function crypto_sign_keypair(pk, sk, seeded) {
            var d = new Uint8Array(64);
            var p = [gf(), gf(), gf(), gf()];
            var i;
            if (!seeded)
                randombytes(sk, 32);
            crypto_hash(d, sk, 32);
            d[0] &= 248;
            d[31] &= 127;
            d[31] |= 64;
            scalarbase(p, d);
            pack(pk, p);
            for (i = 0; i < 32; i++)
                sk[i + 32] = pk[i];
            return 0;
        }
        var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
        function modL(r, x) {
            var carry, i, j, k;
            for (i = 63; i >= 32; --i) {
                carry = 0;
                for (j = i - 32, k = i - 12; j < k; ++j) {
                    x[j] += carry - 16 * x[i] * L[j - (i - 32)];
                    carry = (x[j] + 128) >> 8;
                    x[j] -= carry * 256;
                }
                x[j] += carry;
                x[i] = 0;
            }
            carry = 0;
            for (j = 0; j < 32; j++) {
                x[j] += carry - (x[31] >> 4) * L[j];
                carry = x[j] >> 8;
                x[j] &= 255;
            }
            for (j = 0; j < 32; j++)
                x[j] -= carry * L[j];
            for (i = 0; i < 32; i++) {
                x[i + 1] += x[i] >> 8;
                r[i] = x[i] & 255;
            }
        }
        function reduce(r) {
            var x = new Float64Array(64), i;
            for (i = 0; i < 64; i++)
                x[i] = r[i];
            for (i = 0; i < 64; i++)
                r[i] = 0;
            modL(r, x);
        }
        // Note: difference from C - smlen returned, not passed as argument.
        function crypto_sign(sm, m, n, sk) {
            var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
            var i, j, x = new Float64Array(64);
            var p = [gf(), gf(), gf(), gf()];
            crypto_hash(d, sk, 32);
            d[0] &= 248;
            d[31] &= 127;
            d[31] |= 64;
            var smlen = n + 64;
            for (i = 0; i < n; i++)
                sm[64 + i] = m[i];
            for (i = 0; i < 32; i++)
                sm[32 + i] = d[32 + i];
            crypto_hash(r, sm.subarray(32), n + 32);
            reduce(r);
            scalarbase(p, r);
            pack(sm, p);
            for (i = 32; i < 64; i++)
                sm[i] = sk[i];
            crypto_hash(h, sm, n + 64);
            reduce(h);
            for (i = 0; i < 64; i++)
                x[i] = 0;
            for (i = 0; i < 32; i++)
                x[i] = r[i];
            for (i = 0; i < 32; i++) {
                for (j = 0; j < 32; j++) {
                    x[i + j] += h[i] * d[j];
                }
            }
            modL(sm.subarray(32), x);
            return smlen;
        }
        function unpackneg(r, p) {
            var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
            set25519(r[2], gf1);
            unpack25519(r[1], p);
            S(num, r[1]);
            M(den, num, D);
            Z(num, num, r[2]);
            A(den, r[2], den);
            S(den2, den);
            S(den4, den2);
            M(den6, den4, den2);
            M(t, den6, num);
            M(t, t, den);
            pow2523(t, t);
            M(t, t, num);
            M(t, t, den);
            M(t, t, den);
            M(r[0], t, den);
            S(chk, r[0]);
            M(chk, chk, den);
            if (neq25519(chk, num))
                M(r[0], r[0], I);
            S(chk, r[0]);
            M(chk, chk, den);
            if (neq25519(chk, num))
                return -1;
            if (par25519(r[0]) === (p[31] >> 7))
                Z(r[0], gf0, r[0]);
            M(r[3], r[0], r[1]);
            return 0;
        }
        function crypto_sign_open(m, sm, n, pk) {
            var i, mlen;
            var t = new Uint8Array(32), h = new Uint8Array(64);
            var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()];
            mlen = -1;
            if (n < 64)
                return -1;
            if (unpackneg(q, pk))
                return -1;
            for (i = 0; i < n; i++)
                m[i] = sm[i];
            for (i = 0; i < 32; i++)
                m[i + 32] = pk[i];
            crypto_hash(h, m, n);
            reduce(h);
            scalarmult(p, q, h);
            scalarbase(q, sm.subarray(32));
            add(p, q);
            pack(t, p);
            n -= 64;
            if (crypto_verify_32(sm, 0, t, 0)) {
                for (i = 0; i < n; i++)
                    m[i] = 0;
                return -1;
            }
            for (i = 0; i < n; i++)
                m[i] = sm[i + 64];
            mlen = n;
            return mlen;
        }
        var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64;
        nacl.lowlevel = {
            crypto_core_hsalsa20: crypto_core_hsalsa20,
            crypto_stream_xor: crypto_stream_xor,
            crypto_stream: crypto_stream,
            crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
            crypto_stream_salsa20: crypto_stream_salsa20,
            crypto_onetimeauth: crypto_onetimeauth,
            crypto_onetimeauth_verify: crypto_onetimeauth_verify,
            crypto_verify_16: crypto_verify_16,
            crypto_verify_32: crypto_verify_32,
            crypto_secretbox: crypto_secretbox,
            crypto_secretbox_open: crypto_secretbox_open,
            crypto_scalarmult: crypto_scalarmult,
            crypto_scalarmult_base: crypto_scalarmult_base,
            crypto_box_beforenm: crypto_box_beforenm,
            crypto_box_afternm: crypto_box_afternm,
            crypto_box: crypto_box,
            crypto_box_open: crypto_box_open,
            crypto_box_keypair: crypto_box_keypair,
            crypto_hash: crypto_hash,
            crypto_sign: crypto_sign,
            crypto_sign_keypair: crypto_sign_keypair,
            crypto_sign_open: crypto_sign_open,
            crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
            crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
            crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
            crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
            crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
            crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
            crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
            crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
            crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
            crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
            crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
            crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
            crypto_sign_BYTES: crypto_sign_BYTES,
            crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
            crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
            crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
            crypto_hash_BYTES: crypto_hash_BYTES
        };
        /* High-level API */
        function checkLengths(k, n) {
            if (k.length !== crypto_secretbox_KEYBYTES)
                throw new Error('bad key size');
            if (n.length !== crypto_secretbox_NONCEBYTES)
                throw new Error('bad nonce size');
        }
        function checkBoxLengths(pk, sk) {
            if (pk.length !== crypto_box_PUBLICKEYBYTES)
                throw new Error('bad public key size');
            if (sk.length !== crypto_box_SECRETKEYBYTES)
                throw new Error('bad secret key size');
        }
        function checkArrayTypes() {
            var t, i;
            for (i = 0; i < arguments.length; i++) {
                if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')
                    throw new TypeError('unexpected type ' + t + ', use Uint8Array');
            }
        }
        function cleanup(arr) {
            for (var i = 0; i < arr.length; i++)
                arr[i] = 0;
        }
        // TODO: Completely remove this in v0.15.
        if (!nacl.util) {
            nacl.util = {};
            nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function () {
                throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');
            };
        }
        nacl.randomBytes = function (n) {
            var b = new Uint8Array(n);
            randombytes(b, n);
            return b;
        };
        nacl.secretbox = function (msg, nonce, key) {
            checkArrayTypes(msg, nonce, key);
            checkLengths(key, nonce);
            var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
            var c = new Uint8Array(m.length);
            for (var i = 0; i < msg.length; i++)
                m[i + crypto_secretbox_ZEROBYTES] = msg[i];
            crypto_secretbox(c, m, m.length, nonce, key);
            return c.subarray(crypto_secretbox_BOXZEROBYTES);
        };
        nacl.secretbox.open = function (box, nonce, key) {
            checkArrayTypes(box, nonce, key);
            checkLengths(key, nonce);
            var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
            var m = new Uint8Array(c.length);
            for (var i = 0; i < box.length; i++)
                c[i + crypto_secretbox_BOXZEROBYTES] = box[i];
            if (c.length < 32)
                return false;
            if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0)
                return false;
            return m.subarray(crypto_secretbox_ZEROBYTES);
        };
        nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
        nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
        nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
        nacl.scalarMult = function (n, p) {
            checkArrayTypes(n, p);
            if (n.length !== crypto_scalarmult_SCALARBYTES)
                throw new Error('bad n size');
            if (p.length !== crypto_scalarmult_BYTES)
                throw new Error('bad p size');
            var q = new Uint8Array(crypto_scalarmult_BYTES);
            crypto_scalarmult(q, n, p);
            return q;
        };
        nacl.scalarMult.base = function (n) {
            checkArrayTypes(n);
            if (n.length !== crypto_scalarmult_SCALARBYTES)
                throw new Error('bad n size');
            var q = new Uint8Array(crypto_scalarmult_BYTES);
            crypto_scalarmult_base(q, n);
            return q;
        };
        nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
        nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
        nacl.box = function (msg, nonce, publicKey, secretKey) {
            var k = nacl.box.before(publicKey, secretKey);
            return nacl.secretbox(msg, nonce, k);
        };
        nacl.box.before = function (publicKey, secretKey) {
            checkArrayTypes(publicKey, secretKey);
            checkBoxLengths(publicKey, secretKey);
            var k = new Uint8Array(crypto_box_BEFORENMBYTES);
            crypto_box_beforenm(k, publicKey, secretKey);
            return k;
        };
        nacl.box.after = nacl.secretbox;
        nacl.box.open = function (msg, nonce, publicKey, secretKey) {
            var k = nacl.box.before(publicKey, secretKey);
            return nacl.secretbox.open(msg, nonce, k);
        };
        nacl.box.open.after = nacl.secretbox.open;
        nacl.box.keyPair = function () {
            var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
            var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
            crypto_box_keypair(pk, sk);
            return { publicKey: pk, secretKey: sk };
        };
        nacl.box.keyPair.fromSecretKey = function (secretKey) {
            checkArrayTypes(secretKey);
            if (secretKey.length !== crypto_box_SECRETKEYBYTES)
                throw new Error('bad secret key size');
            var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
            crypto_scalarmult_base(pk, secretKey);
            return { publicKey: pk, secretKey: new Uint8Array(secretKey) };
        };
        nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
        nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
        nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
        nacl.box.nonceLength = crypto_box_NONCEBYTES;
        nacl.box.overheadLength = nacl.secretbox.overheadLength;
        nacl.sign = function (msg, secretKey) {
            checkArrayTypes(msg, secretKey);
            if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
                throw new Error('bad secret key size');
            var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
            crypto_sign(signedMsg, msg, msg.length, secretKey);
            return signedMsg;
        };
        nacl.sign.open = function (signedMsg, publicKey) {
            if (arguments.length !== 2)
                throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');
            checkArrayTypes(signedMsg, publicKey);
            if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
                throw new Error('bad public key size');
            var tmp = new Uint8Array(signedMsg.length);
            var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
            if (mlen < 0)
                return null;
            var m = new Uint8Array(mlen);
            for (var i = 0; i < m.length; i++)
                m[i] = tmp[i];
            return m;
        };
        nacl.sign.detached = function (msg, secretKey) {
            var signedMsg = nacl.sign(msg, secretKey);
            var sig = new Uint8Array(crypto_sign_BYTES);
            for (var i = 0; i < sig.length; i++)
                sig[i] = signedMsg[i];
            return sig;
        };
        nacl.sign.detached.verify = function (msg, sig, publicKey) {
            checkArrayTypes(msg, sig, publicKey);
            if (sig.length !== crypto_sign_BYTES)
                throw new Error('bad signature size');
            if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
                throw new Error('bad public key size');
            var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
            var m = new Uint8Array(crypto_sign_BYTES + msg.length);
            var i;
            for (i = 0; i < crypto_sign_BYTES; i++)
                sm[i] = sig[i];
            for (i = 0; i < msg.length; i++)
                sm[i + crypto_sign_BYTES] = msg[i];
            return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
        };
        nacl.sign.keyPair = function () {
            var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
            var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
            crypto_sign_keypair(pk, sk);
            return { publicKey: pk, secretKey: sk };
        };
        nacl.sign.keyPair.fromSecretKey = function (secretKey) {
            checkArrayTypes(secretKey);
            if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
                throw new Error('bad secret key size');
            var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
            for (var i = 0; i < pk.length; i++)
                pk[i] = secretKey[32 + i];
            return { publicKey: pk, secretKey: new Uint8Array(secretKey) };
        };
        nacl.sign.keyPair.fromSeed = function (seed) {
            checkArrayTypes(seed);
            if (seed.length !== crypto_sign_SEEDBYTES)
                throw new Error('bad seed size');
            var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
            var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
            for (var i = 0; i < 32; i++)
                sk[i] = seed[i];
            crypto_sign_keypair(pk, sk, true);
            return { publicKey: pk, secretKey: sk };
        };
        nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
        nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
        nacl.sign.seedLength = crypto_sign_SEEDBYTES;
        nacl.sign.signatureLength = crypto_sign_BYTES;
        nacl.hash = function (msg) {
            checkArrayTypes(msg);
            var h = new Uint8Array(crypto_hash_BYTES);
            crypto_hash(h, msg, msg.length);
            return h;
        };
        nacl.hash.hashLength = crypto_hash_BYTES;
        nacl.verify = function (x, y) {
            checkArrayTypes(x, y);
            // Zero length arguments are considered not equal.
            if (x.length === 0 || y.length === 0)
                return false;
            if (x.length !== y.length)
                return false;
            return (vn(x, 0, y, 0, x.length) === 0) ? true : false;
        };
        nacl.setPRNG = function (fn) {
            randombytes = fn;
        };
        (function () {
            // Initialize PRNG if environment provides CSPRNG.
            // If not, methods calling randombytes will throw.
            var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
            if (crypto && crypto.getRandomValues) {
                // Browsers.
                var QUOTA = 65536;
                nacl.setPRNG(function (x, n) {
                    var i, v = new Uint8Array(n);
                    for (i = 0; i < n; i += QUOTA) {
                        crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
                    }
                    for (i = 0; i < n; i++)
                        x[i] = v[i];
                    cleanup(v);
                });
            }
            else if (typeof require !== 'undefined') {
                // Node.js.
                crypto = require('crypto');
                if (crypto && crypto.randomBytes) {
                    nacl.setPRNG(function (x, n) {
                        var i, v = crypto.randomBytes(n);
                        for (i = 0; i < n; i++)
                            x[i] = v[i];
                        cleanup(v);
                    });
                }
            }
        })();
    })(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
}
,
/* typescript/lib/typescript */ function _(require, module, exports) {
    var __assign = (this && this.__assign) || function () {
        __assign = Object.assign || function (t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s)
                    if (Object.prototype.hasOwnProperty.call(s, p))
                        t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };
    var __generator = (this && this.__generator) || function (thisArg, body) {
        var _ = { label: 0, sent: function () { if (t[0] & 1)
                throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (_)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    };
    var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    };
    var __extends = (this && this.__extends) || (function () {
        var extendStatics = function (d, b) {
            extendStatics = Object.setPrototypeOf ||
                ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                function (d, b) { for (var p in b)
                    if (b.hasOwnProperty(p))
                        d[p] = b[p]; };
            return extendStatics(d, b);
        };
        return function (d, b) {
            extendStatics(d, b);
            function __() { this.constructor = d; }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
        };
    })();
    var ts;
    (function (ts) {
        // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
        // If changing the text in this section, be sure to test `configureNightly` too.
        ts.versionMajorMinor = "3.1";
        /** The version of the TypeScript compiler release */
        ts.version = ts.versionMajorMinor + ".6";
    })(ts || (ts = {}));
    (function (ts) {
        /* @internal */
        var Comparison;
        (function (Comparison) {
            Comparison[Comparison["LessThan"] = -1] = "LessThan";
            Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
            Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
        })(Comparison = ts.Comparison || (ts.Comparison = {}));
    })(ts || (ts = {}));
    /* @internal */
    (function (ts) {
        ts.emptyArray = [];
        /** Create a MapLike with good performance. */
        function createDictionaryObject() {
            var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword
            // Using 'delete' on an object causes V8 to put the object in dictionary mode.
            // This disables creation of hidden classes, which are expensive when an object is
            // constantly changing shape.
            map.__ = undefined;
            delete map.__;
            return map;
        }
        /** Create a new map. If a template object is provided, the map will copy entries from it. */
        function createMap() {
            return new ts.MapCtr();
        }
        ts.createMap = createMap;
        function createMapFromEntries(entries) {
            var map = createMap();
            for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
                var _a = entries_1[_i], key = _a[0], value = _a[1];
                map.set(key, value);
            }
            return map;
        }
        ts.createMapFromEntries = createMapFromEntries;
        function createMapFromTemplate(template) {
            var map = new ts.MapCtr();
            // Copies keys/values from template. Note that for..in will not throw if
            // template is undefined, and instead will just exit the loop.
            for (var key in template) {
                if (hasOwnProperty.call(template, key)) {
                    map.set(key, template[key]);
                }
            }
            return map;
        }
        ts.createMapFromTemplate = createMapFromTemplate;
        // Internet Explorer's Map doesn't support iteration, so don't use it.
        // tslint:disable-next-line no-in-operator variable-name
        ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
        // Keep the class inside a function so it doesn't get compiled if it's not used.
        function shimMap() {
            var MapIterator = /** @class */ (function () {
                function MapIterator(data, selector) {
                    this.index = 0;
                    this.data = data;
                    this.selector = selector;
                    this.keys = Object.keys(data);
                }
                MapIterator.prototype.next = function () {
                    var index = this.index;
                    if (index < this.keys.length) {
                        this.index++;
                        return { value: this.selector(this.data, this.keys[index]), done: false };
                    }
                    return { value: undefined, done: true };
                };
                return MapIterator;
            }());
            return /** @class */ (function () {
                function class_1() {
                    this.data = createDictionaryObject();
                    this.size = 0;
                }
                class_1.prototype.get = function (key) {
                    return this.data[key];
                };
                class_1.prototype.set = function (key, value) {
                    if (!this.has(key)) {
                        this.size++;
                    }
                    this.data[key] = value;
                    return this;
                };
                class_1.prototype.has = function (key) {
                    // tslint:disable-next-line:no-in-operator
                    return key in this.data;
                };
                class_1.prototype.delete = function (key) {
                    if (this.has(key)) {
                        this.size--;
                        delete this.data[key];
                        return true;
                    }
                    return false;
                };
                class_1.prototype.clear = function () {
                    this.data = createDictionaryObject();
                    this.size = 0;
                };
                class_1.prototype.keys = function () {
                    return new MapIterator(this.data, function (_data, key) { return key; });
                };
                class_1.prototype.values = function () {
                    return new MapIterator(this.data, function (data, key) { return data[key]; });
                };
                class_1.prototype.entries = function () {
                    return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
                };
                class_1.prototype.forEach = function (action) {
                    for (var key in this.data) {
                        action(this.data[key], key);
                    }
                };
                return class_1;
            }());
        }
        function length(array) {
            return array ? array.length : 0;
        }
        ts.length = length;
        /**
         * Iterates through 'array' by index and performs the callback on each element of array until the callback
         * returns a truthy value, then returns that value.
         * If no such value is found, the callback is applied to each element of array and undefined is returned.
         */
        function forEach(array, callback) {
            if (array) {
                for (var i = 0; i < array.length; i++) {
                    var result = callback(array[i], i);
                    if (result) {
                        return result;
                    }
                }
            }
            return undefined;
        }
        ts.forEach = forEach;
        /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
        function firstDefined(array, callback) {
            if (array === undefined) {
                return undefined;
            }
            for (var i = 0; i < array.length; i++) {
                var result = callback(array[i], i);
                if (result !== undefined) {
                    return result;
                }
            }
            return undefined;
        }
        ts.firstDefined = firstDefined;
        function firstDefinedIterator(iter, callback) {
            while (true) {
                var _a = iter.next(), value = _a.value, done = _a.done;
                if (done) {
                    return undefined;
                }
                var result = callback(value);
                if (result !== undefined) {
                    return result;
                }
            }
        }
        ts.firstDefinedIterator = firstDefinedIterator;
        function zipWith(arrayA, arrayB, callback) {
            var result = [];
            Debug.assertEqual(arrayA.length, arrayB.length);
            for (var i = 0; i < arrayA.length; i++) {
                result.push(callback(arrayA[i], arrayB[i], i));
            }
            return result;
        }
        ts.zipWith = zipWith;
        function zipToIterator(arrayA, arrayB) {
            Debug.assertEqual(arrayA.length, arrayB.length);
            var i = 0;
            return {
                next: function () {
                    if (i === arrayA.length) {
                        return { value: undefined, done: true };
                    }
                    i++;
                    return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
                }
            };
        }
        ts.zipToIterator = zipToIterator;
        function zipToMap(keys, values) {
            Debug.assert(keys.length === values.length);
            var map = createMap();
            for (var i = 0; i < keys.length; ++i) {
                map.set(keys[i], values[i]);
            }
            return map;
        }
        ts.zipToMap = zipToMap;
        /**
         * Iterates through `array` by index and performs the callback on each element of array until the callback
         * returns a falsey value, then returns false.
         * If no such value is found, the callback is applied to each element of array and `true` is returned.
         */
        function every(array, callback) {
            if (array) {
                for (var i = 0; i < array.length; i++) {
                    if (!callback(array[i], i)) {
                        return false;
                    }
                }
            }
            return true;
        }
        ts.every = every;
        function find(array, predicate) {
            for (var i = 0; i < array.length; i++) {
                var value = array[i];
                if (predicate(value, i)) {
                    return value;
                }
            }
            return undefined;
        }
        ts.find = find;
        function findLast(array, predicate) {
            for (var i = array.length - 1; i >= 0; i--) {
                var value = array[i];
                if (predicate(value, i)) {
                    return value;
                }
            }
            return undefined;
        }
        ts.findLast = findLast;
        /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
        function findIndex(array, predicate, startIndex) {
            for (var i = startIndex || 0; i < array.length; i++) {
                if (predicate(array[i], i)) {
                    return i;
                }
            }
            return -1;
        }
        ts.findIndex = findIndex;
        function findLastIndex(array, predicate, startIndex) {
            for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
                if (predicate(array[i], i)) {
                    return i;
                }
            }
            return -1;
        }
        ts.findLastIndex = findLastIndex;
        /**
         * Returns the first truthy result of `callback`, or else fails.
         * This is like `forEach`, but never returns undefined.
         */
        function findMap(array, callback) {
            for (var i = 0; i < array.length; i++) {
                var result = callback(array[i], i);
                if (result) {
                    return result;
                }
            }
            return Debug.fail();
        }
        ts.findMap = findMap;
        function contains(array, value, equalityComparer) {
            if (equalityComparer === void 0) {
                equalityComparer = equateValues;
            }
            if (array) {
                for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
                    var v = array_1[_i];
                    if (equalityComparer(v, value)) {
                        return true;
                    }
                }
            }
            return false;
        }
        ts.contains = contains;
        function arraysEqual(a, b, equalityComparer) {
            if (equalityComparer === void 0) {
                equalityComparer = equateValues;
            }
            return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
        }
        ts.arraysEqual = arraysEqual;
        function indexOfAnyCharCode(text, charCodes, start) {
            for (var i = start || 0; i < text.length; i++) {
                if (contains(charCodes, text.charCodeAt(i))) {
                    return i;
                }
            }
            return -1;
        }
        ts.indexOfAnyCharCode = indexOfAnyCharCode;
        function countWhere(array, predicate) {
            var count = 0;
            if (array) {
                for (var i = 0; i < array.length; i++) {
                    var v = array[i];
                    if (predicate(v, i)) {
                        count++;
                    }
                }
            }
            return count;
        }
        ts.countWhere = countWhere;
        function filter(array, f) {
            if (array) {
                var len = array.length;
                var i = 0;
                while (i < len && f(array[i]))
                    i++;
                if (i < len) {
                    var result = array.slice(0, i);
                    i++;
                    while (i < len) {
                        var item = array[i];
                        if (f(item)) {
                            result.push(item);
                        }
                        i++;
                    }
                    return result;
                }
            }
            return array;
        }
        ts.filter = filter;
        function filterMutate(array, f) {
            var outIndex = 0;
            for (var i = 0; i < array.length; i++) {
                if (f(array[i], i, array)) {
                    array[outIndex] = array[i];
                    outIndex++;
                }
            }
            array.length = outIndex;
        }
        ts.filterMutate = filterMutate;
        function clear(array) {
            array.length = 0;
        }
        ts.clear = clear;
        function map(array, f) {
            var result;
            if (array) {
                result = [];
                for (var i = 0; i < array.length; i++) {
                    result.push(f(array[i], i));
                }
            }
            return result;
        }
        ts.map = map;
        function mapIterator(iter, mapFn) {
            return {
                next: function () {
                    var iterRes = iter.next();
                    return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
                }
            };
        }
        ts.mapIterator = mapIterator;
        function sameMap(array, f) {
            if (array) {
                for (var i = 0; i < array.length; i++) {
                    var item = array[i];
                    var mapped = f(item, i);
                    if (item !== mapped) {
                        var result = array.slice(0, i);
                        result.push(mapped);
                        for (i++; i < array.length; i++) {
                            result.push(f(array[i], i));
                        }
                        return result;
                    }
                }
            }
            return array;
        }
        ts.sameMap = sameMap;
        function flatten(array) {
            var result;
            if (array) {
                result = [];
                for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
                    var v = array_2[_i];
                    if (v) {
                        if (isArray(v)) {
                            addRange(result, v);
                        }
                        else {
                            result.push(v);
                        }
                    }
                }
            }
            return result;
        }
        ts.flatten = flatten;
        function flatMap(array, mapfn) {
            var result;
            if (array) {
                result = [];
                for (var i = 0; i < array.length; i++) {
                    var v = mapfn(array[i], i);
                    if (v) {
                        if (isArray(v)) {
                            addRange(result, v);
                        }
                        else {
                            result.push(v);
                        }
                    }
                }
            }
            return result;
        }
        ts.flatMap = flatMap;
        function flatMapIterator(iter, mapfn) {
            var first = iter.next();
            if (first.done) {
                return ts.emptyIterator;
            }
            var currentIter = getIterator(first.value);
            return {
                next: function () {
                    while (true) {
                        var currentRes = currentIter.next();
                        if (!currentRes.done) {
                            return currentRes;
                        }
                        var iterRes = iter.next();
                        if (iterRes.done) {
                            return iterRes;
                        }
                        currentIter = getIterator(iterRes.value);
                    }
                },
            };
            function getIterator(x) {
                var res = mapfn(x);
                return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
            }
        }
        ts.flatMapIterator = flatMapIterator;
        function sameFlatMap(array, mapfn) {
            var result;
            if (array) {
                for (var i = 0; i < array.length; i++) {
                    var item = array[i];
                    var mapped = mapfn(item, i);
                    if (result || item !== mapped || isArray(mapped)) {
                        if (!result) {
                            result = array.slice(0, i);
                        }
                        if (isArray(mapped)) {
                            addRange(result, mapped);
                        }
                        else {
                            result.push(mapped);
                        }
                    }
                }
            }
            return result || array;
        }
        ts.sameFlatMap = sameFlatMap;
        function mapAllOrFail(array, mapFn) {
            var result = [];
            for (var i = 0; i < array.length; i++) {
                var mapped = mapFn(array[i], i);
                if (mapped === undefined) {
                    return undefined;
                }
                result.push(mapped);
            }
            return result;
        }
        ts.mapAllOrFail = mapAllOrFail;
        function mapDefined(array, mapFn) {
            var result = [];
            if (array) {
                for (var i = 0; i < array.length; i++) {
                    var mapped = mapFn(array[i], i);
                    if (mapped !== undefined) {
                        result.push(mapped);
                    }
                }
            }
            return result;
        }
        ts.mapDefined = mapDefined;
        function mapDefinedIterator(iter, mapFn) {
            return {
                next: function () {
                    while (true) {
                        var res = iter.next();
                        if (res.done) {
                            return res;
                        }
                        var value = mapFn(res.value);
                        if (value !== undefined) {
                            return { value: value, done: false };
                        }
                    }
                }
            };
        }
        ts.mapDefinedIterator = mapDefinedIterator;
        ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
        function singleIterator(value) {
            var done = false;
            return {
                next: function () {
                    var wasDone = done;
                    done = true;
                    return wasDone ? { value: undefined, done: true } : { value: value, done: false };
                }
            };
        }
        ts.singleIterator = singleIterator;
        function spanMap(array, keyfn, mapfn) {
            var result;
            if (array) {
                result = [];
                var len = array.length;
                var previousKey = void 0;
                var key = void 0;
                var start = 0;
                var pos = 0;
                while (start < len) {
                    while (pos < len) {
                        var value = array[pos];
                        key = keyfn(value, pos);
                        if (pos === 0) {
                            previousKey = key;
                        }
                        else if (key !== previousKey) {
                            break;
                        }
                        pos++;
                    }
                    if (start < pos) {
                        var v = mapfn(array.slice(start, pos), previousKey, start, pos);
                        if (v) {
                            result.push(v);
                        }
                        start = pos;
                    }
                    previousKey = key;
                    pos++;
                }
            }
            return result;
        }
        ts.spanMap = spanMap;
        function mapEntries(map, f) {
            if (!map) {
                return undefined;
            }
            var result = createMap();
            map.forEach(function (value, key) {
                var _a = f(key, value), newKey = _a[0], newValue = _a[1];
                result.set(newKey, newValue);
            });
            return result;
        }
        ts.mapEntries = mapEntries;
        function some(array, predicate) {
            if (array) {
                if (predicate) {
                    for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
                        var v = array_3[_i];
                        if (predicate(v)) {
                            return true;
                        }
                    }
                }
                else {
                    return array.length > 0;
                }
            }
            return false;
        }
        ts.some = some;
        /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
        function getRangesWhere(arr, pred, cb) {
            var start;
            for (var i = 0; i < arr.length; i++) {
                if (pred(arr[i])) {
                    start = start === undefined ? i : start;
                }
                else {
                    if (start !== undefined) {
                        cb(start, i);
                        start = undefined;
                    }
                }
            }
            if (start !== undefined)
                cb(start, arr.length);
        }
        ts.getRangesWhere = getRangesWhere;
        function concatenate(array1, array2) {
            if (!some(array2))
                return array1;
            if (!some(array1))
                return array2;
            return array1.concat(array2);
        }
        ts.concatenate = concatenate;
        function deduplicateRelational(array, equalityComparer, comparer) {
            // Perform a stable sort of the array. This ensures the first entry in a list of
            // duplicates remains the first entry in the result.
            var indices = array.map(function (_, i) { return i; });
            stableSortIndices(array, indices, comparer);
            var last = array[indices[0]];
            var deduplicated = [indices[0]];
            for (var i = 1; i < indices.length; i++) {
                var index = indices[i];
                var item = array[index];
                if (!equalityComparer(last, item)) {
                    deduplicated.push(index);
                    last = item;
                }
            }
            // restore original order
            deduplicated.sort();
            return deduplicated.map(function (i) { return array[i]; });
        }
        function deduplicateEquality(array, equalityComparer) {
            var result = [];
            for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
                var item = array_4[_i];
                pushIfUnique(result, item, equalityComparer);
            }
            return result;
        }
        /**
         * Deduplicates an unsorted array.
         * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
         * @param comparer An optional `Comparer` used to sort entries before comparison, though the
         * result will remain in the original order in `array`.
         */
        function deduplicate(array, equalityComparer, comparer) {
            return array.length === 0 ? [] :
                array.length === 1 ? array.slice() :
                    comparer ? deduplicateRelational(array, equalityComparer, comparer) :
                        deduplicateEquality(array, equalityComparer);
        }
        ts.deduplicate = deduplicate;
        /**
         * Deduplicates an array that has already been sorted.
         */
        function deduplicateSorted(array, comparer) {
            if (array.length === 0)
                return [];
            var last = array[0];
            var deduplicated = [last];
            for (var i = 1; i < array.length; i++) {
                var next = array[i];
                switch (comparer(next, last)) {
                    // equality comparison
                    case true:
                    // relational comparison
                    case 0 /* EqualTo */:
                        continue;
                    case -1 /* LessThan */:
                        // If `array` is sorted, `next` should **never** be less than `last`.
                        return Debug.fail("Array is unsorted.");
                }
                deduplicated.push(last = next);
            }
            return deduplicated;
        }
        function insertSorted(array, insert, compare) {
            if (array.length === 0) {
                array.push(insert);
                return;
            }
            var insertIndex = binarySearch(array, insert, identity, compare);
            if (insertIndex < 0) {
                array.splice(~insertIndex, 0, insert);
            }
        }
        ts.insertSorted = insertSorted;
        function sortAndDeduplicate(array, comparer, equalityComparer) {
            return deduplicateSorted(sort(array, comparer), equalityComparer || comparer);
        }
        ts.sortAndDeduplicate = sortAndDeduplicate;
        function arrayIsEqualTo(array1, array2, equalityComparer) {
            if (equalityComparer === void 0) {
                equalityComparer = equateValues;
            }
            if (!array1 || !array2) {
                return array1 === array2;
            }
            if (array1.length !== array2.length) {
                return false;
            }
            for (var i = 0; i < array1.length; i++) {
                if (!equalityComparer(array1[i], array2[i], i)) {
                    return false;
                }
            }
            return true;
        }
        ts.arrayIsEqualTo = arrayIsEqualTo;
        function compact(array) {
            var result;
            if (array) {
                for (var i = 0; i < array.length; i++) {
                    var v = array[i];
                    if (result || !v) {
                        if (!result) {
                            result = array.slice(0, i);
                        }
                        if (v) {
                            result.push(v);
                        }
                    }
                }
            }
            return result || array;
        }
        ts.compact = compact;
        /**
         * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
         * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
         * based on the provided comparer.
         */
        function relativeComplement(arrayA, arrayB, comparer) {
            if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
                return arrayB;
            var result = [];
            loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
                if (offsetB > 0) {
                    // Ensure `arrayB` is properly sorted.
                    Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
                }
                loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
                    if (offsetA > startA) {
                        // Ensure `arrayA` is properly sorted. We only need to perform this check if
                        // `offsetA` has changed since we entered the loop.
                        Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
                    }
                    switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
                        case -1 /* LessThan */:
                            // If B is less than A, B does not exist in arrayA. Add B to the result and
                            // move to the next element in arrayB without changing the current position
                            // in arrayA.
                            result.push(arrayB[offsetB]);
                            continue loopB;
                        case 0 /* EqualTo */:
                            // If B is equal to A, B exists in arrayA. Move to the next element in
                            // arrayB without adding B to the result or changing the current position
                            // in arrayA.
                            continue loopB;
                        case 1 /* GreaterThan */:
                            // If B is greater than A, we need to keep looking for B in arrayA. Move to
                            // the next element in arrayA and recheck.
                            continue loopA;
                    }
                }
            }
            return result;
        }
        ts.relativeComplement = relativeComplement;
        function sum(array, prop) {
            var result = 0;
            for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
                var v = array_5[_i];
                result += v[prop];
            }
            return result;
        }
        ts.sum = sum;
        function append(to, value) {
            if (value === undefined)
                return to;
            if (to === undefined)
                return [value];
            to.push(value);
            return to;
        }
        ts.append = append;
        /**
         * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
         * position offset from the end of the array.
         */
        function toOffset(array, offset) {
            return offset < 0 ? array.length + offset : offset;
        }
        function addRange(to, from, start, end) {
            if (from === undefined || from.length === 0)
                return to;
            if (to === undefined)
                return from.slice(start, end);
            start = start === undefined ? 0 : toOffset(from, start);
            end = end === undefined ? from.length : toOffset(from, end);
            for (var i = start; i < end && i < from.length; i++) {
                if (from[i] !== undefined) {
                    to.push(from[i]);
                }
            }
            return to;
        }
        ts.addRange = addRange;
        /**
         * @return Whether the value was added.
         */
        function pushIfUnique(array, toAdd, equalityComparer) {
            if (contains(array, toAdd, equalityComparer)) {
                return false;
            }
            else {
                array.push(toAdd);
                return true;
            }
        }
        ts.pushIfUnique = pushIfUnique;
        /**
         * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
         */
        function appendIfUnique(array, toAdd, equalityComparer) {
            if (array) {
                pushIfUnique(array, toAdd, equalityComparer);
                return array;
            }
            else {
                return [toAdd];
            }
        }
        ts.appendIfUnique = appendIfUnique;
        function stableSortIndices(array, indices, comparer) {
            // sort indices by value then position
            indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
        }
        /**
         * Returns a new sorted array.
         */
        function sort(array, comparer) {
            return array.slice().sort(comparer);
        }
        ts.sort = sort;
        function arrayIterator(array) {
            var i = 0;
            return { next: function () {
                    if (i === array.length) {
                        return { value: undefined, done: true };
                    }
                    else {
                        i++;
                        return { value: array[i - 1], done: false };
                    }
                } };
        }
        ts.arrayIterator = arrayIterator;
        /**
         * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
         */
        function stableSort(array, comparer) {
            var indices = array.map(function (_, i) { return i; });
            stableSortIndices(array, indices, comparer);
            return indices.map(function (i) { return array[i]; });
        }
        ts.stableSort = stableSort;
        function rangeEquals(array1, array2, pos, end) {
            while (pos < end) {
                if (array1[pos] !== array2[pos]) {
                    return false;
                }
                pos++;
            }
            return true;
        }
        ts.rangeEquals = rangeEquals;
        /**
         * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
         * A negative offset indicates the element should be retrieved from the end of the array.
         */
        function elementAt(array, offset) {
            if (array) {
                offset = toOffset(array, offset);
                if (offset < array.length) {
                    return array[offset];
                }
            }
            return undefined;
        }
        ts.elementAt = elementAt;
        /**
         * Returns the first element of an array if non-empty, `undefined` otherwise.
         */
        function firstOrUndefined(array) {
            return array.length === 0 ? undefined : array[0];
        }
        ts.firstOrUndefined = firstOrUndefined;
        function first(array) {
            Debug.assert(array.length !== 0);
            return array[0];
        }
        ts.first = first;
        /**
         * Returns the last element of an array if non-empty, `undefined` otherwise.
         */
        function lastOrUndefined(array) {
            return array.length === 0 ? undefined : array[array.length - 1];
        }
        ts.lastOrUndefined = lastOrUndefined;
        function last(array) {
            Debug.assert(array.length !== 0);
            return array[array.length - 1];
        }
        ts.last = last;
        /**
         * Returns the only element of an array if it contains only one element, `undefined` otherwise.
         */
        function singleOrUndefined(array) {
            return array && array.length === 1
                ? array[0]
                : undefined;
        }
        ts.singleOrUndefined = singleOrUndefined;
        function singleOrMany(array) {
            return array && array.length === 1
                ? array[0]
                : array;
        }
        ts.singleOrMany = singleOrMany;
        function replaceElement(array, index, value) {
            var result = array.slice(0);
            result[index] = value;
            return result;
        }
        ts.replaceElement = replaceElement;
        /**
         * Performs a binary search, finding the index at which `value` occurs in `array`.
         * If no such index is found, returns the 2's-complement of first index at which
         * `array[index]` exceeds `value`.
         * @param array A sorted array whose first element must be no larger than number
         * @param value The value to be searched for in the array.
         * @param keySelector A callback used to select the search key from `value` and each element of
         * `array`.
         * @param keyComparer A callback used to compare two keys in a sorted array.
         * @param offset An offset into `array` at which to start the search.
         */
        function binarySearch(array, value, keySelector, keyComparer, offset) {
            if (!array || array.length === 0) {
                return -1;
            }
            var low = offset || 0;
            var high = array.length - 1;
            var key = keySelector(value);
            while (low <= high) {
                var middle = low + ((high - low) >> 1);
                var midKey = keySelector(array[middle]);
                switch (keyComparer(midKey, key)) {
                    case -1 /* LessThan */:
                        low = middle + 1;
                        break;
                    case 0 /* EqualTo */:
                        return middle;
                    case 1 /* GreaterThan */:
                        high = middle - 1;
                        break;
                }
            }
            return ~low;
        }
        ts.binarySearch = binarySearch;
        function reduceLeft(array, f, initial, start, count) {
            if (array && array.length > 0) {
                var size = array.length;
                if (size > 0) {
                    var pos = start === undefined || start < 0 ? 0 : start;
                    var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
                    var result = void 0;
                    if (arguments.length <= 2) {
                        result = array[pos];
                        pos++;
                    }
                    else {
                        result = initial;
                    }
                    while (pos <= end) {
                        result = f(result, array[pos], pos);
                        pos++;
                    }
                    return result;
                }
            }
            return initial;
        }
        ts.reduceLeft = reduceLeft;
        var hasOwnProperty = Object.prototype.hasOwnProperty;
        /**
         * Indicates whether a map-like contains an own property with the specified key.
         *
         * @param map A map-like.
         * @param key A property key.
         */
        function hasProperty(map, key) {
            return hasOwnProperty.call(map, key);
        }
        ts.hasProperty = hasProperty;
        /**
         * Gets the value of an owned property in a map-like.
         *
         * @param map A map-like.
         * @param key A property key.
         */
        function getProperty(map, key) {
            return hasOwnProperty.call(map, key) ? map[key] : undefined;
        }
        ts.getProperty = getProperty;
        /**
         * Gets the owned, enumerable property keys of a map-like.
         */
        function getOwnKeys(map) {
            var keys = [];
            for (var key in map) {
                if (hasOwnProperty.call(map, key)) {
                    keys.push(key);
                }
            }
            return keys;
        }
        ts.getOwnKeys = getOwnKeys;
        function getOwnValues(sparseArray) {
            var values = [];
            for (var key in sparseArray) {
                if (hasOwnProperty.call(sparseArray, key)) {
                    values.push(sparseArray[key]);
                }
            }
            return values;
        }
        ts.getOwnValues = getOwnValues;
        function arrayFrom(iterator, map) {
            var _a;
            var result = [];
            for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
                result.push(map ? map(value) : value);
            }
            return result;
        }
        ts.arrayFrom = arrayFrom;
        function assign(t) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
                var arg = args_1[_a];
                for (var p in arg) {
                    if (hasProperty(arg, p)) {
                        t[p] = arg[p]; // TODO: GH#23368
                    }
                }
            }
            return t;
        }
        ts.assign = assign;
        /**
         * Performs a shallow equality comparison of the contents of two map-likes.
         *
         * @param left A map-like whose properties should be compared.
         * @param right A map-like whose properties should be compared.
         */
        function equalOwnProperties(left, right, equalityComparer) {
            if (equalityComparer === void 0) {
                equalityComparer = equateValues;
            }
            if (left === right)
                return true;
            if (!left || !right)
                return false;
            for (var key in left) {
                if (hasOwnProperty.call(left, key)) {
                    if (!hasOwnProperty.call(right, key))
                        return false;
                    if (!equalityComparer(left[key], right[key]))
                        return false;
                }
            }
            for (var key in right) {
                if (hasOwnProperty.call(right, key)) {
                    if (!hasOwnProperty.call(left, key))
                        return false;
                }
            }
            return true;
        }
        ts.equalOwnProperties = equalOwnProperties;
        function arrayToMap(array, makeKey, makeValue) {
            if (makeValue === void 0) {
                makeValue = identity;
            }
            var result = createMap();
            for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
                var value = array_6[_i];
                var key = makeKey(value);
                if (key !== undefined)
                    result.set(key, makeValue(value));
            }
            return result;
        }
        ts.arrayToMap = arrayToMap;
        function arrayToNumericMap(array, makeKey, makeValue) {
            if (makeValue === void 0) {
                makeValue = identity;
            }
            var result = [];
            for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
                var value = array_7[_i];
                result[makeKey(value)] = makeValue(value);
            }
            return result;
        }
        ts.arrayToNumericMap = arrayToNumericMap;
        function arrayToMultiMap(values, makeKey, makeValue) {
            if (makeValue === void 0) {
                makeValue = identity;
            }
            var result = createMultiMap();
            for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
                var value = values_1[_i];
                result.add(makeKey(value), makeValue(value));
            }
            return result;
        }
        ts.arrayToMultiMap = arrayToMultiMap;
        function group(values, getGroupId) {
            return arrayFrom(arrayToMultiMap(values, getGroupId).values());
        }
        ts.group = group;
        function clone(object) {
            var result = {};
            for (var id in object) {
                if (hasOwnProperty.call(object, id)) {
                    result[id] = object[id];
                }
            }
            return result;
        }
        ts.clone = clone;
        function extend(first, second) {
            var result = {};
            for (var id in second) {
                if (hasOwnProperty.call(second, id)) {
                    result[id] = second[id];
                }
            }
            for (var id in first) {
                if (hasOwnProperty.call(first, id)) {
                    result[id] = first[id];
                }
            }
            return result;
        }
        ts.extend = extend;
        function createMultiMap() {
            var map = createMap();
            map.add = multiMapAdd;
            map.remove = multiMapRemove;
            return map;
        }
        ts.createMultiMap = createMultiMap;
        function multiMapAdd(key, value) {
            var values = this.get(key);
            if (values) {
                values.push(value);
            }
            else {
                this.set(key, values = [value]);
            }
            return values;
        }
        function multiMapRemove(key, value) {
            var values = this.get(key);
            if (values) {
                unorderedRemoveItem(values, value);
                if (!values.length) {
                    this.delete(key);
                }
            }
        }
        /**
         * Tests whether a value is an array.
         */
        function isArray(value) {
            return Array.isArray ? Array.isArray(value) : value instanceof Array;
        }
        ts.isArray = isArray;
        function toArray(value) {
            return isArray(value) ? value : [value];
        }
        ts.toArray = toArray;
        /**
         * Tests whether a value is string
         */
        function isString(text) {
            return typeof text === "string";
        }
        ts.isString = isString;
        function isNumber(x) {
            return typeof x === "number";
        }
        ts.isNumber = isNumber;
        function tryCast(value, test) {
            return value !== undefined && test(value) ? value : undefined;
        }
        ts.tryCast = tryCast;
        function cast(value, test) {
            if (value !== undefined && test(value))
                return value;
            return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'.");
        }
        ts.cast = cast;
        /** Does nothing. */
        function noop(_) { } // tslint:disable-line no-empty
        ts.noop = noop;
        /** Do nothing and return false */
        function returnFalse() { return false; }
        ts.returnFalse = returnFalse;
        /** Do nothing and return true */
        function returnTrue() { return true; }
        ts.returnTrue = returnTrue;
        /** Returns its argument. */
        function identity(x) { return x; }
        ts.identity = identity;
        /** Returns lower case string */
        function toLowerCase(x) { return x.toLowerCase(); }
        ts.toLowerCase = toLowerCase;
        /** Throws an error because a function is not implemented. */
        function notImplemented() {
            throw new Error("Not implemented");
        }
        ts.notImplemented = notImplemented;
        function memoize(callback) {
            var value;
            return function () {
                if (callback) {
                    value = callback();
                    callback = undefined;
                }
                return value;
            };
        }
        ts.memoize = memoize;
        function chain(a, b, c, d, e) {
            if (e) {
                var args_2 = [];
                for (var i = 0; i < arguments.length; i++) {
                    args_2[i] = arguments[i];
                }
                return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); };
            }
            else if (d) {
                return function (t) { return compose(a(t), b(t), c(t), d(t)); };
            }
            else if (c) {
                return function (t) { return compose(a(t), b(t), c(t)); };
            }
            else if (b) {
                return function (t) { return compose(a(t), b(t)); };
            }
            else if (a) {
                return function (t) { return compose(a(t)); };
            }
            else {
                return function (_) { return function (u) { return u; }; };
            }
        }
        ts.chain = chain;
        function compose(a, b, c, d, e) {
            if (e) {
                var args_3 = [];
                for (var i = 0; i < arguments.length; i++) {
                    args_3[i] = arguments[i];
                }
                return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); };
            }
            else if (d) {
                return function (t) { return d(c(b(a(t)))); };
            }
            else if (c) {
                return function (t) { return c(b(a(t))); };
            }
            else if (b) {
                return function (t) { return b(a(t)); };
            }
            else if (a) {
                return function (t) { return a(t); };
            }
            else {
                return function (t) { return t; };
            }
        }
        ts.compose = compose;
        var AssertionLevel;
        (function (AssertionLevel) {
            AssertionLevel[AssertionLevel["None"] = 0] = "None";
            AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
            AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
            AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
        })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
        var Debug;
        (function (Debug) {
            Debug.currentAssertionLevel = 0 /* None */;
            Debug.isDebugging = false;
            function shouldAssert(level) {
                return Debug.currentAssertionLevel >= level;
            }
            Debug.shouldAssert = shouldAssert;
            function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
                if (!expression) {
                    if (verboseDebugInfo) {
                        message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
                    }
                    fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
                }
            }
            Debug.assert = assert;
            function assertEqual(a, b, msg, msg2) {
                if (a !== b) {
                    var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
                    fail("Expected " + a + " === " + b + ". " + message);
                }
            }
            Debug.assertEqual = assertEqual;
            function assertLessThan(a, b, msg) {
                if (a >= b) {
                    fail("Expected " + a + " < " + b + ". " + (msg || ""));
                }
            }
            Debug.assertLessThan = assertLessThan;
            function assertLessThanOrEqual(a, b) {
                if (a > b) {
                    fail("Expected " + a + " <= " + b);
                }
            }
            Debug.assertLessThanOrEqual = assertLessThanOrEqual;
            function assertGreaterThanOrEqual(a, b) {
                if (a < b) {
                    fail("Expected " + a + " >= " + b);
                }
            }
            Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
            function fail(message, stackCrawlMark) {
                debugger;
                var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
                if (Error.captureStackTrace) {
                    Error.captureStackTrace(e, stackCrawlMark || fail);
                }
                throw e;
            }
            Debug.fail = fail;
            function assertDefined(value, message) {
                if (value === undefined || value === null)
                    return fail(message);
                return value;
            }
            Debug.assertDefined = assertDefined;
            function assertEachDefined(value, message) {
                for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
                    var v = value_1[_i];
                    assertDefined(v, message);
                }
                return value;
            }
            Debug.assertEachDefined = assertEachDefined;
            function assertNever(member, message, stackCrawlMark) {
                return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever);
            }
            Debug.assertNever = assertNever;
            function getFunctionName(func) {
                if (typeof func !== "function") {
                    return "";
                }
                else if (func.hasOwnProperty("name")) {
                    return func.name;
                }
                else {
                    var text = Function.prototype.toString.call(func);
                    var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
                    return match ? match[1] : "";
                }
            }
            Debug.getFunctionName = getFunctionName;
        })(Debug = ts.Debug || (ts.Debug = {}));
        function equateValues(a, b) {
            return a === b;
        }
        ts.equateValues = equateValues;
        /**
         * Compare the equality of two strings using a case-sensitive ordinal comparison.
         *
         * Case-sensitive comparisons compare both strings one code-point at a time using the integer
         * value of each code-point after applying `toUpperCase` to each string. We always map both
         * strings to their upper-case form as some unicode characters do not properly round-trip to
         * lowercase (such as `ẞ` (German sharp capital s)).
         */
        function equateStringsCaseInsensitive(a, b) {
            return a === b
                || a !== undefined
                    && b !== undefined
                    && a.toUpperCase() === b.toUpperCase();
        }
        ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
        /**
         * Compare the equality of two strings using a case-sensitive ordinal comparison.
         *
         * Case-sensitive comparisons compare both strings one code-point at a time using the
         * integer value of each code-point.
         */
        function equateStringsCaseSensitive(a, b) {
            return equateValues(a, b);
        }
        ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
        function compareComparableValues(a, b) {
            return a === b ? 0 /* EqualTo */ :
                a === undefined ? -1 /* LessThan */ :
                    b === undefined ? 1 /* GreaterThan */ :
                        a < b ? -1 /* LessThan */ :
                            1 /* GreaterThan */;
        }
        /**
         * Compare two numeric values for their order relative to each other.
         * To compare strings, use any of the `compareStrings` functions.
         */
        function compareValues(a, b) {
            return compareComparableValues(a, b);
        }
        ts.compareValues = compareValues;
        function min(a, b, compare) {
            return compare(a, b) === -1 /* LessThan */ ? a : b;
        }
        ts.min = min;
        /**
         * Compare two strings using a case-insensitive ordinal comparison.
         *
         * Ordinal comparisons are based on the difference between the unicode code points of both
         * strings. Characters with multiple unicode representations are considered unequal. Ordinal
         * comparisons provide predictable ordering, but place "a" after "B".
         *
         * Case-insensitive comparisons compare both strings one code-point at a time using the integer
         * value of each code-point after applying `toUpperCase` to each string. We always map both
         * strings to their upper-case form as some unicode characters do not properly round-trip to
         * lowercase (such as `áºž` (German sharp capital s)).
         */
        function compareStringsCaseInsensitive(a, b) {
            if (a === b)
                return 0 /* EqualTo */;
            if (a === undefined)
                return -1 /* LessThan */;
            if (b === undefined)
                return 1 /* GreaterThan */;
            a = a.toUpperCase();
            b = b.toUpperCase();
            return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
        }
        ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
        /**
         * Compare two strings using a case-sensitive ordinal comparison.
         *
         * Ordinal comparisons are based on the difference between the unicode code points of both
         * strings. Characters with multiple unicode representations are considered unequal. Ordinal
         * comparisons provide predictable ordering, but place "a" after "B".
         *
         * Case-sensitive comparisons compare both strings one code-point at a time using the integer
         * value of each code-point.
         */
        function compareStringsCaseSensitive(a, b) {
            return compareComparableValues(a, b);
        }
        ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
        function getStringComparer(ignoreCase) {
            return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
        }
        ts.getStringComparer = getStringComparer;
        /**
         * Creates a string comparer for use with string collation in the UI.
         */
        var createUIStringComparer = (function () {
            var defaultComparer;
            var enUSComparer;
            var stringComparerFactory = getStringComparerFactory();
            return createStringComparer;
            function compareWithCallback(a, b, comparer) {
                if (a === b)
                    return 0 /* EqualTo */;
                if (a === undefined)
                    return -1 /* LessThan */;
                if (b === undefined)
                    return 1 /* GreaterThan */;
                var value = comparer(a, b);
                return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
            }
            function createIntlCollatorStringComparer(locale) {
                // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
                // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
                var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
                return function (a, b) { return compareWithCallback(a, b, comparer); };
            }
            function createLocaleCompareStringComparer(locale) {
                // if the locale is not the default locale (`undefined`), use the fallback comparer.
                if (locale !== undefined)
                    return createFallbackStringComparer();
                return function (a, b) { return compareWithCallback(a, b, compareStrings); };
                function compareStrings(a, b) {
                    return a.localeCompare(b);
                }
            }
            function createFallbackStringComparer() {
                // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
                // We first sort case insensitively.  So "Aaa" will come before "baa".
                // Then we sort case sensitively, so "aaa" will come before "Aaa".
                //
                // For case insensitive comparisons we always map both strings to their
                // upper-case form as some unicode characters do not properly round-trip to
                // lowercase (such as `áºž` (German sharp capital s)).
                return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
                function compareDictionaryOrder(a, b) {
                    return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
                }
                function compareStrings(a, b) {
                    return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
                }
            }
            function getStringComparerFactory() {
                // If the host supports Intl, we use it for comparisons using the default locale.
                if (typeof Intl === "object" && typeof Intl.Collator === "function") {
                    return createIntlCollatorStringComparer;
                }
                // If the host does not support Intl, we fall back to localeCompare.
                // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
                if (typeof String.prototype.localeCompare === "function" &&
                    typeof String.prototype.toLocaleUpperCase === "function" &&
                    "a".localeCompare("B") < 0) {
                    return createLocaleCompareStringComparer;
                }
                // Otherwise, fall back to ordinal comparison:
                return createFallbackStringComparer;
            }
            function createStringComparer(locale) {
                // Hold onto common string comparers. This avoids constantly reallocating comparers during
                // tests.
                if (locale === undefined) {
                    return defaultComparer || (defaultComparer = stringComparerFactory(locale));
                }
                else if (locale === "en-US") {
                    return enUSComparer || (enUSComparer = stringComparerFactory(locale));
                }
                else {
                    return stringComparerFactory(locale);
                }
            }
        })();
        var uiComparerCaseSensitive;
        var uiLocale;
        function getUILocale() {
            return uiLocale;
        }
        ts.getUILocale = getUILocale;
        function setUILocale(value) {
            if (uiLocale !== value) {
                uiLocale = value;
                uiComparerCaseSensitive = undefined;
            }
        }
        ts.setUILocale = setUILocale;
        /**
         * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
         *
         * Ordering is not predictable between different host locales, but is best for displaying
         * ordered data for UI presentation. Characters with multiple unicode representations may
         * be considered equal.
         *
         * Case-sensitive comparisons compare strings that differ in base characters, or
         * accents/diacritic marks, or case as unequal.
         */
        function compareStringsCaseSensitiveUI(a, b) {
            var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
            return comparer(a, b);
        }
        ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
        function compareProperties(a, b, key, comparer) {
            return a === b ? 0 /* EqualTo */ :
                a === undefined ? -1 /* LessThan */ :
                    b === undefined ? 1 /* GreaterThan */ :
                        comparer(a[key], b[key]);
        }
        ts.compareProperties = compareProperties;
        /** True is greater than false. */
        function compareBooleans(a, b) {
            return compareValues(a ? 1 : 0, b ? 1 : 0);
        }
        ts.compareBooleans = compareBooleans;
        /**
         * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
         * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
         *
         * If there is a candidate that's the same except for case, return that.
         * If there is a candidate that's within one edit of the name, return that.
         * Otherwise, return the candidate with the smallest Levenshtein distance,
         *    except for candidates:
         *      * With no name
         *      * Whose length differs from the target name by more than 0.34 of the length of the name.
         *      * Whose levenshtein distance is more than 0.4 of the length of the name
         *        (0.4 allows 1 substitution/transposition for every 5 characters,
         *         and 1 insertion/deletion at 3 characters)
         */
        function getSpellingSuggestion(name, candidates, getName) {
            var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
            var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
            var bestCandidate;
            var justCheckExactMatches = false;
            var nameLowerCase = name.toLowerCase();
            for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
                var candidate = candidates_1[_i];
                var candidateName = getName(candidate);
                if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
                    var candidateNameLowerCase = candidateName.toLowerCase();
                    if (candidateNameLowerCase === nameLowerCase) {
                        if (candidateName === name) {
                            continue;
                        }
                        return candidate;
                    }
                    if (justCheckExactMatches) {
                        continue;
                    }
                    if (candidateName.length < 3) {
                        // Don't bother, user would have noticed a 2-character name having an extra character
                        continue;
                    }
                    // Only care about a result better than the best so far.
                    var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
                    if (distance === undefined) {
                        continue;
                    }
                    if (distance < 3) {
                        justCheckExactMatches = true;
                        bestCandidate = candidate;
                    }
                    else {
                        Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
                        bestDistance = distance;
                        bestCandidate = candidate;
                    }
                }
            }
            return bestCandidate;
        }
        ts.getSpellingSuggestion = getSpellingSuggestion;
        function levenshteinWithMax(s1, s2, max) {
            var previous = new Array(s2.length + 1);
            var current = new Array(s2.length + 1);
            /** Represents any value > max. We don't care about the particular value. */
            var big = max + 1;
            for (var i = 0; i <= s2.length; i++) {
                previous[i] = i;
            }
            for (var i = 1; i <= s1.length; i++) {
                var c1 = s1.charCodeAt(i - 1);
                var minJ = i > max ? i - max : 1;
                var maxJ = s2.length > max + i ? max + i : s2.length;
                current[0] = i;
                /** Smallest value of the matrix in the ith column. */
                var colMin = i;
                for (var j = 1; j < minJ; j++) {
                    current[j] = big;
                }
                for (var j = minJ; j <= maxJ; j++) {
                    var dist = c1 === s2.charCodeAt(j - 1)
                        ? previous[j - 1]
                        : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
                    current[j] = dist;
                    colMin = Math.min(colMin, dist);
                }
                for (var j = maxJ + 1; j <= s2.length; j++) {
                    current[j] = big;
                }
                if (colMin > max) {
                    // Give up -- everything in this column is > max and it can't get better in future columns.
                    return undefined;
                }
                var temp = previous;
                previous = current;
                current = temp;
            }
            var res = previous[s2.length];
            return res > max ? undefined : res;
        }
        function endsWith(str, suffix) {
            var expectedPos = str.length - suffix.length;
            return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
        }
        ts.endsWith = endsWith;
        function removeSuffix(str, suffix) {
            return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
        }
        ts.removeSuffix = removeSuffix;
        function tryRemoveSuffix(str, suffix) {
            return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
        }
        ts.tryRemoveSuffix = tryRemoveSuffix;
        function stringContains(str, substring) {
            return str.indexOf(substring) !== -1;
        }
        ts.stringContains = stringContains;
        function fileExtensionIs(path, extension) {
            return path.length > extension.length && endsWith(path, extension);
        }
        ts.fileExtensionIs = fileExtensionIs;
        function fileExtensionIsOneOf(path, extensions) {
            for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
                var extension = extensions_1[_i];
                if (fileExtensionIs(path, extension)) {
                    return true;
                }
            }
            return false;
        }
        ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
        /**
         * Takes a string like "jquery-min.4.2.3" and returns "jquery"
         */
        function removeMinAndVersionNumbers(fileName) {
            // Match a "." or "-" followed by a version number or 'min' at the end of the name
            var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
            // The "min" or version may both be present, in either order, so try applying the above twice.
            return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
        }
        ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
        /** Remove an item from an array, moving everything to its right one space left. */
        function orderedRemoveItem(array, item) {
            for (var i = 0; i < array.length; i++) {
                if (array[i] === item) {
                    orderedRemoveItemAt(array, i);
                    return true;
                }
            }
            return false;
        }
        ts.orderedRemoveItem = orderedRemoveItem;
        /** Remove an item by index from an array, moving everything to its right one space left. */
        function orderedRemoveItemAt(array, index) {
            // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
            for (var i = index; i < array.length - 1; i++) {
                array[i] = array[i + 1];
            }
            array.pop();
        }
        ts.orderedRemoveItemAt = orderedRemoveItemAt;
        function unorderedRemoveItemAt(array, index) {
            // Fill in the "hole" left at `index`.
            array[index] = array[array.length - 1];
            array.pop();
        }
        ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
        /** Remove the *first* occurrence of `item` from the array. */
        function unorderedRemoveItem(array, item) {
            return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
        }
        ts.unorderedRemoveItem = unorderedRemoveItem;
        /** Remove the *first* element satisfying `predicate`. */
        function unorderedRemoveFirstItemWhere(array, predicate) {
            for (var i = 0; i < array.length; i++) {
                if (predicate(array[i])) {
                    unorderedRemoveItemAt(array, i);
                    return true;
                }
            }
            return false;
        }
        function createGetCanonicalFileName(useCaseSensitiveFileNames) {
            return useCaseSensitiveFileNames ? identity : toLowerCase;
        }
        ts.createGetCanonicalFileName = createGetCanonicalFileName;
        function patternText(_a) {
            var prefix = _a.prefix, suffix = _a.suffix;
            return prefix + "*" + suffix;
        }
        ts.patternText = patternText;
        /**
         * Given that candidate matches pattern, returns the text matching the '*'.
         * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
         */
        function matchedText(pattern, candidate) {
            Debug.assert(isPatternMatch(pattern, candidate));
            return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
        }
        ts.matchedText = matchedText;
        /** Return the object corresponding to the best pattern to match `candidate`. */
        function findBestPatternMatch(values, getPattern, candidate) {
            var matchedValue;
            // use length of prefix as betterness criteria
            var longestMatchPrefixLength = -1;
            for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
                var v = values_2[_i];
                var pattern = getPattern(v);
                if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
                    longestMatchPrefixLength = pattern.prefix.length;
                    matchedValue = v;
                }
            }
            return matchedValue;
        }
        ts.findBestPatternMatch = findBestPatternMatch;
        function startsWith(str, prefix) {
            return str.lastIndexOf(prefix, 0) === 0;
        }
        ts.startsWith = startsWith;
        function removePrefix(str, prefix) {
            return startsWith(str, prefix) ? str.substr(prefix.length) : str;
        }
        ts.removePrefix = removePrefix;
        function tryRemovePrefix(str, prefix, getCanonicalFileName) {
            if (getCanonicalFileName === void 0) {
                getCanonicalFileName = identity;
            }
            return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
        }
        ts.tryRemovePrefix = tryRemovePrefix;
        function isPatternMatch(_a, candidate) {
            var prefix = _a.prefix, suffix = _a.suffix;
            return candidate.length >= prefix.length + suffix.length &&
                startsWith(candidate, prefix) &&
                endsWith(candidate, suffix);
        }
        function and(f, g) {
            return function (arg) { return f(arg) && g(arg); };
        }
        ts.and = and;
        function or(f, g) {
            return function (arg) { return f(arg) || g(arg); };
        }
        ts.or = or;
        function assertType(_) { } // tslint:disable-line no-empty
        ts.assertType = assertType;
        function singleElementArray(t) {
            return t === undefined ? undefined : [t];
        }
        ts.singleElementArray = singleElementArray;
        function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
            unchanged = unchanged || noop;
            var newIndex = 0;
            var oldIndex = 0;
            var newLen = newItems.length;
            var oldLen = oldItems.length;
            while (newIndex < newLen && oldIndex < oldLen) {
                var newItem = newItems[newIndex];
                var oldItem = oldItems[oldIndex];
                var compareResult = comparer(newItem, oldItem);
                if (compareResult === -1 /* LessThan */) {
                    inserted(newItem);
                    newIndex++;
                }
                else if (compareResult === 1 /* GreaterThan */) {
                    deleted(oldItem);
                    oldIndex++;
                }
                else {
                    unchanged(oldItem, newItem);
                    newIndex++;
                    oldIndex++;
                }
            }
            while (newIndex < newLen) {
                inserted(newItems[newIndex++]);
            }
            while (oldIndex < oldLen) {
                deleted(oldItems[oldIndex++]);
            }
        }
        ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
        function fill(length, cb) {
            return new Array(length).fill(0).map(function (_, i) { return cb(i); });
        }
        ts.fill = fill;
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        /** Gets a timestamp with (at least) ms resolution */
        ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
    })(ts || (ts = {}));
    /*@internal*/
    /** Performance measurements for the compiler. */
    (function (ts) {
        var performance;
        (function (performance) {
            // NOTE: cannot use ts.noop as core.ts loads after this
            var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
            var enabled = false;
            var profilerStart = 0;
            var counts;
            var marks;
            var measures;
            /**
             * Marks a performance event.
             *
             * @param markName The name of the mark.
             */
            function mark(markName) {
                if (enabled) {
                    marks.set(markName, ts.timestamp());
                    counts.set(markName, (counts.get(markName) || 0) + 1);
                    profilerEvent(markName);
                }
            }
            performance.mark = mark;
            /**
             * Adds a performance measurement with the specified name.
             *
             * @param measureName The name of the performance measurement.
             * @param startMarkName The name of the starting mark. If not supplied, the point at which the
             *      profiler was enabled is used.
             * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
             *      used.
             */
            function measure(measureName, startMarkName, endMarkName) {
                if (enabled) {
                    var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
                    var start = startMarkName && marks.get(startMarkName) || profilerStart;
                    measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
                }
            }
            performance.measure = measure;
            /**
             * Gets the number of times a marker was encountered.
             *
             * @param markName The name of the mark.
             */
            function getCount(markName) {
                return counts && counts.get(markName) || 0;
            }
            performance.getCount = getCount;
            /**
             * Gets the total duration of all measurements with the supplied name.
             *
             * @param measureName The name of the measure whose durations should be accumulated.
             */
            function getDuration(measureName) {
                return measures && measures.get(measureName) || 0;
            }
            performance.getDuration = getDuration;
            /**
             * Iterate over each measure, performing some action
             *
             * @param cb The action to perform for each measure
             */
            function forEachMeasure(cb) {
                measures.forEach(function (measure, key) {
                    cb(key, measure);
                });
            }
            performance.forEachMeasure = forEachMeasure;
            /** Enables (and resets) performance measurements for the compiler. */
            function enable() {
                counts = ts.createMap();
                marks = ts.createMap();
                measures = ts.createMap();
                enabled = true;
                profilerStart = ts.timestamp();
            }
            performance.enable = enable;
            /** Disables performance measurements for the compiler. */
            function disable() {
                enabled = false;
            }
            performance.disable = disable;
        })(performance = ts.performance || (ts.performance = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        // https://semver.org/#spec-item-2
        // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
        // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
        // > version, and Z is the patch version. Each element MUST increase numerically.
        //
        // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
        // value of `0`.
        var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
        // https://semver.org/#spec-item-9
        // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
        // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
        // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
        // > MUST NOT include leading zeroes.
        var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
        // https://semver.org/#spec-item-10
        // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
        // > identifiers immediately following the patch or pre-release version. Identifiers MUST
        // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
        var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
        // https://semver.org/#spec-item-9
        // > Numeric identifiers MUST NOT include leading zeroes.
        var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
        /**
         * Describes a precise semantic version number, https://semver.org
         */
        var Version = /** @class */ (function () {
            function Version(major, minor, patch, prerelease, build) {
                if (minor === void 0) {
                    minor = 0;
                }
                if (patch === void 0) {
                    patch = 0;
                }
                if (prerelease === void 0) {
                    prerelease = "";
                }
                if (build === void 0) {
                    build = "";
                }
                if (typeof major === "string") {
                    var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version");
                    (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
                }
                ts.Debug.assert(major >= 0, "Invalid argument: major");
                ts.Debug.assert(minor >= 0, "Invalid argument: minor");
                ts.Debug.assert(patch >= 0, "Invalid argument: patch");
                ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
                ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
                this.major = major;
                this.minor = minor;
                this.patch = patch;
                this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
                this.build = build ? build.split(".") : ts.emptyArray;
            }
            Version.tryParse = function (text) {
                var result = tryParseComponents(text);
                if (!result)
                    return undefined;
                var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
                return new Version(major, minor, patch, prerelease, build);
            };
            Version.prototype.compareTo = function (other) {
                // https://semver.org/#spec-item-11
                // > Precedence is determined by the first difference when comparing each of these
                // > identifiers from left to right as follows: Major, minor, and patch versions are
                // > always compared numerically.
                //
                // https://semver.org/#spec-item-11
                // > Precedence for two pre-release versions with the same major, minor, and patch version
                // > MUST be determined by comparing each dot separated identifier from left to right until
                // > a difference is found [...]
                //
                // https://semver.org/#spec-item-11
                // > Build metadata does not figure into precedence
                if (this === other)
                    return 0 /* EqualTo */;
                if (other === undefined)
                    return 1 /* GreaterThan */;
                return ts.compareValues(this.major, other.major)
                    || ts.compareValues(this.minor, other.minor)
                    || ts.compareValues(this.patch, other.patch)
                    || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
            };
            Version.prototype.increment = function (field) {
                switch (field) {
                    case "major": return new Version(this.major + 1, 0, 0);
                    case "minor": return new Version(this.major, this.minor + 1, 0);
                    case "patch": return new Version(this.major, this.minor, this.patch + 1);
                    default: return ts.Debug.assertNever(field);
                }
            };
            Version.prototype.toString = function () {
                var result = this.major + "." + this.minor + "." + this.patch;
                if (ts.some(this.prerelease))
                    result += "-" + this.prerelease.join(".");
                if (ts.some(this.build))
                    result += "+" + this.build.join(".");
                return result;
            };
            Version.zero = new Version(0, 0, 0);
            return Version;
        }());
        ts.Version = Version;
        function tryParseComponents(text) {
            var match = versionRegExp.exec(text);
            if (!match)
                return undefined;
            var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d;
            if (prerelease && !prereleaseRegExp.test(prerelease))
                return undefined;
            if (build && !buildRegExp.test(build))
                return undefined;
            return {
                major: parseInt(major, 10),
                minor: parseInt(minor, 10),
                patch: parseInt(patch, 10),
                prerelease: prerelease,
                build: build
            };
        }
        function comparePrerelaseIdentifiers(left, right) {
            // https://semver.org/#spec-item-11
            // > When major, minor, and patch are equal, a pre-release version has lower precedence
            // > than a normal version.
            if (left === right)
                return 0 /* EqualTo */;
            if (left.length === 0)
                return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
            if (right.length === 0)
                return -1 /* LessThan */;
            // https://semver.org/#spec-item-11
            // > Precedence for two pre-release versions with the same major, minor, and patch version
            // > MUST be determined by comparing each dot separated identifier from left to right until
            // > a difference is found [...]
            var length = Math.min(left.length, right.length);
            for (var i = 0; i < length; i++) {
                var leftIdentifier = left[i];
                var rightIdentifier = right[i];
                if (leftIdentifier === rightIdentifier)
                    continue;
                var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
                var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
                if (leftIsNumeric || rightIsNumeric) {
                    // https://semver.org/#spec-item-11
                    // > Numeric identifiers always have lower precedence than non-numeric identifiers.
                    if (leftIsNumeric !== rightIsNumeric)
                        return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
                    // https://semver.org/#spec-item-11
                    // > identifiers consisting of only digits are compared numerically
                    var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
                    if (result)
                        return result;
                }
                else {
                    // https://semver.org/#spec-item-11
                    // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
                    var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
                    if (result)
                        return result;
                }
            }
            // https://semver.org/#spec-item-11
            // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
            // > of the preceding identifiers are equal.
            return ts.compareValues(left.length, right.length);
        }
        /**
         * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
         */
        var VersionRange = /** @class */ (function () {
            function VersionRange(spec) {
                this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
            }
            VersionRange.tryParse = function (text) {
                var sets = parseRange(text);
                if (sets) {
                    var range = new VersionRange("");
                    range._alternatives = sets;
                    return range;
                }
                return undefined;
            };
            VersionRange.prototype.test = function (version) {
                if (typeof version === "string")
                    version = new Version(version);
                return testDisjunction(version, this._alternatives);
            };
            VersionRange.prototype.toString = function () {
                return formatDisjunction(this._alternatives);
            };
            return VersionRange;
        }());
        ts.VersionRange = VersionRange;
        // https://github.com/npm/node-semver#range-grammar
        //
        // range-set    ::= range ( logical-or range ) *
        // range        ::= hyphen | simple ( ' ' simple ) * | ''
        // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
        var logicalOrRegExp = /\s*\|\|\s*/g;
        var whitespaceRegExp = /\s+/g;
        // https://github.com/npm/node-semver#range-grammar
        //
        // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
        // xr           ::= 'x' | 'X' | '*' | nr
        // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
        // qualifier    ::= ( '-' pre )? ( '+' build )?
        // pre          ::= parts
        // build        ::= parts
        // parts        ::= part ( '.' part ) *
        // part         ::= nr | [-0-9A-Za-z]+
        var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
        // https://github.com/npm/node-semver#range-grammar
        //
        // hyphen       ::= partial ' - ' partial
        var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
        // https://github.com/npm/node-semver#range-grammar
        //
        // simple       ::= primitive | partial | tilde | caret
        // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
        // tilde        ::= '~' partial
        // caret        ::= '^' partial
        var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
        function parseRange(text) {
            var alternatives = [];
            for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
                var range = _a[_i];
                if (!range)
                    continue;
                var comparators = [];
                var match = hyphenRegExp.exec(range);
                if (match) {
                    if (!parseHyphen(match[1], match[2], comparators))
                        return undefined;
                }
                else {
                    for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
                        var simple = _c[_b];
                        var match_1 = rangeRegExp.exec(simple);
                        if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
                            return undefined;
                    }
                }
                alternatives.push(comparators);
            }
            return alternatives;
        }
        function parsePartial(text) {
            var match = partialRegExp.exec(text);
            if (!match)
                return undefined;
            var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5];
            var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build);
            return { version: version, major: major, minor: minor, patch: patch };
        }
        function parseHyphen(left, right, comparators) {
            var leftResult = parsePartial(left);
            if (!leftResult)
                return false;
            var rightResult = parsePartial(right);
            if (!rightResult)
                return false;
            if (!isWildcard(leftResult.major)) {
                comparators.push(createComparator(">=", leftResult.version));
            }
            if (!isWildcard(rightResult.major)) {
                comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
                    isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
                        createComparator("<=", rightResult.version));
            }
            return true;
        }
        function parseComparator(operator, text, comparators) {
            var result = parsePartial(text);
            if (!result)
                return false;
            var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
            if (!isWildcard(major)) {
                switch (operator) {
                    case "~":
                        comparators.push(createComparator(">=", version));
                        comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
                            "minor")));
                        break;
                    case "^":
                        comparators.push(createComparator(">=", version));
                        comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
                            version.minor > 0 || isWildcard(patch) ? "minor" :
                                "patch")));
                        break;
                    case "<":
                    case ">=":
                        comparators.push(createComparator(operator, version));
                        break;
                    case "<=":
                    case ">":
                        comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
                            isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
                                createComparator(operator, version));
                        break;
                    case "=":
                    case undefined:
                        if (isWildcard(minor) || isWildcard(patch)) {
                            comparators.push(createComparator(">=", version));
                            comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
                        }
                        else {
                            comparators.push(createComparator("=", version));
                        }
                        break;
                    default:
                        // unrecognized
                        return false;
                }
            }
            else if (operator === "<" || operator === ">") {
                comparators.push(createComparator("<", Version.zero));
            }
            return true;
        }
        function isWildcard(part) {
            return part === "*" || part === "x" || part === "X";
        }
        function createComparator(operator, operand) {
            return { operator: operator, operand: operand };
        }
        function testDisjunction(version, alternatives) {
            // an empty disjunction is treated as "*" (all versions)
            if (alternatives.length === 0)
                return true;
            for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
                var alternative = alternatives_1[_i];
                if (testAlternative(version, alternative))
                    return true;
            }
            return false;
        }
        function testAlternative(version, comparators) {
            for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
                var comparator = comparators_1[_i];
                if (!testComparator(version, comparator.operator, comparator.operand))
                    return false;
            }
            return true;
        }
        function testComparator(version, operator, operand) {
            var cmp = version.compareTo(operand);
            switch (operator) {
                case "<": return cmp < 0;
                case "<=": return cmp <= 0;
                case ">": return cmp > 0;
                case ">=": return cmp >= 0;
                case "=": return cmp === 0;
                default: return ts.Debug.assertNever(operator);
            }
        }
        function formatDisjunction(alternatives) {
            return ts.map(alternatives, formatAlternative).join(" || ") || "*";
        }
        function formatAlternative(comparators) {
            return ts.map(comparators, formatComparator).join(" ");
        }
        function formatComparator(comparator) {
            return "" + comparator.operator + comparator.operand;
        }
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        // token > SyntaxKind.Identifier => token is a keyword
        // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
        var SyntaxKind;
        (function (SyntaxKind) {
            SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
            SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
            SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
            SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
            SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
            SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
            // We detect and preserve #! on the first line
            SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
            // We detect and provide better error recovery when we encounter a git merge marker.  This
            // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
            SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
            // Literals
            SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
            SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral";
            SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText";
            SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces";
            SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral";
            SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral";
            // Pseudo-literals
            SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead";
            SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle";
            SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail";
            // Punctuation
            SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken";
            SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken";
            SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken";
            SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken";
            SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken";
            SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken";
            SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken";
            SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken";
            SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken";
            SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken";
            SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken";
            SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken";
            SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken";
            SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken";
            SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken";
            SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken";
            SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken";
            SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken";
            SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken";
            SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken";
            SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken";
            SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken";
            SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken";
            SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken";
            SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken";
            SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken";
            SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken";
            SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken";
            SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken";
            SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken";
            SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken";
            SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken";
            SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken";
            SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken";
            SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken";
            SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken";
            SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken";
            SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken";
            SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken";
            SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken";
            SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken";
            // Assignments
            SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken";
            SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken";
            SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken";
            SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken";
            SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken";
            SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken";
            SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken";
            SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken";
            SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken";
            SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken";
            SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken";
            SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken";
            SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken";
            // Identifiers
            SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier";
            // Reserved words
            SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword";
            SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword";
            SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword";
            SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword";
            SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword";
            SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword";
            SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword";
            SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword";
            SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword";
            SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword";
            SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword";
            SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword";
            SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword";
            SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword";
            SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword";
            SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword";
            SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword";
            SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword";
            SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword";
            SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword";
            SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword";
            SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword";
            SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword";
            SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword";
            SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword";
            SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword";
            SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword";
            SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword";
            SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword";
            SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword";
            SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword";
            SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword";
            SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword";
            SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword";
            SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword";
            SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword";
            // Strict mode reserved words
            SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword";
            SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword";
            SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword";
            SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword";
            SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword";
            SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword";
            SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword";
            SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword";
            SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword";
            // Contextual keywords
            SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword";
            SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword";
            SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword";
            SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword";
            SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword";
            SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword";
            SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword";
            SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword";
            SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword";
            SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword";
            SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword";
            SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword";
            SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword";
            SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword";
            SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword";
            SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword";
            SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword";
            SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword";
            SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword";
            SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword";
            SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword";
            SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword";
            SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword";
            SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword";
            SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword";
            SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword";
            SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword";
            SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword";
            SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword";
            // Parse tree nodes
            // Names
            SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName";
            SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName";
            // Signature elements
            SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter";
            SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter";
            SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator";
            // TypeMember
            SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature";
            SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration";
            SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature";
            SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration";
            SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor";
            SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor";
            SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor";
            SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature";
            SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature";
            SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature";
            // Type
            SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate";
            SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference";
            SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType";
            SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType";
            SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery";
            SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral";
            SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType";
            SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType";
            SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType";
            SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType";
            SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType";
            SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType";
            SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType";
            SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType";
            SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType";
            SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType";
            SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator";
            SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType";
            SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType";
            SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType";
            SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType";
            // Binding patterns
            SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern";
            SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern";
            SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement";
            // Expression
            SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression";
            SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression";
            SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression";
            SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression";
            SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression";
            SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression";
            SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression";
            SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression";
            SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression";
            SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression";
            SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction";
            SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression";
            SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression";
            SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression";
            SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression";
            SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression";
            SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression";
            SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression";
            SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression";
            SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression";
            SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression";
            SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement";
            SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression";
            SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression";
            SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments";
            SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression";
            SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression";
            SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty";
            SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression";
            // Misc
            SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan";
            SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement";
            // Element
            SyntaxKind[SyntaxKind["Block"] = 216] = "Block";
            SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement";
            SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement";
            SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement";
            SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement";
            SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement";
            SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement";
            SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement";
            SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement";
            SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement";
            SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement";
            SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement";
            SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement";
            SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement";
            SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement";
            SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement";
            SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement";
            SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement";
            SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement";
            SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration";
            SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList";
            SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration";
            SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration";
            SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration";
            SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration";
            SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration";
            SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration";
            SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock";
            SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock";
            SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration";
            SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration";
            SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration";
            SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause";
            SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport";
            SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports";
            SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier";
            SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment";
            SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration";
            SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports";
            SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier";
            SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration";
            // Module references
            SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference";
            // JSX
            SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement";
            SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement";
            SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement";
            SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement";
            SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment";
            SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment";
            SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment";
            SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute";
            SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes";
            SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute";
            SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression";
            // Clauses
            SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause";
            SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause";
            SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause";
            SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause";
            // Property assignments
            SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment";
            SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment";
            SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment";
            // Enum
            SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember";
            // Top-level nodes
            SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile";
            SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle";
            SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource";
            SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles";
            // JSDoc nodes
            SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression";
            // The * type
            SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType";
            // The ? type
            SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType";
            SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType";
            SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType";
            SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType";
            SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType";
            SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType";
            SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment";
            SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral";
            SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature";
            SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag";
            SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag";
            SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag";
            SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag";
            SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag";
            SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag";
            SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag";
            SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag";
            SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag";
            SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag";
            SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag";
            SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag";
            // Synthesized list
            SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList";
            // Transformation nodes
            SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement";
            SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression";
            SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression";
            SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker";
            SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker";
            // Enum value count
            SyntaxKind[SyntaxKind["Count"] = 310] = "Count";
            // Markers
            SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
            SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
            SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment";
            SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment";
            SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord";
            SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord";
            SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword";
            SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword";
            SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord";
            SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord";
            SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode";
            SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode";
            SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation";
            SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation";
            SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
            SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken";
            SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
            SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
            SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
            SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken";
            SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken";
            SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken";
            SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator";
            SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator";
            SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode";
            SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode";
            SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode";
            SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode";
            SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode";
            /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
            /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword";
        })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
        var NodeFlags;
        (function (NodeFlags) {
            NodeFlags[NodeFlags["None"] = 0] = "None";
            NodeFlags[NodeFlags["Let"] = 1] = "Let";
            NodeFlags[NodeFlags["Const"] = 2] = "Const";
            NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
            NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
            NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
            NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext";
            NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis";
            NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn";
            NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn";
            NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation";
            NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions";
            NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext";
            NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext";
            NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext";
            NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext";
            NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError";
            NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile";
            NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError";
            NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData";
            // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
            // walking the tree if the flags are not set. However, these flags are just a approximation
            // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
            // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
            // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
            // However, the removal operation should not occur often and in the case of the
            // removal, it is likely that users will add the import anyway.
            // The advantage of this approach is its simplicity. For the case of batch compilation,
            // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
            /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport";
            /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta";
            NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
            /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
            /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
            NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile";
            NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
            NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
            NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
            // Parsing context flags
            NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags";
            // Exclude these flags when parsing a Type
            NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags";
            // Represents all flags that are potentially set once and
            // never cleared on SourceFiles which get re-used in between incremental parses.
            // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
            /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags";
        })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
        var ModifierFlags;
        (function (ModifierFlags) {
            ModifierFlags[ModifierFlags["None"] = 0] = "None";
            ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
            ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
            ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
            ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
            ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
            ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
            ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
            ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
            ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
            ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
            ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
            ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
            ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
            // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
            ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
            ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
            ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
            ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
            ModifierFlags[ModifierFlags["All"] = 3071] = "All";
        })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
        var JsxFlags;
        (function (JsxFlags) {
            JsxFlags[JsxFlags["None"] = 0] = "None";
            /** An element from a named property of the JSX.IntrinsicElements interface */
            JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
            /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
            JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
            JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
        })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
        /* @internal */
        var RelationComparisonResult;
        (function (RelationComparisonResult) {
            RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
            RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
            RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported";
        })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
        /*@internal*/
        var GeneratedIdentifierFlags;
        (function (GeneratedIdentifierFlags) {
            // Kinds
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
            // Flags
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
            GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
        })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
        /* @internal */
        var TokenFlags;
        (function (TokenFlags) {
            TokenFlags[TokenFlags["None"] = 0] = "None";
            TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
            TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
            TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
            TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
            TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
            TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
            TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
            TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
            TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
            TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
            TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
            TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
        })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
        var FlowFlags;
        (function (FlowFlags) {
            FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
            FlowFlags[FlowFlags["Start"] = 2] = "Start";
            FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
            FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
            FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
            FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
            FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
            FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
            FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
            FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced";
            FlowFlags[FlowFlags["Shared"] = 1024] = "Shared";
            FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally";
            FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally";
            FlowFlags[FlowFlags["Label"] = 12] = "Label";
            FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
        })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
        var OperationCanceledException = /** @class */ (function () {
            function OperationCanceledException() {
            }
            return OperationCanceledException;
        }());
        ts.OperationCanceledException = OperationCanceledException;
        /* @internal */
        var StructureIsReused;
        (function (StructureIsReused) {
            StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
            StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
            StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
        })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
        /** Return code used by getEmitOutput function to indicate status of the function */
        var ExitStatus;
        (function (ExitStatus) {
            // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
            // when -version or -help was provided, or this was a normal compilation, no diagnostics
            // were produced, and all outputs were generated successfully.
            ExitStatus[ExitStatus["Success"] = 0] = "Success";
            // Diagnostics were produced and because of them no code was generated.
            ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
            // Diagnostics were produced and outputs were generated in spite of them.
            ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
        })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
        /* @internal */
        var UnionReduction;
        (function (UnionReduction) {
            UnionReduction[UnionReduction["None"] = 0] = "None";
            UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
            UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
        })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
        // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
        var NodeBuilderFlags;
        (function (NodeBuilderFlags) {
            NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
            // Options
            NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
            NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
            NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
            NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
            NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
            NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
            NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
            NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
            NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
            NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
            NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
            NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
            NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
            NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
            NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
            // Error handling
            NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
            NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
            NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
            NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
            NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
            NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
            NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
            NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
            // State
            NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
            NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
            NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
            NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
        })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
        // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
        var TypeFormatFlags;
        (function (TypeFormatFlags) {
            TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
            TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
            TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
            // hole because there's a hole in node builder flags
            TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
            // hole because there's a hole in node builder flags
            TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
            TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
            // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
            TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
            // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
            TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
            TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
            TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
            TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
            TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
            // even though `T` can't be accessed in the current scope.
            // Error Handling
            TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
            // TypeFormatFlags exclusive
            TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
            TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
            // State
            TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
            TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
            TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
            TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
            /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
            TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask";
        })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
        var SymbolFormatFlags;
        (function (SymbolFormatFlags) {
            SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
            // Write symbols's type argument if it is instantiated symbol
            // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
            //     var a: C<number>;
            //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
            SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
            // Use only external alias information to get the symbol name in the given context
            // eg.  module m { export class c { } } import x = m.c;
            // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
            SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
            // Build symbol name using any nodes needed, instead of just components of an entity name
            SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
            // Prefer aliases which are not directly visible
            SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
        })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
        /* @internal */
        var SymbolAccessibility;
        (function (SymbolAccessibility) {
            SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
            SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
            SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
        })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
        /* @internal */
        var SyntheticSymbolKind;
        (function (SyntheticSymbolKind) {
            SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
            SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
        })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
        var TypePredicateKind;
        (function (TypePredicateKind) {
            TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
            TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
        })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
        /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
        /* @internal */
        var TypeReferenceSerializationKind;
        (function (TypeReferenceSerializationKind) {
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
            // should be emitted using a safe fallback.
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
            // function that can be reached at runtime (e.g. a `class`
            // declaration or a `var` declaration for the static side
            // of a type, such as the global `Promise` type in lib.d.ts).
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType";
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType";
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType";
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType";
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise";
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature";
            // with call signatures.
            TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType";
        })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
        var SymbolFlags;
        (function (SymbolFlags) {
            SymbolFlags[SymbolFlags["None"] = 0] = "None";
            SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
            SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
            SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
            SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
            SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
            SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
            SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
            SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
            SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
            SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
            SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
            SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
            SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
            SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
            SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
            SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
            SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
            SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
            SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
            SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
            SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
            SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
            SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
            SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
            SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
            SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
            SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
            SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
            /* @internal */
            SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
            SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
            SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
            SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value";
            SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type";
            SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
            SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
            SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
            // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
            // same name, or any other value that is not a variable, e.g. ValueModule or Class
            SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes";
            // Block-scoped declarations are not allowed to be re-declared
            // they can not merge with anything in the value space
            SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes";
            SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes";
            SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
            SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes";
            SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes";
            SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes";
            SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes";
            SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes";
            SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes";
            SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
            SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
            SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes";
            SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes";
            SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes";
            SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes";
            SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes";
            SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
            SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
            SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
            SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
            SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
            SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
            /* @internal */
            // The set of things we consider semantically classifiable.  Used to speed up the LS during
            // classification.
            SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
            /* @internal */
            SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer";
        })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
        /* @internal */
        var EnumKind;
        (function (EnumKind) {
            EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
            EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
        })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
        /* @internal */
        var CheckFlags;
        (function (CheckFlags) {
            CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
            CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
            CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
            CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
            CheckFlags[CheckFlags["Partial"] = 16] = "Partial";
            CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType";
            CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic";
            CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected";
            CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate";
            CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic";
            CheckFlags[CheckFlags["Late"] = 1024] = "Late";
            CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped";
            CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter";
            CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter";
            CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
        })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
        var InternalSymbolName;
        (function (InternalSymbolName) {
            InternalSymbolName["Call"] = "__call";
            InternalSymbolName["Constructor"] = "__constructor";
            InternalSymbolName["New"] = "__new";
            InternalSymbolName["Index"] = "__index";
            InternalSymbolName["ExportStar"] = "__export";
            InternalSymbolName["Global"] = "__global";
            InternalSymbolName["Missing"] = "__missing";
            InternalSymbolName["Type"] = "__type";
            InternalSymbolName["Object"] = "__object";
            InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
            InternalSymbolName["Class"] = "__class";
            InternalSymbolName["Function"] = "__function";
            InternalSymbolName["Computed"] = "__computed";
            InternalSymbolName["Resolving"] = "__resolving__";
            InternalSymbolName["ExportEquals"] = "export=";
            InternalSymbolName["Default"] = "default";
            InternalSymbolName["This"] = "this";
        })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
        /* @internal */
        var NodeCheckFlags;
        (function (NodeCheckFlags) {
            NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
            NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
            NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
            NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
            NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
            NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
            NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
            NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
            NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
            NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
            NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
            NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
            NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
            NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding";
            NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop";
            NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding";
            NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding";
            NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter";
            NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked";
            NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference";
            NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass";
        })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
        var TypeFlags;
        (function (TypeFlags) {
            TypeFlags[TypeFlags["Any"] = 1] = "Any";
            TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
            TypeFlags[TypeFlags["String"] = 4] = "String";
            TypeFlags[TypeFlags["Number"] = 8] = "Number";
            TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
            TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
            TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral";
            TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral";
            TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral";
            TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral";
            TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol";
            TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol";
            TypeFlags[TypeFlags["Void"] = 4096] = "Void";
            TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined";
            TypeFlags[TypeFlags["Null"] = 16384] = "Null";
            TypeFlags[TypeFlags["Never"] = 32768] = "Never";
            TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter";
            TypeFlags[TypeFlags["Object"] = 131072] = "Object";
            TypeFlags[TypeFlags["Union"] = 262144] = "Union";
            TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection";
            TypeFlags[TypeFlags["Index"] = 1048576] = "Index";
            TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess";
            TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional";
            TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution";
            TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive";
            /* @internal */
            TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral";
            /* @internal */
            TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes";
            /* @internal */
            TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
            /* @internal */
            TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
            /* @internal */
            TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
            /* @internal */
            TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
            /* @internal */
            TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable";
            TypeFlags[TypeFlags["Literal"] = 448] = "Literal";
            TypeFlags[TypeFlags["Unit"] = 27072] = "Unit";
            TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral";
            /* @internal */
            TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique";
            /* @internal */
            TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy";
            TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy";
            /* @internal */
            TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic";
            /* @internal */
            TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive";
            TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike";
            TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike";
            TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike";
            TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike";
            TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike";
            TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike";
            /* @internal */
            TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains";
            TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection";
            TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType";
            TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable";
            TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive";
            TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive";
            TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable";
            TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable";
            // 'Narrowable' types are types where narrowing actually narrows.
            // This *should* be every type other than null, undefined, void, and never
            TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable";
            TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit";
            /* @internal */
            TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion";
            /* @internal */
            TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
            /* @internal */
            TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
            // The following flags are used for different purposes during union and intersection type construction
            /* @internal */
            TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
            /* @internal */
            TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
            /* @internal */
            TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
            /* @internal */
            TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
            // The following flag is used for different purposes by maybeTypeOfKind
            /* @internal */
            TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
        })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
        var ObjectFlags;
        (function (ObjectFlags) {
            ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
            ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
            ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
            ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
            ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
            ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
            ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
            ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
            ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
            ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
            ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
            ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
            ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
            ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
            ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
            ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
        })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
        /* @internal */
        var Variance;
        (function (Variance) {
            Variance[Variance["Invariant"] = 0] = "Invariant";
            Variance[Variance["Covariant"] = 1] = "Covariant";
            Variance[Variance["Contravariant"] = 2] = "Contravariant";
            Variance[Variance["Bivariant"] = 3] = "Bivariant";
            Variance[Variance["Independent"] = 4] = "Independent";
        })(Variance = ts.Variance || (ts.Variance = {}));
        var SignatureKind;
        (function (SignatureKind) {
            SignatureKind[SignatureKind["Call"] = 0] = "Call";
            SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
        })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
        var IndexKind;
        (function (IndexKind) {
            IndexKind[IndexKind["String"] = 0] = "String";
            IndexKind[IndexKind["Number"] = 1] = "Number";
        })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
        var InferencePriority;
        (function (InferencePriority) {
            InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
            InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
            InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
            InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
            InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof";
            InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints";
            InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict";
            InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination";
        })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
        /* @internal */
        var InferenceFlags;
        (function (InferenceFlags) {
            InferenceFlags[InferenceFlags["None"] = 0] = "None";
            InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
            InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
        })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
        /**
         * Ternary values are defined such that
         * x & y is False if either x or y is False.
         * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
         * x & y is True if both x and y are True.
         * x | y is False if both x and y are False.
         * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
         * x | y is True if either x or y is True.
         */
        /* @internal */
        var Ternary;
        (function (Ternary) {
            Ternary[Ternary["False"] = 0] = "False";
            Ternary[Ternary["Maybe"] = 1] = "Maybe";
            Ternary[Ternary["True"] = -1] = "True";
        })(Ternary = ts.Ternary || (ts.Ternary = {}));
        /* @internal */
        var AssignmentDeclarationKind;
        (function (AssignmentDeclarationKind) {
            AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
            /// exports.name = expr
            AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
            /// module.exports = expr
            AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
            /// className.prototype.name = expr
            AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
            /// this.name = expr
            AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
            // F.name = expr
            AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
            // F.prototype = { ... }
            AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
        })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
        var DiagnosticCategory;
        (function (DiagnosticCategory) {
            DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
            DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
            DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
            DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
        })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
        /* @internal */
        function diagnosticCategoryName(d, lowerCase) {
            if (lowerCase === void 0) {
                lowerCase = true;
            }
            var name = DiagnosticCategory[d.category];
            return lowerCase ? name.toLowerCase() : name;
        }
        ts.diagnosticCategoryName = diagnosticCategoryName;
        var ModuleResolutionKind;
        (function (ModuleResolutionKind) {
            ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
            ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
        })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
        var ModuleKind;
        (function (ModuleKind) {
            ModuleKind[ModuleKind["None"] = 0] = "None";
            ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
            ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
            ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
            ModuleKind[ModuleKind["System"] = 4] = "System";
            ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
            ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext";
        })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
        var JsxEmit;
        (function (JsxEmit) {
            JsxEmit[JsxEmit["None"] = 0] = "None";
            JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
            JsxEmit[JsxEmit["React"] = 2] = "React";
            JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
        })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
        var NewLineKind;
        (function (NewLineKind) {
            NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
            NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
        })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
        var ScriptKind;
        (function (ScriptKind) {
            ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
            ScriptKind[ScriptKind["JS"] = 1] = "JS";
            ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
            ScriptKind[ScriptKind["TS"] = 3] = "TS";
            ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
            ScriptKind[ScriptKind["External"] = 5] = "External";
            ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
            /**
             * Used on extensions that doesn't define the ScriptKind but the content defines it.
             * Deferred extensions are going to be included in all project contexts.
             */
            ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
        })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
        var ScriptTarget;
        (function (ScriptTarget) {
            ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
            ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
            ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
            ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
            ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
            ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
            ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
            ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
            ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
        })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
        var LanguageVariant;
        (function (LanguageVariant) {
            LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
            LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
        })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
        var WatchDirectoryFlags;
        (function (WatchDirectoryFlags) {
            WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
            WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
        })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
        /* @internal */
        var CharacterCodes;
        (function (CharacterCodes) {
            CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
            CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
            CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
            CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
            CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
            CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
            CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
            // Unicode 3.0 space characters
            CharacterCodes[CharacterCodes["space"] = 32] = "space";
            CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
            CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
            CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
            CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
            CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
            CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
            CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
            CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
            CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
            CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
            CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
            CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
            CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
            CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
            CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
            CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
            CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
            CharacterCodes[CharacterCodes["_"] = 95] = "_";
            CharacterCodes[CharacterCodes["$"] = 36] = "$";
            CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
            CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
            CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
            CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
            CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
            CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
            CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
            CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
            CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
            CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
            CharacterCodes[CharacterCodes["a"] = 97] = "a";
            CharacterCodes[CharacterCodes["b"] = 98] = "b";
            CharacterCodes[CharacterCodes["c"] = 99] = "c";
            CharacterCodes[CharacterCodes["d"] = 100] = "d";
            CharacterCodes[CharacterCodes["e"] = 101] = "e";
            CharacterCodes[CharacterCodes["f"] = 102] = "f";
            CharacterCodes[CharacterCodes["g"] = 103] = "g";
            CharacterCodes[CharacterCodes["h"] = 104] = "h";
            CharacterCodes[CharacterCodes["i"] = 105] = "i";
            CharacterCodes[CharacterCodes["j"] = 106] = "j";
            CharacterCodes[CharacterCodes["k"] = 107] = "k";
            CharacterCodes[CharacterCodes["l"] = 108] = "l";
            CharacterCodes[CharacterCodes["m"] = 109] = "m";
            CharacterCodes[CharacterCodes["n"] = 110] = "n";
            CharacterCodes[CharacterCodes["o"] = 111] = "o";
            CharacterCodes[CharacterCodes["p"] = 112] = "p";
            CharacterCodes[CharacterCodes["q"] = 113] = "q";
            CharacterCodes[CharacterCodes["r"] = 114] = "r";
            CharacterCodes[CharacterCodes["s"] = 115] = "s";
            CharacterCodes[CharacterCodes["t"] = 116] = "t";
            CharacterCodes[CharacterCodes["u"] = 117] = "u";
            CharacterCodes[CharacterCodes["v"] = 118] = "v";
            CharacterCodes[CharacterCodes["w"] = 119] = "w";
            CharacterCodes[CharacterCodes["x"] = 120] = "x";
            CharacterCodes[CharacterCodes["y"] = 121] = "y";
            CharacterCodes[CharacterCodes["z"] = 122] = "z";
            CharacterCodes[CharacterCodes["A"] = 65] = "A";
            CharacterCodes[CharacterCodes["B"] = 66] = "B";
            CharacterCodes[CharacterCodes["C"] = 67] = "C";
            CharacterCodes[CharacterCodes["D"] = 68] = "D";
            CharacterCodes[CharacterCodes["E"] = 69] = "E";
            CharacterCodes[CharacterCodes["F"] = 70] = "F";
            CharacterCodes[CharacterCodes["G"] = 71] = "G";
            CharacterCodes[CharacterCodes["H"] = 72] = "H";
            CharacterCodes[CharacterCodes["I"] = 73] = "I";
            CharacterCodes[CharacterCodes["J"] = 74] = "J";
            CharacterCodes[CharacterCodes["K"] = 75] = "K";
            CharacterCodes[CharacterCodes["L"] = 76] = "L";
            CharacterCodes[CharacterCodes["M"] = 77] = "M";
            CharacterCodes[CharacterCodes["N"] = 78] = "N";
            CharacterCodes[CharacterCodes["O"] = 79] = "O";
            CharacterCodes[CharacterCodes["P"] = 80] = "P";
            CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
            CharacterCodes[CharacterCodes["R"] = 82] = "R";
            CharacterCodes[CharacterCodes["S"] = 83] = "S";
            CharacterCodes[CharacterCodes["T"] = 84] = "T";
            CharacterCodes[CharacterCodes["U"] = 85] = "U";
            CharacterCodes[CharacterCodes["V"] = 86] = "V";
            CharacterCodes[CharacterCodes["W"] = 87] = "W";
            CharacterCodes[CharacterCodes["X"] = 88] = "X";
            CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
            CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
            CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
            CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
            CharacterCodes[CharacterCodes["at"] = 64] = "at";
            CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
            CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
            CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
            CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
            CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
            CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
            CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
            CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
            CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
            CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
            CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
            CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
            CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
            CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
            CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
            CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
            CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
            CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
            CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
            CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
            CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
            CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
            CharacterCodes[CharacterCodes["question"] = 63] = "question";
            CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
            CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
            CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
            CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
            CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
            CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
            CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
            CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
            CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
        })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
        var Extension;
        (function (Extension) {
            Extension["Ts"] = ".ts";
            Extension["Tsx"] = ".tsx";
            Extension["Dts"] = ".d.ts";
            Extension["Js"] = ".js";
            Extension["Jsx"] = ".jsx";
            Extension["Json"] = ".json";
        })(Extension = ts.Extension || (ts.Extension = {}));
        /* @internal */
        var TransformFlags;
        (function (TransformFlags) {
            TransformFlags[TransformFlags["None"] = 0] = "None";
            // Facts
            // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
            TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
            TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
            TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
            TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
            TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
            TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
            TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
            TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
            TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
            TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
            TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
            TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
            // Markers
            // - Flags used to indicate that a subtree contains a specific transformation.
            TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators";
            TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer";
            TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis";
            TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis";
            TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName";
            TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments";
            TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments";
            TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread";
            TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread";
            TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest";
            TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest";
            TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName";
            TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding";
            TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern";
            TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield";
            TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion";
            TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport";
            TransformFlags[TransformFlags["Super"] = 134217728] = "Super";
            TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper";
            // Please leave this as 1 << 29.
            // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
            // It is a good reminder of how much room we have left
            TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
            // Assertions
            // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
            TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
            TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
            TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
            TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
            TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
            TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
            TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
            TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
            // Scope Exclusions
            // - Bitmasks that exclude flags from propagating out of a specific context
            //   into the subtree flags of their container.
            TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
            TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes";
            TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes";
            TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes";
            TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes";
            TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes";
            TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes";
            TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes";
            TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes";
            TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
            TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes";
            TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes";
            TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes";
            TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes";
            TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes";
            TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes";
            // Masks
            // - Additional bitmasks
            TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask";
            TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask";
        })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
        var EmitFlags;
        (function (EmitFlags) {
            EmitFlags[EmitFlags["None"] = 0] = "None";
            EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
            EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
            EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
            EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
            EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
            EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
            EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
            EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
            EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
            EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
            EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
            EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
            EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
            EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
            EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
            EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
            EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
            EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
            EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
            EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
            EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
            EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
            EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
            EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
            EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
            EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
            EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
            EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
            /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
            /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
        })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
        /**
         * Used by the checker, this enum keeps track of external emit helpers that should be type
         * checked.
         */
        /* @internal */
        var ExternalEmitHelpers;
        (function (ExternalEmitHelpers) {
            ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
            ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
            ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
            ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
            ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
            ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
            ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
            ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
            ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
            ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
            ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
            ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
            ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
            ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
            ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
            ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
            ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject";
            ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
            ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper";
            // Helpers included by ES2015 for..of
            ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
            // Helpers included by ES2017 for..await..of
            ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
            // Helpers included by ES2017 async generators
            ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
            // Helpers included by yield* in ES2017 async generators
            ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
            // Helpers included by ES2015 spread
            ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
        })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
        var EmitHint;
        (function (EmitHint) {
            EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
            EmitHint[EmitHint["Expression"] = 1] = "Expression";
            EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
            EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
            EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
        })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
        var ListFormat;
        (function (ListFormat) {
            ListFormat[ListFormat["None"] = 0] = "None";
            // Line separators
            ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
            ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
            ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
            ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
            // Delimiters
            ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
            ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
            ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
            ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
            ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask";
            ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma";
            // Whitespace
            ListFormat[ListFormat["Indented"] = 64] = "Indented";
            ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces";
            ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings";
            // Brackets/Braces
            ListFormat[ListFormat["Braces"] = 512] = "Braces";
            ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis";
            ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets";
            ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets";
            ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask";
            ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined";
            ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty";
            ListFormat[ListFormat["Optional"] = 24576] = "Optional";
            // Other
            ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine";
            ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine";
            ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments";
            ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty";
            ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement";
            // Precomputed Formats
            ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers";
            ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses";
            ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers";
            ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers";
            ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements";
            ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents";
            ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents";
            ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements";
            ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements";
            ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties";
            ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements";
            ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements";
            ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments";
            ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments";
            ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans";
            ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements";
            ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements";
            ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList";
            ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements";
            ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
            ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
            ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers";
            ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers";
            ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers";
            ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses";
            ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements";
            ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren";
            ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes";
            ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements";
            ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes";
            ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements";
            ListFormat[ListFormat["Decorators"] = 24577] = "Decorators";
            ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments";
            ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters";
            ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
            ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
        })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
        /* @internal */
        var PragmaKindFlags;
        (function (PragmaKindFlags) {
            PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
            /**
             * Triple slash comment of the form
             * /// <pragma-name argname="value" />
             */
            PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
            /**
             * Single line comment of the form
             * // @pragma-name argval1 argval2
             * or
             * /// @pragma-name argval1 argval2
             */
            PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
            /**
             * Multiline non-jsdoc pragma of the form
             * /* @pragma-name argval1 argval2 * /
             */
            PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
            PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
            PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
        })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
        /**
         * This function only exists to cause exact types to be inferred for all the literals within `commentPragmas`
         */
        /* @internal */
        function _contextuallyTypePragmas(args) {
            return args;
        }
        // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
        //  fancy effectively defining it twice, once in value-space and once in type-space
        /* @internal */
        ts.commentPragmas = _contextuallyTypePragmas({
            "reference": {
                args: [
                    { name: "types", optional: true, captureSpan: true },
                    { name: "lib", optional: true, captureSpan: true },
                    { name: "path", optional: true, captureSpan: true },
                    { name: "no-default-lib", optional: true }
                ],
                kind: 1 /* TripleSlashXML */
            },
            "amd-dependency": {
                args: [{ name: "path" }, { name: "name", optional: true }],
                kind: 1 /* TripleSlashXML */
            },
            "amd-module": {
                args: [{ name: "name" }],
                kind: 1 /* TripleSlashXML */
            },
            "ts-check": {
                kind: 2 /* SingleLine */
            },
            "ts-nocheck": {
                kind: 2 /* SingleLine */
            },
            "jsx": {
                args: [{ name: "factory" }],
                kind: 4 /* MultiLine */
            },
        });
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        /**
         * Set a high stack trace limit to provide more information in case of an error.
         * Called for command-line and server use cases.
         * Not called if TypeScript is used as a library.
         */
        /* @internal */
        function setStackTraceLimit() {
            if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
                Error.stackTraceLimit = 100;
            }
        }
        ts.setStackTraceLimit = setStackTraceLimit;
        var FileWatcherEventKind;
        (function (FileWatcherEventKind) {
            FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
            FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
            FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
        })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
        /* @internal */
        var PollingInterval;
        (function (PollingInterval) {
            PollingInterval[PollingInterval["High"] = 2000] = "High";
            PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
            PollingInterval[PollingInterval["Low"] = 250] = "Low";
        })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
        function getPriorityValues(highPriorityValue) {
            var mediumPriorityValue = highPriorityValue * 2;
            var lowPriorityValue = mediumPriorityValue * 4;
            return [highPriorityValue, mediumPriorityValue, lowPriorityValue];
        }
        function pollingInterval(watchPriority) {
            return pollingIntervalsForPriority[watchPriority];
        }
        var pollingIntervalsForPriority = getPriorityValues(250);
        /* @internal */
        function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) {
            return host.watchFile(fileName, callback, pollingInterval(watchPriority));
        }
        ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval;
        /* @internal */
        ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
        function createPollingIntervalBasedLevels(levels) {
            var _a;
            return _a = {},
                _a[PollingInterval.Low] = levels.Low,
                _a[PollingInterval.Medium] = levels.Medium,
                _a[PollingInterval.High] = levels.High,
                _a;
        }
        var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
        var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
        /* @internal */
        ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
        /* @internal */
        function setCustomPollingValues(system) {
            if (!system.getEnvironmentVariable) {
                return;
            }
            var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
            pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
            ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
            function getLevel(envVar, level) {
                return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
            }
            function getCustomLevels(baseVariable) {
                var customLevels;
                setCustomLevel("Low");
                setCustomLevel("Medium");
                setCustomLevel("High");
                return customLevels;
                function setCustomLevel(level) {
                    var customLevel = getLevel(baseVariable, level);
                    if (customLevel) {
                        (customLevels || (customLevels = {}))[level] = Number(customLevel);
                    }
                }
            }
            function setCustomLevels(baseVariable, levels) {
                var customLevels = getCustomLevels(baseVariable);
                if (customLevels) {
                    setLevel("Low");
                    setLevel("Medium");
                    setLevel("High");
                    return true;
                }
                return false;
                function setLevel(level) {
                    levels[level] = customLevels[level] || levels[level];
                }
            }
            function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
                var customLevels = getCustomLevels(baseVariable);
                return (pollingIntervalChanged || customLevels) &&
                    createPollingIntervalBasedLevels(customLevels ? __assign({}, defaultLevels, customLevels) : defaultLevels);
            }
        }
        ts.setCustomPollingValues = setCustomPollingValues;
        /* @internal */
        function createDynamicPriorityPollingWatchFile(host) {
            var watchedFiles = [];
            var changedFilesInLastPoll = [];
            var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
            var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
            var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
            return watchFile;
            function watchFile(fileName, callback, defaultPollingInterval) {
                var file = {
                    fileName: fileName,
                    callback: callback,
                    unchangedPolls: 0,
                    mtime: getModifiedTime(fileName)
                };
                watchedFiles.push(file);
                addToPollingIntervalQueue(file, defaultPollingInterval);
                return {
                    close: function () {
                        file.isClosed = true;
                        // Remove from watchedFiles
                        ts.unorderedRemoveItem(watchedFiles, file);
                        // Do not update polling interval queue since that will happen as part of polling
                    }
                };
            }
            function createPollingIntervalQueue(pollingInterval) {
                var queue = [];
                queue.pollingInterval = pollingInterval;
                queue.pollIndex = 0;
                queue.pollScheduled = false;
                return queue;
            }
            function pollPollingIntervalQueue(queue) {
                queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
                // Set the next polling index and timeout
                if (queue.length) {
                    scheduleNextPoll(queue.pollingInterval);
                }
                else {
                    ts.Debug.assert(queue.pollIndex === 0);
                    queue.pollScheduled = false;
                }
            }
            function pollLowPollingIntervalQueue(queue) {
                // Always poll complete list of changedFilesInLastPoll
                pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
                // Finally do the actual polling of the queue
                pollPollingIntervalQueue(queue);
                // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
                // as pollPollingIntervalQueue wont schedule for next poll
                if (!queue.pollScheduled && changedFilesInLastPoll.length) {
                    scheduleNextPoll(PollingInterval.Low);
                }
            }
            function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
                // Max visit would be all elements of the queue
                var needsVisit = queue.length;
                var definedValueCopyToIndex = pollIndex;
                for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
                    var watchedFile = queue[pollIndex];
                    if (!watchedFile) {
                        continue;
                    }
                    else if (watchedFile.isClosed) {
                        queue[pollIndex] = undefined;
                        continue;
                    }
                    polled++;
                    var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
                    if (watchedFile.isClosed) {
                        // Closed watcher as part of callback
                        queue[pollIndex] = undefined;
                    }
                    else if (fileChanged) {
                        watchedFile.unchangedPolls = 0;
                        // Changed files go to changedFilesInLastPoll queue
                        if (queue !== changedFilesInLastPoll) {
                            queue[pollIndex] = undefined;
                            addChangedFileToLowPollingIntervalQueue(watchedFile);
                        }
                    }
                    else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
                        watchedFile.unchangedPolls++;
                    }
                    else if (queue === changedFilesInLastPoll) {
                        // Restart unchangedPollCount for unchanged file and move to low polling interval queue
                        watchedFile.unchangedPolls = 1;
                        queue[pollIndex] = undefined;
                        addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
                    }
                    else if (pollingInterval !== PollingInterval.High) {
                        watchedFile.unchangedPolls++;
                        queue[pollIndex] = undefined;
                        addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
                    }
                    if (queue[pollIndex]) {
                        // Copy this file to the non hole location
                        if (definedValueCopyToIndex < pollIndex) {
                            queue[definedValueCopyToIndex] = watchedFile;
                            queue[pollIndex] = undefined;
                        }
                        definedValueCopyToIndex++;
                    }
                }
                // Return next poll index
                return pollIndex;
                function nextPollIndex() {
                    pollIndex++;
                    if (pollIndex === queue.length) {
                        if (definedValueCopyToIndex < pollIndex) {
                            // There are holes from nextDefinedValueIndex to end of queue, change queue size
                            queue.length = definedValueCopyToIndex;
                        }
                        pollIndex = 0;
                        definedValueCopyToIndex = 0;
                    }
                }
            }
            function pollingIntervalQueue(pollingInterval) {
                switch (pollingInterval) {
                    case PollingInterval.Low:
                        return lowPollingIntervalQueue;
                    case PollingInterval.Medium:
                        return mediumPollingIntervalQueue;
                    case PollingInterval.High:
                        return highPollingIntervalQueue;
                }
            }
            function addToPollingIntervalQueue(file, pollingInterval) {
                pollingIntervalQueue(pollingInterval).push(file);
                scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
            }
            function addChangedFileToLowPollingIntervalQueue(file) {
                changedFilesInLastPoll.push(file);
                scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
            }
            function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
                if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
                    scheduleNextPoll(pollingInterval);
                }
            }
            function scheduleNextPoll(pollingInterval) {
                pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
            }
            function getModifiedTime(fileName) {
                return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
            }
        }
        ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
        /**
         * Returns true if file status changed
         */
        /*@internal*/
        function onWatchedFileStat(watchedFile, modifiedTime) {
            var oldTime = watchedFile.mtime.getTime();
            var newTime = modifiedTime.getTime();
            if (oldTime !== newTime) {
                watchedFile.mtime = modifiedTime;
                watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
                return true;
            }
            return false;
        }
        ts.onWatchedFileStat = onWatchedFileStat;
        /*@internal*/
        function getFileWatcherEventKind(oldTime, newTime) {
            return oldTime === 0
                ? FileWatcherEventKind.Created
                : newTime === 0
                    ? FileWatcherEventKind.Deleted
                    : FileWatcherEventKind.Changed;
        }
        ts.getFileWatcherEventKind = getFileWatcherEventKind;
        /**
         * Watch the directory recursively using host provided method to watch child directories
         * that means if this is recursive watcher, watch the children directories as well
         * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
         */
        /*@internal*/
        function createRecursiveDirectoryWatcher(host) {
            var cache = ts.createMap();
            var callbackCache = ts.createMultiMap();
            var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
            var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
            return createDirectoryWatcher;
            /**
             * Create the directory watcher for the dirPath.
             */
            function createDirectoryWatcher(dirName, callback) {
                var dirPath = toCanonicalFilePath(dirName);
                var directoryWatcher = cache.get(dirPath);
                if (directoryWatcher) {
                    directoryWatcher.refCount++;
                }
                else {
                    directoryWatcher = {
                        watcher: host.watchDirectory(dirName, function (fileName) {
                            // Call the actual callback
                            callbackCache.forEach(function (callbacks, rootDirName) {
                                if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
                                    callbacks.forEach(function (callback) { return callback(fileName); });
                                }
                            });
                            // Iterate through existing children and update the watches if needed
                            updateChildWatches(dirName, dirPath);
                        }),
                        refCount: 1,
                        childWatches: ts.emptyArray
                    };
                    cache.set(dirPath, directoryWatcher);
                    updateChildWatches(dirName, dirPath);
                }
                if (callback) {
                    callbackCache.add(dirPath, callback);
                }
                return {
                    dirName: dirName,
                    close: function () {
                        var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath));
                        if (callback)
                            callbackCache.remove(dirPath, callback);
                        directoryWatcher.refCount--;
                        if (directoryWatcher.refCount)
                            return;
                        cache.delete(dirPath);
                        ts.closeFileWatcherOf(directoryWatcher);
                        directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
                    }
                };
            }
            function updateChildWatches(dirName, dirPath) {
                // Iterate through existing children and update the watches if needed
                var parentWatcher = cache.get(dirPath);
                if (parentWatcher) {
                    parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches);
                }
            }
            /**
             * Watch the directories in the parentDir
             */
            function watchChildDirectories(parentDir, existingChildWatches) {
                var newChildWatches;
                ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
                    var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
                    // Filter our the symbolic link directories since those arent included in recursive watch
                    // which is same behaviour when recursive: true is passed to fs.watch
                    return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
                }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
                return newChildWatches || ts.emptyArray;
                /**
                 * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
                 */
                function createAndAddChildDirectoryWatcher(childName) {
                    var result = createDirectoryWatcher(childName);
                    addChildDirectoryWatcher(result);
                }
                /**
                 * Add child directory watcher to the new ChildDirectoryWatcher list
                 */
                function addChildDirectoryWatcher(childWatcher) {
                    (newChildWatches || (newChildWatches = [])).push(childWatcher);
                }
            }
        }
        ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
        function getNodeMajorVersion() {
            if (typeof process === "undefined") {
                return undefined;
            }
            var version = process.version;
            if (!version) {
                return undefined;
            }
            var dot = version.indexOf(".");
            if (dot === -1) {
                return undefined;
            }
            return parseInt(version.substring(1, dot));
        }
        ts.getNodeMajorVersion = getNodeMajorVersion;
        // TODO: GH#18217 this is used as if it's certainly defined in many places.
        ts.sys = (function () {
            // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
            // byte order mark from the specified encoding. Using any other byte order mark does
            // not actually work.
            var byteOrderMarkIndicator = "\uFEFF";
            function getNodeSystem() {
                var _fs = require("fs");
                var _path = require("path");
                var _os = require("os");
                // crypto can be absent on reduced node installations
                var _crypto;
                try {
                    _crypto = require("crypto");
                }
                catch (_a) {
                    _crypto = undefined;
                }
                var Buffer = require("buffer").Buffer;
                var nodeVersion = getNodeMajorVersion();
                var isNode4OrLater = nodeVersion >= 4;
                var platform = _os.platform();
                var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
                var FileSystemEntryKind;
                (function (FileSystemEntryKind) {
                    FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
                    FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
                })(FileSystemEntryKind || (FileSystemEntryKind = {}));
                var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER;
                var tscWatchFile = process.env.TSC_WATCHFILE;
                var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY;
                var dynamicPollingWatchFile;
                var nodeSystem = {
                    args: process.argv.slice(2),
                    newLine: _os.EOL,
                    useCaseSensitiveFileNames: useCaseSensitiveFileNames,
                    write: function (s) {
                        process.stdout.write(s);
                    },
                    writeOutputIsTTY: function () {
                        return process.stdout.isTTY;
                    },
                    readFile: readFile,
                    writeFile: writeFile,
                    watchFile: getWatchFile(),
                    watchDirectory: getWatchDirectory(),
                    resolvePath: function (path) { return _path.resolve(path); },
                    fileExists: fileExists,
                    directoryExists: directoryExists,
                    createDirectory: function (directoryName) {
                        if (!nodeSystem.directoryExists(directoryName)) {
                            _fs.mkdirSync(directoryName);
                        }
                    },
                    getExecutingFilePath: function () {
                        return __filename;
                    },
                    getCurrentDirectory: function () {
                        return process.cwd();
                    },
                    getDirectories: getDirectories,
                    getEnvironmentVariable: function (name) {
                        return process.env[name] || "";
                    },
                    readDirectory: readDirectory,
                    getModifiedTime: getModifiedTime,
                    setModifiedTime: setModifiedTime,
                    deleteFile: deleteFile,
                    createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
                    createSHA256Hash: _crypto ? createSHA256Hash : undefined,
                    getMemoryUsage: function () {
                        if (global.gc) {
                            global.gc();
                        }
                        return process.memoryUsage().heapUsed;
                    },
                    getFileSize: function (path) {
                        try {
                            var stat = _fs.statSync(path);
                            if (stat.isFile()) {
                                return stat.size;
                            }
                        }
                        catch ( /*ignore*/_a) { /*ignore*/ }
                        return 0;
                    },
                    exit: function (exitCode) {
                        process.exit(exitCode);
                    },
                    realpath: realpath,
                    debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
                    tryEnableSourceMapsForHost: function () {
                        try {
                            require(318) /* source-map-support */.install();
                        }
                        catch (_a) {
                            // Could not enable source maps.
                        }
                    },
                    setTimeout: setTimeout,
                    clearTimeout: clearTimeout,
                    clearScreen: function () {
                        process.stdout.write("\x1Bc");
                    },
                    setBlocking: function () {
                        if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
                            process.stdout._handle.setBlocking(true);
                        }
                    },
                    bufferFrom: bufferFrom,
                    base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
                    base64encode: function (input) { return bufferFrom(input).toString("base64"); },
                };
                return nodeSystem;
                function bufferFrom(input, encoding) {
                    // See https://github.com/Microsoft/TypeScript/issues/25652
                    return Buffer.from && Buffer.from !== Int8Array.from
                        ? Buffer.from(input, encoding)
                        : new Buffer(input, encoding);
                }
                function isFileSystemCaseSensitive() {
                    // win32\win64 are case insensitive platforms
                    if (platform === "win32" || platform === "win64") {
                        return false;
                    }
                    // If this file exists under a different case, we must be case-insensitve.
                    return !fileExists(swapCase(__filename));
                }
                /** Convert all lowercase chars to uppercase, and vice-versa */
                function swapCase(s) {
                    return s.replace(/\w/g, function (ch) {
                        var up = ch.toUpperCase();
                        return ch === up ? ch.toLowerCase() : up;
                    });
                }
                function getWatchFile() {
                    switch (tscWatchFile) {
                        case "PriorityPollingInterval":
                            // Use polling interval based on priority when create watch using host.watchFile
                            return fsWatchFile;
                        case "DynamicPriorityPolling":
                            // Use polling interval but change the interval depending on file changes and their default polling interval
                            return createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout });
                        case "UseFsEvents":
                            // Use notifications from FS to watch with falling back to fs.watchFile
                            return watchFileUsingFsWatch;
                        case "UseFsEventsWithFallbackDynamicPolling":
                            // Use notifications from FS to watch with falling back to dynamic watch file
                            dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout });
                            return createWatchFileUsingDynamicWatchFile(dynamicPollingWatchFile);
                        case "UseFsEventsOnParentDirectory":
                            // Use notifications from FS to watch with falling back to fs.watchFile
                            return createNonPollingWatchFile();
                    }
                    return useNonPollingWatchers ?
                        createNonPollingWatchFile() :
                        // Default to do not use polling interval as it is before this experiment branch
                        function (fileName, callback) { return fsWatchFile(fileName, callback); };
                }
                function getWatchDirectory() {
                    // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
                    // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
                    var fsSupportsRecursive = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
                    if (fsSupportsRecursive) {
                        return watchDirectoryUsingFsWatch;
                    }
                    var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ?
                        createWatchDirectoryUsing(fsWatchFile) :
                        tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ?
                            createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) :
                            watchDirectoryUsingFsWatch;
                    var watchDirectoryRecursively = createRecursiveDirectoryWatcher({
                        useCaseSensitiveFileNames: useCaseSensitiveFileNames,
                        directoryExists: directoryExists,
                        getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
                        watchDirectory: watchDirectory,
                        realpath: realpath
                    });
                    return function (directoryName, callback, recursive) {
                        if (recursive) {
                            return watchDirectoryRecursively(directoryName, callback);
                        }
                        return watchDirectory(directoryName, callback);
                    };
                }
                function createNonPollingWatchFile() {
                    // One file can have multiple watchers
                    var fileWatcherCallbacks = ts.createMultiMap();
                    var dirWatchers = ts.createMap();
                    var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
                    return nonPollingWatchFile;
                    function nonPollingWatchFile(fileName, callback) {
                        var filePath = toCanonicalName(fileName);
                        fileWatcherCallbacks.add(filePath, callback);
                        var dirPath = ts.getDirectoryPath(filePath) || ".";
                        var watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath);
                        watcher.referenceCount++;
                        return {
                            close: function () {
                                if (watcher.referenceCount === 1) {
                                    watcher.close();
                                    dirWatchers.delete(dirPath);
                                }
                                else {
                                    watcher.referenceCount--;
                                }
                                fileWatcherCallbacks.remove(filePath, callback);
                            }
                        };
                    }
                    function createDirectoryWatcher(dirName, dirPath) {
                        var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) {
                            // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
                            var fileName = !ts.isString(relativeFileName)
                                ? undefined // TODO: GH#18217
                                : ts.getNormalizedAbsolutePath(relativeFileName, dirName);
                            // Some applications save a working file via rename operations
                            var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName));
                            if (callbacks) {
                                for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
                                    var fileCallback = callbacks_1[_i];
                                    fileCallback(fileName, FileWatcherEventKind.Changed);
                                }
                            }
                        });
                        watcher.referenceCount = 0;
                        dirWatchers.set(dirPath, watcher);
                        return watcher;
                    }
                }
                function fsWatchFile(fileName, callback, pollingInterval) {
                    _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged);
                    var eventKind;
                    return {
                        close: function () { return _fs.unwatchFile(fileName, fileChanged); }
                    };
                    function fileChanged(curr, prev) {
                        // previous event kind check is to ensure we recongnize the file as previously also missing when it is restored or renamed twice (that is it disappears and reappears)
                        // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
                        var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
                        if (+curr.mtime === 0) {
                            if (isPreviouslyDeleted) {
                                // Already deleted file, no need to callback again
                                return;
                            }
                            eventKind = FileWatcherEventKind.Deleted;
                        }
                        else if (isPreviouslyDeleted) {
                            eventKind = FileWatcherEventKind.Created;
                        }
                        // If there is no change in modified time, ignore the event
                        else if (+curr.mtime === +prev.mtime) {
                            return;
                        }
                        else {
                            // File changed
                            eventKind = FileWatcherEventKind.Changed;
                        }
                        callback(fileName, eventKind);
                    }
                }
                function createFileWatcherCallback(callback) {
                    return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
                }
                function createFsWatchCallbackForFileWatcherCallback(fileName, callback) {
                    return function (eventName) {
                        if (eventName === "rename") {
                            callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
                        }
                        else {
                            // Change
                            callback(fileName, FileWatcherEventKind.Changed);
                        }
                    };
                }
                function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
                    return function (eventName, relativeFileName) {
                        // In watchDirectory we only care about adding and removing files (when event name is
                        // "rename"); changes made within files are handled by corresponding fileWatchers (when
                        // event name is "change")
                        if (eventName === "rename") {
                            // When deleting a file, the passed baseFileName is null
                            callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
                        }
                    };
                }
                function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingWatchFile, pollingInterval) {
                    var options;
                    /** Watcher for the file system entry depending on whether it is missing or present */
                    var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
                        watchMissingFileSystemEntry() :
                        watchPresentFileSystemEntry();
                    return {
                        close: function () {
                            // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
                            watcher.close();
                            watcher = undefined;
                        }
                    };
                    /**
                     * Invoke the callback with rename and update the watcher if not closed
                     * @param createWatcher
                     */
                    function invokeCallbackAndUpdateWatcher(createWatcher) {
                        // Call the callback for current directory
                        callback("rename", "");
                        // If watcher is not closed, update it
                        if (watcher) {
                            watcher.close();
                            watcher = createWatcher();
                        }
                    }
                    /**
                     * Watch the file or directory that is currently present
                     * and when the watched file or directory is deleted, switch to missing file system entry watcher
                     */
                    function watchPresentFileSystemEntry() {
                        // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
                        // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
                        if (options === undefined) {
                            if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) {
                                options = { persistent: true, recursive: !!recursive };
                            }
                            else {
                                options = { persistent: true };
                            }
                        }
                        try {
                            var presentWatcher = _fs.watch(fileOrDirectory, options, callback);
                            // Watch the missing file or directory or error
                            presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
                            return presentWatcher;
                        }
                        catch (e) {
                            // Catch the exception and use polling instead
                            // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
                            // so instead of throwing error, use fs.watchFile
                            return watchPresentFileSystemEntryWithFsWatchFile();
                        }
                    }
                    /**
                     * Watch the file or directory using fs.watchFile since fs.watch threw exception
                     * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point
                     */
                    function watchPresentFileSystemEntryWithFsWatchFile() {
                        return fallbackPollingWatchFile(fileOrDirectory, createFileWatcherCallback(callback), pollingInterval);
                    }
                    /**
                     * Watch the file or directory that is missing
                     * and switch to existing file or directory when the missing filesystem entry is created
                     */
                    function watchMissingFileSystemEntry() {
                        return fallbackPollingWatchFile(fileOrDirectory, function (_fileName, eventKind) {
                            if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
                                // Call the callback for current file or directory
                                // For now it could be callback for the inner directory creation,
                                // but just return current directory, better than current no-op
                                invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
                            }
                        }, pollingInterval);
                    }
                }
                function watchFileUsingFsWatch(fileName, callback, pollingInterval) {
                    return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, fsWatchFile, pollingInterval);
                }
                function createWatchFileUsingDynamicWatchFile(watchFile) {
                    return function (fileName, callback, pollingInterval) { return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback), /*recursive*/ false, watchFile, pollingInterval); };
                }
                function fsWatchDirectory(directoryName, callback, recursive) {
                    return fsWatch(directoryName, 1 /* Directory */, callback, !!recursive, fsWatchFile);
                }
                function watchDirectoryUsingFsWatch(directoryName, callback, recursive) {
                    return fsWatchDirectory(directoryName, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive);
                }
                function createWatchDirectoryUsing(fsWatchFile) {
                    return function (directoryName, callback) { return fsWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium); };
                }
                function readFile(fileName, _encoding) {
                    if (!fileExists(fileName)) {
                        return undefined;
                    }
                    var buffer = _fs.readFileSync(fileName);
                    var len = buffer.length;
                    if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
                        // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
                        // flip all byte pairs and treat as little endian.
                        len &= ~1; // Round down to a multiple of 2
                        for (var i = 0; i < len; i += 2) {
                            var temp = buffer[i];
                            buffer[i] = buffer[i + 1];
                            buffer[i + 1] = temp;
                        }
                        return buffer.toString("utf16le", 2);
                    }
                    if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
                        // Little endian UTF-16 byte order mark detected
                        return buffer.toString("utf16le", 2);
                    }
                    if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
                        // UTF-8 byte order mark detected
                        return buffer.toString("utf8", 3);
                    }
                    // Default is UTF-8 with no byte order mark
                    return buffer.toString("utf8");
                }
                function writeFile(fileName, data, writeByteOrderMark) {
                    // If a BOM is required, emit one
                    if (writeByteOrderMark) {
                        data = byteOrderMarkIndicator + data;
                    }
                    var fd;
                    try {
                        fd = _fs.openSync(fileName, "w");
                        _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
                    }
                    finally {
                        if (fd !== undefined) {
                            _fs.closeSync(fd);
                        }
                    }
                }
                function getAccessibleFileSystemEntries(path) {
                    try {
                        var entries = _fs.readdirSync(path || ".").sort();
                        var files = [];
                        var directories = [];
                        for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
                            var entry = entries_2[_i];
                            // This is necessary because on some file system node fails to exclude
                            // "." and "..". See https://github.com/nodejs/node/issues/4002
                            if (entry === "." || entry === "..") {
                                continue;
                            }
                            var name = ts.combinePaths(path, entry);
                            var stat = void 0;
                            try {
                                stat = _fs.statSync(name);
                            }
                            catch (e) {
                                continue;
                            }
                            if (stat.isFile()) {
                                files.push(entry);
                            }
                            else if (stat.isDirectory()) {
                                directories.push(entry);
                            }
                        }
                        return { files: files, directories: directories };
                    }
                    catch (e) {
                        return ts.emptyFileSystemEntries;
                    }
                }
                function readDirectory(path, extensions, excludes, includes, depth) {
                    return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
                }
                function fileSystemEntryExists(path, entryKind) {
                    try {
                        var stat = _fs.statSync(path);
                        switch (entryKind) {
                            case 0 /* File */: return stat.isFile();
                            case 1 /* Directory */: return stat.isDirectory();
                            default: return false;
                        }
                    }
                    catch (e) {
                        return false;
                    }
                }
                function fileExists(path) {
                    return fileSystemEntryExists(path, 0 /* File */);
                }
                function directoryExists(path) {
                    return fileSystemEntryExists(path, 1 /* Directory */);
                }
                function getDirectories(path) {
                    return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); });
                }
                function realpath(path) {
                    try {
                        return _fs.realpathSync(path);
                    }
                    catch (_a) {
                        return path;
                    }
                }
                function getModifiedTime(path) {
                    try {
                        return _fs.statSync(path).mtime;
                    }
                    catch (e) {
                        return undefined;
                    }
                }
                function setModifiedTime(path, time) {
                    try {
                        _fs.utimesSync(path, time, time);
                    }
                    catch (e) {
                        return;
                    }
                }
                function deleteFile(path) {
                    try {
                        return _fs.unlinkSync(path);
                    }
                    catch (e) {
                        return;
                    }
                }
                /**
                 * djb2 hashing algorithm
                 * http://www.cse.yorku.ca/~oz/hash.html
                 */
                function generateDjb2Hash(data) {
                    var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
                    return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
                }
                function createMD5HashUsingNativeCrypto(data) {
                    var hash = _crypto.createHash("md5");
                    hash.update(data);
                    return hash.digest("hex");
                }
                function createSHA256Hash(data) {
                    var hash = _crypto.createHash("sha256");
                    hash.update(data);
                    return hash.digest("hex");
                }
            }
            function getChakraSystem() {
                var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
                return {
                    newLine: ChakraHost.newLine || "\r\n",
                    args: ChakraHost.args,
                    useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames,
                    write: ChakraHost.echo,
                    readFile: function (path, _encoding) {
                        // encoding is automatically handled by the implementation in ChakraHost
                        return ChakraHost.readFile(path);
                    },
                    writeFile: function (path, data, writeByteOrderMark) {
                        // If a BOM is required, emit one
                        if (writeByteOrderMark) {
                            data = byteOrderMarkIndicator + data;
                        }
                        ChakraHost.writeFile(path, data);
                    },
                    resolvePath: ChakraHost.resolvePath,
                    fileExists: ChakraHost.fileExists,
                    deleteFile: ChakraHost.deleteFile,
                    getModifiedTime: ChakraHost.getModifiedTime,
                    setModifiedTime: ChakraHost.setModifiedTime,
                    directoryExists: ChakraHost.directoryExists,
                    createDirectory: ChakraHost.createDirectory,
                    getExecutingFilePath: function () { return ChakraHost.executingFile; },
                    getCurrentDirectory: function () { return ChakraHost.currentDirectory; },
                    getDirectories: ChakraHost.getDirectories,
                    getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }),
                    readDirectory: function (path, extensions, excludes, includes, _depth) {
                        var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory);
                        return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern);
                    },
                    exit: ChakraHost.quit,
                    realpath: realpath
                };
            }
            function recursiveCreateDirectory(directoryPath, sys) {
                var basePath = ts.getDirectoryPath(directoryPath);
                var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath);
                if (shouldCreateParent) {
                    recursiveCreateDirectory(basePath, sys);
                }
                if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
                    sys.createDirectory(directoryPath);
                }
            }
            var sys;
            if (typeof ChakraHost !== "undefined") {
                sys = getChakraSystem();
            }
            else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
                // process and process.nextTick checks if current environment is node-like
                // process.browser check excludes webpack and browserify
                sys = getNodeSystem();
            }
            if (sys) {
                // patch writefile to create folder before writing the file
                var originalWriteFile_1 = sys.writeFile;
                sys.writeFile = function (path, data, writeBom) {
                    var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path));
                    if (directoryPath && !sys.directoryExists(directoryPath)) {
                        recursiveCreateDirectory(directoryPath, sys);
                    }
                    originalWriteFile_1.call(sys, path, data, writeBom);
                };
            }
            return sys;
        })();
        if (ts.sys && ts.sys.getEnvironmentVariable) {
            setCustomPollingValues(ts.sys);
            ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
                ? 1 /* Normal */
                : 0 /* None */;
        }
        if (ts.sys && ts.sys.debugMode) {
            ts.Debug.isDebugging = true;
        }
    })(ts || (ts = {}));
    // <auto-generated />
    // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
    /* @internal */
    var ts;
    (function (ts) {
        function diag(code, category, key, message, reportsUnnecessary) {
            return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary };
        }
        // tslint:disable-next-line variable-name
        ts.Diagnostics = {
            Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
            Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
            _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
            A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."),
            Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
            Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
            An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."),
            Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
            A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."),
            A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."),
            Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."),
            A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."),
            An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."),
            An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."),
            An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."),
            An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."),
            An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."),
            An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."),
            An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."),
            readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."),
            Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
            _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
            _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
            _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."),
            super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."),
            Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."),
            Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."),
            A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."),
            Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."),
            _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."),
            _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."),
            _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
            _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."),
            _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."),
            A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."),
            A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."),
            A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
            A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."),
            A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."),
            A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."),
            A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."),
            A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."),
            A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
            Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."),
            Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."),
            An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."),
            The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."),
            A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."),
            The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."),
            Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
            Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."),
            An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."),
            The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise<T> type."),
            In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."),
            Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."),
            Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."),
            _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."),
            _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."),
            A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."),
            Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
            Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."),
            An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."),
            _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."),
            _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."),
            Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."),
            Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."),
            Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."),
            An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
            A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."),
            An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."),
            _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
            Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
            Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
            Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."),
            with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."),
            delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."),
            A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."),
            A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."),
            A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."),
            Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
            A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."),
            Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
            Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
            A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."),
            Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
            A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."),
            A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."),
            An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."),
            An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."),
            An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."),
            An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
            Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."),
            Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
            Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
            Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
            Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
            Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
            Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
            Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
            case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
            Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
            Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
            Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
            Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
            Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
            Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
            Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
            Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
            Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
            String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
            Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
            or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
            Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
            Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."),
            Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."),
            File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."),
            new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead."),
            const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
            const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."),
            let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."),
            Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
            Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
            An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."),
            A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."),
            Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."),
            A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."),
            A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."),
            A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."),
            A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."),
            A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."),
            A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."),
            extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
            extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
            Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."),
            implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
            Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
            Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
            Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
            Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
            Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
            Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
            A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."),
            An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."),
            Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
            Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
            A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."),
            A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."),
            Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."),
            The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."),
            The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."),
            An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
            Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
            An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
            Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."),
            Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."),
            Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."),
            An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."),
            Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
            Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
            Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."),
            Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."),
            Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."),
            Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
            Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
            Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
            Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
            Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
            A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
            Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
            Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."),
            Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."),
            Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."),
            Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."),
            Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."),
            Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."),
            Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."),
            Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."),
            An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."),
            _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
            Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."),
            Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
            Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."),
            Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."),
            A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."),
            A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."),
            A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."),
            An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."),
            An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."),
            An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."),
            An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."),
            A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."),
            The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."),
            The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."),
            Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."),
            Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."),
            Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."),
            Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."),
            abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."),
            _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."),
            Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."),
            Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."),
            An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."),
            A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."),
            A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."),
            A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."),
            Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."),
            Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."),
            Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."),
            _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."),
            A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."),
            A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."),
            A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."),
            A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."),
            with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."),
            await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."),
            can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."),
            The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."),
            Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."),
            Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."),
            Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."),
            A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."),
            An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."),
            A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."),
            Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
            Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
            Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
            Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
            Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
            Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
            Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
            String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
            Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."),
            _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"),
            A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."),
            A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."),
            A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."),
            unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."),
            unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."),
            unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."),
            An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."),
            An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."),
            infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."),
            Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."),
            Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"),
            Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
            The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."),
            A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
            An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"),
            This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."),
            use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."),
            Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
            use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
            Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
            Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."),
            Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."),
            Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
            Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
            Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."),
            File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
            Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."),
            Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."),
            An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."),
            Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."),
            A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
            An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."),
            Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."),
            Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."),
            Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
            Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."),
            Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."),
            Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
            Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."),
            Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."),
            Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."),
            Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."),
            Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
            Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."),
            Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."),
            Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
            Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."),
            Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."),
            Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."),
            Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
            this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."),
            this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."),
            this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."),
            this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."),
            super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."),
            super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."),
            Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."),
            super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."),
            Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."),
            Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."),
            Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."),
            An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."),
            This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."),
            Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."),
            Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."),
            Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."),
            Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."),
            Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"),
            Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."),
            Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."),
            Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."),
            Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."),
            Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."),
            This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."),
            A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."),
            An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."),
            The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."),
            The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."),
            The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."),
            The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."),
            The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."),
            The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."),
            The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."),
            The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."),
            Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."),
            Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."),
            This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."),
            Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
            A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."),
            A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."),
            A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."),
            Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."),
            Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."),
            Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
            Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
            A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."),
            Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."),
            A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."),
            Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."),
            get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."),
            A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."),
            Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."),
            Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."),
            Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."),
            Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."),
            Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."),
            Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
            Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
            Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
            Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
            Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
            Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
            Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
            Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
            Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
            Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
            Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
            Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."),
            Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."),
            Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."),
            Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."),
            Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type.  Variable '{0}' must be of type '{1}', but here has type '{2}'."),
            The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."),
            The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."),
            The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."),
            The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."),
            Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
            Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."),
            The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."),
            Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."),
            Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."),
            Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."),
            Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
            Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."),
            Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."),
            Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."),
            Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."),
            Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
            A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."),
            Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),
            Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),
            Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),
            Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."),
            Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
            All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."),
            Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
            Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
            In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."),
            A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."),
            A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."),
            Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."),
            Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."),
            Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."),
            Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
            Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."),
            Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."),
            Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."),
            Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."),
            Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."),
            Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."),
            Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."),
            Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."),
            The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."),
            Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."),
            Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
            Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
            Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
            An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."),
            The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."),
            Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."),
            Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."),
            Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
            Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
            An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."),
            Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."),
            Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."),
            Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."),
            A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."),
            A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."),
            A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."),
            this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."),
            super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."),
            A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."),
            Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
            The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."),
            Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."),
            A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."),
            Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."),
            Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."),
            In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."),
            const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."),
            A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."),
            const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."),
            const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."),
            Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."),
            let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."),
            Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."),
            The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."),
            Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."),
            The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."),
            Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."),
            An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."),
            The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."),
            The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."),
            Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."),
            Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."),
            Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."),
            Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."),
            The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."),
            Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."),
            Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."),
            An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."),
            A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."),
            A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."),
            _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."),
            Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
            Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."),
            A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."),
            _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."),
            Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."),
            No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."),
            Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."),
            Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."),
            Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."),
            Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."),
            Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."),
            Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."),
            Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."),
            All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."),
            Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."),
            A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."),
            An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."),
            Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."),
            Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."),
            The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."),
            yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."),
            await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."),
            Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."),
            A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."),
            The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."),
            A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."),
            Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."),
            Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."),
            Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
            Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
            Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
            A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."),
            Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."),
            Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."),
            Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."),
            Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."),
            Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."),
            Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."),
            The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
            Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."),
            Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),
            Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."),
            A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."),
            Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."),
            The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."),
            Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
            Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."),
            Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"),
            Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"),
            Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."),
            Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
            Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."),
            Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."),
            Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."),
            Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."),
            Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."),
            Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"),
            Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"),
            Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."),
            The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."),
            Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."),
            Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."),
            A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."),
            Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."),
            Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),
            Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),
            Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"),
            Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
            Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
            Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."),
            A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."),
            No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."),
            Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"),
            Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
            Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
            Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
            Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
            Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
            Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
            _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
            Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
            JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
            JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
            The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
            JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),
            Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."),
            JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."),
            JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."),
            Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."),
            JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."),
            The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."),
            JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."),
            Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."),
            A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."),
            Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."),
            Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."),
            Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."),
            Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."),
            JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."),
            Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."),
            super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."),
            super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."),
            Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."),
            Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"),
            Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"),
            Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."),
            Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."),
            Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."),
            Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."),
            export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."),
            Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."),
            Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."),
            Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."),
            Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."),
            Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."),
            Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."),
            Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."),
            Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."),
            A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."),
            Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."),
            A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."),
            A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."),
            A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."),
            get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."),
            this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."),
            The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."),
            The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."),
            _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."),
            All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."),
            Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."),
            Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"),
            An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."),
            _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."),
            _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."),
            Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."),
            Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true),
            The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"),
            An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),
            Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."),
            Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."),
            Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."),
            The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."),
            _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."),
            The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."),
            The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."),
            An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
            Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."),
            Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."),
            Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."),
            Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."),
            _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."),
            A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),
            A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),
            Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"),
            The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."),
            Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."),
            Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."),
            Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type.  Property '{0}' must be of type '{1}', but here has type '{2}'."),
            Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."),
            Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."),
            Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"),
            Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."),
            Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."),
            Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."),
            Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
            Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."),
            Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
            Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"),
            _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
            Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."),
            An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."),
            Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."),
            Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"),
            Index_0_is_out_of_bounds_in_tuple_of_length_1: diag(2733, ts.DiagnosticCategory.Error, "Index_0_is_out_of_bounds_in_tuple_of_length_1_2733", "Index '{0}' is out-of-bounds in tuple of length {1}."),
            It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."),
            Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."),
            Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."),
            Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."),
            Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
            Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
            Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
            Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."),
            Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."),
            Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."),
            Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."),
            extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."),
            extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."),
            Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."),
            Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."),
            Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."),
            Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
            Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."),
            Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
            Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."),
            Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
            Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."),
            Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
            Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."),
            Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
            Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."),
            Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
            Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."),
            Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),
            Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."),
            Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."),
            Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."),
            Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."),
            Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."),
            Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."),
            Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."),
            Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
            Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."),
            Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."),
            Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."),
            Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."),
            Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."),
            Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."),
            Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."),
            Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."),
            Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."),
            Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."),
            Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."),
            Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),
            Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),
            Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."),
            Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."),
            Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."),
            Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."),
            Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."),
            Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."),
            Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."),
            Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."),
            Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."),
            Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."),
            Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."),
            Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."),
            Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
            Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."),
            Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),
            Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),
            Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
            Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
            Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
            The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
            Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
            File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
            Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
            Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."),
            Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
            Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."),
            Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."),
            Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."),
            Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."),
            Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."),
            Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."),
            Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."),
            A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."),
            Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."),
            Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."),
            Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."),
            The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."),
            Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."),
            Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."),
            Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."),
            Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."),
            Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."),
            Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."),
            File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."),
            Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."),
            Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
            Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
            Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
            Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
            Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."),
            Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
            Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."),
            Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
            Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
            Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
            Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."),
            Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."),
            Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
            Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
            Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."),
            Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."),
            Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
            Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
            Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."),
            Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
            Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
            Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
            Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
            Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
            Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
            Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
            Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."),
            Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
            options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
            file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
            Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
            Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
            Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
            Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."),
            Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
            File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
            KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
            FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
            VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
            LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
            DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
            STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
            FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
            Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
            Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
            Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."),
            Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."),
            Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'."),
            Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
            Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
            Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
            Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."),
            File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
            File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."),
            Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."),
            Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."),
            Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."),
            File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."),
            Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."),
            NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
            Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."),
            Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
            Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."),
            Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."),
            Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."),
            Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."),
            Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
            Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."),
            Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."),
            Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."),
            Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."),
            Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."),
            Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."),
            Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."),
            Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."),
            Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."),
            File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."),
            Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."),
            Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."),
            Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"),
            Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."),
            Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
            Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."),
            Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."),
            Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"),
            Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
            paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."),
            Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
            Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."),
            Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."),
            Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."),
            File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
            File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."),
            Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."),
            Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
            package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."),
            package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."),
            Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
            Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."),
            Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."),
            Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."),
            baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."),
            rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."),
            Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."),
            Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."),
            Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
            Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
            Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."),
            Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
            Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"),
            Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."),
            Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"),
            Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
            Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
            Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"),
            Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"),
            Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
            Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."),
            Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"),
            Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."),
            Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."),
            Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."),
            Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"),
            Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"),
            Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."),
            Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."),
            File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."),
            _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
            Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
            Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
            The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."),
            Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."),
            Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true),
            Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
            Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."),
            Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."),
            Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."),
            Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."),
            Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),
            Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),
            Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."),
            Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."),
            Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
            Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
            Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."),
            Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."),
            Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."),
            Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."),
            Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."),
            The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"),
            Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."),
            Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."),
            Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."),
            Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."),
            List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."),
            Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
            The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."),
            Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),
            Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
            Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
            A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."),
            List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."),
            Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
            Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"),
            Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
            Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
            Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
            Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
            Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
            Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
            Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
            Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
            Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."),
            Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
            List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
            Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
            Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."),
            Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."),
            Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."),
            Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
            Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."),
            Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
            Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."),
            Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."),
            Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."),
            All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true),
            Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."),
            Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
            Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
            _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
            Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
            All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
            All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
            Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"),
            Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
            _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
            and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
            All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
            package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."),
            package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."),
            package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."),
            package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."),
            An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."),
            An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."),
            Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"),
            Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"),
            Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
            Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
            Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
            Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
            Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
            Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
            File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
            Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
            Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
            Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"),
            Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"),
            Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"),
            Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"),
            Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"),
            Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
            A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"),
            A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"),
            Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
            Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
            delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"),
            Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
            Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"),
            Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"),
            Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"),
            Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
            Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
            Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"),
            Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"),
            Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
            Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
            The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
            The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
            The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
            Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
            Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
            Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
            new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."),
            _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."),
            Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."),
            Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."),
            Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."),
            Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."),
            Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."),
            Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."),
            Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."),
            Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."),
            _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."),
            _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),
            Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),
            Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."),
            JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."),
            Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
            Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
            Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
            Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."),
            Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."),
            Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."),
            Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."),
            Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."),
            Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
            Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."),
            Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."),
            Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."),
            Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."),
            If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"),
            The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."),
            Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."),
            You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
            You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."),
            import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."),
            export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."),
            type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."),
            implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."),
            interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."),
            module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."),
            type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."),
            _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."),
            types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."),
            type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."),
            parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."),
            non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."),
            enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."),
            type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."),
            Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."),
            Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."),
            Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
            JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."),
            JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."),
            JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."),
            JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."),
            JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."),
            Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."),
            Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."),
            Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."),
            JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."),
            JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."),
            The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."),
            You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."),
            Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."),
            class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
            Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
            JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."),
            JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."),
            Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."),
            JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
            Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."),
            A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."),
            An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
            A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),
            JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."),
            super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."),
            Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
            super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."),
            _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"),
            Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."),
            JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."),
            Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."),
            JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
            JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
            Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"),
            A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
            The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."),
            No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),
            File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
            This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."),
            Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."),
            JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."),
            require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."),
            This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."),
            Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
            Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"),
            Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
            Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"),
            Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
            Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
            Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
            Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
            Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
            Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
            Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
            Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
            Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
            Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
            Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
            Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
            Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
            Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
            Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
            Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
            Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
            Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
            Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
            Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
            Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
            Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"),
            Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
            Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
            Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
            Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
            Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
            Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
            Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""),
            Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
            Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
            Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
            Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
            Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
            Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
            Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
            Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
            Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
            Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
            Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
            Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
            Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
            Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
            Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
            Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
            Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
            Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
            Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"),
            Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
            Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
            Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
            Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"),
            Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
            Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
            Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"),
            Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"),
            Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"),
            Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"),
            Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
            Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
            Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
            Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
            Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"),
            Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"),
            Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
            Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
            Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
            Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
            Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"),
            Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
            Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
            Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
            Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
            Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
            Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
            Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
            Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
            Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
            Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
            Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
            Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
            Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
            Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
            Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
            Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"),
            Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
            Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
            Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
            Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
            Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
            Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
            Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
            Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
            Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"),
            Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"),
        };
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        var _a;
        /* @internal */
        function tokenIsIdentifierOrKeyword(token) {
            return token >= 71 /* Identifier */;
        }
        ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
        /* @internal */
        function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
            return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
        }
        ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
        var textToKeywordObj = (_a = {
            abstract: 117 /* AbstractKeyword */,
            any: 119 /* AnyKeyword */,
            as: 118 /* AsKeyword */,
            boolean: 122 /* BooleanKeyword */,
            break: 72 /* BreakKeyword */,
            case: 73 /* CaseKeyword */,
            catch: 74 /* CatchKeyword */,
            class: 75 /* ClassKeyword */,
            continue: 77 /* ContinueKeyword */,
            const: 76 /* ConstKeyword */
        },
            _a["" + "constructor"] = 123 /* ConstructorKeyword */,
            _a.debugger = 78 /* DebuggerKeyword */,
            _a.declare = 124 /* DeclareKeyword */,
            _a.default = 79 /* DefaultKeyword */,
            _a.delete = 80 /* DeleteKeyword */,
            _a.do = 81 /* DoKeyword */,
            _a.else = 82 /* ElseKeyword */,
            _a.enum = 83 /* EnumKeyword */,
            _a.export = 84 /* ExportKeyword */,
            _a.extends = 85 /* ExtendsKeyword */,
            _a.false = 86 /* FalseKeyword */,
            _a.finally = 87 /* FinallyKeyword */,
            _a.for = 88 /* ForKeyword */,
            _a.from = 143 /* FromKeyword */,
            _a.function = 89 /* FunctionKeyword */,
            _a.get = 125 /* GetKeyword */,
            _a.if = 90 /* IfKeyword */,
            _a.implements = 108 /* ImplementsKeyword */,
            _a.import = 91 /* ImportKeyword */,
            _a.in = 92 /* InKeyword */,
            _a.infer = 126 /* InferKeyword */,
            _a.instanceof = 93 /* InstanceOfKeyword */,
            _a.interface = 109 /* InterfaceKeyword */,
            _a.is = 127 /* IsKeyword */,
            _a.keyof = 128 /* KeyOfKeyword */,
            _a.let = 110 /* LetKeyword */,
            _a.module = 129 /* ModuleKeyword */,
            _a.namespace = 130 /* NamespaceKeyword */,
            _a.never = 131 /* NeverKeyword */,
            _a.new = 94 /* NewKeyword */,
            _a.null = 95 /* NullKeyword */,
            _a.number = 134 /* NumberKeyword */,
            _a.object = 135 /* ObjectKeyword */,
            _a.package = 111 /* PackageKeyword */,
            _a.private = 112 /* PrivateKeyword */,
            _a.protected = 113 /* ProtectedKeyword */,
            _a.public = 114 /* PublicKeyword */,
            _a.readonly = 132 /* ReadonlyKeyword */,
            _a.require = 133 /* RequireKeyword */,
            _a.global = 144 /* GlobalKeyword */,
            _a.return = 96 /* ReturnKeyword */,
            _a.set = 136 /* SetKeyword */,
            _a.static = 115 /* StaticKeyword */,
            _a.string = 137 /* StringKeyword */,
            _a.super = 97 /* SuperKeyword */,
            _a.switch = 98 /* SwitchKeyword */,
            _a.symbol = 138 /* SymbolKeyword */,
            _a.this = 99 /* ThisKeyword */,
            _a.throw = 100 /* ThrowKeyword */,
            _a.true = 101 /* TrueKeyword */,
            _a.try = 102 /* TryKeyword */,
            _a.type = 139 /* TypeKeyword */,
            _a.typeof = 103 /* TypeOfKeyword */,
            _a.undefined = 140 /* UndefinedKeyword */,
            _a.unique = 141 /* UniqueKeyword */,
            _a.unknown = 142 /* UnknownKeyword */,
            _a.var = 104 /* VarKeyword */,
            _a.void = 105 /* VoidKeyword */,
            _a.while = 106 /* WhileKeyword */,
            _a.with = 107 /* WithKeyword */,
            _a.yield = 116 /* YieldKeyword */,
            _a.async = 120 /* AsyncKeyword */,
            _a.await = 121 /* AwaitKeyword */,
            _a.of = 145 /* OfKeyword */,
            _a);
        var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
        var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, "</": 28 /* LessThanSlashToken */, ">>": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ }));
        /*
            As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
            IdentifierStart ::
                Can contain Unicode 3.0.0 categories:
                Uppercase letter (Lu),
                Lowercase letter (Ll),
                Titlecase letter (Lt),
                Modifier letter (Lm),
                Other letter (Lo), or
                Letter number (Nl).
            IdentifierPart :: =
                Can contain IdentifierStart + Unicode 3.0.0 categories:
                Non-spacing mark (Mn),
                Combining spacing mark (Mc),
                Decimal number (Nd), or
                Connector punctuation (Pc).
    
            Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
            http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
        */
        var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
        var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
        /*
            As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
            IdentifierStart ::
                Can contain Unicode 6.2 categories:
                Uppercase letter (Lu),
                Lowercase letter (Ll),
                Titlecase letter (Lt),
                Modifier letter (Lm),
                Other letter (Lo), or
                Letter number (Nl).
            IdentifierPart ::
                Can contain IdentifierStart + Unicode 6.2 categories:
                Non-spacing mark (Mn),
                Combining spacing mark (Mc),
                Decimal number (Nd),
                Connector punctuation (Pc),
                <ZWNJ>, or
                <ZWJ>.
    
            Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
            http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
        */
        var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
        var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,];
        function lookupInUnicodeMap(code, map) {
            // Bail out quickly if it couldn't possibly be in the map.
            if (code < map[0]) {
                return false;
            }
            // Perform binary search in one of the Unicode range maps
            var lo = 0;
            var hi = map.length;
            var mid;
            while (lo + 1 < hi) {
                mid = lo + (hi - lo) / 2;
                // mid has to be even to catch a range's beginning
                mid -= mid % 2;
                if (map[mid] <= code && code <= map[mid + 1]) {
                    return true;
                }
                if (code < map[mid]) {
                    hi = mid;
                }
                else {
                    lo = mid + 2;
                }
            }
            return false;
        }
        /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
            return languageVersion >= 1 /* ES5 */ ?
                lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
                lookupInUnicodeMap(code, unicodeES3IdentifierStart);
        }
        ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
        function isUnicodeIdentifierPart(code, languageVersion) {
            return languageVersion >= 1 /* ES5 */ ?
                lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
                lookupInUnicodeMap(code, unicodeES3IdentifierPart);
        }
        function makeReverseMap(source) {
            var result = [];
            source.forEach(function (value, name) {
                result[value] = name;
            });
            return result;
        }
        var tokenStrings = makeReverseMap(textToToken);
        function tokenToString(t) {
            return tokenStrings[t];
        }
        ts.tokenToString = tokenToString;
        /* @internal */
        function stringToToken(s) {
            return textToToken.get(s);
        }
        ts.stringToToken = stringToToken;
        /* @internal */
        function computeLineStarts(text) {
            var result = new Array();
            var pos = 0;
            var lineStart = 0;
            while (pos < text.length) {
                var ch = text.charCodeAt(pos);
                pos++;
                switch (ch) {
                    case 13 /* carriageReturn */:
                        if (text.charCodeAt(pos) === 10 /* lineFeed */) {
                            pos++;
                        }
                    // falls through
                    case 10 /* lineFeed */:
                        result.push(lineStart);
                        lineStart = pos;
                        break;
                    default:
                        if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
                            result.push(lineStart);
                            lineStart = pos;
                        }
                        break;
                }
            }
            result.push(lineStart);
            return result;
        }
        ts.computeLineStarts = computeLineStarts;
        function getPositionOfLineAndCharacter(sourceFile, line, character) {
            return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text);
        }
        ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
        /* @internal */
        function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) {
            if (line < 0 || line >= lineStarts.length) {
                ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
            }
            var res = lineStarts[line] + character;
            if (line < lineStarts.length - 1) {
                ts.Debug.assert(res < lineStarts[line + 1]);
            }
            else if (debugText !== undefined) {
                ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
            }
            return res;
        }
        ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
        /* @internal */
        function getLineStarts(sourceFile) {
            return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
        }
        ts.getLineStarts = getLineStarts;
        /* @internal */
        /**
         * We assume the first line starts at position 0 and 'position' is non-negative.
         */
        function computeLineAndCharacterOfPosition(lineStarts, position) {
            var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues);
            if (lineNumber < 0) {
                // If the actual position was not found,
                // the binary search returns the 2's-complement of the next line start
                // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
                // then the search will return -2.
                //
                // We want the index of the previous line start, so we subtract 1.
                // Review 2's-complement if this is confusing.
                lineNumber = ~lineNumber - 1;
                ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
            }
            return {
                line: lineNumber,
                character: position - lineStarts[lineNumber]
            };
        }
        ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
        function getLineAndCharacterOfPosition(sourceFile, position) {
            return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
        }
        ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
        function isWhiteSpaceLike(ch) {
            return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
        }
        ts.isWhiteSpaceLike = isWhiteSpaceLike;
        /** Does not include line breaks. For that, see isWhiteSpaceLike. */
        function isWhiteSpaceSingleLine(ch) {
            // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
            // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
            return ch === 32 /* space */ ||
                ch === 9 /* tab */ ||
                ch === 11 /* verticalTab */ ||
                ch === 12 /* formFeed */ ||
                ch === 160 /* nonBreakingSpace */ ||
                ch === 133 /* nextLine */ ||
                ch === 5760 /* ogham */ ||
                ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
                ch === 8239 /* narrowNoBreakSpace */ ||
                ch === 8287 /* mathematicalSpace */ ||
                ch === 12288 /* ideographicSpace */ ||
                ch === 65279 /* byteOrderMark */;
        }
        ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
        function isLineBreak(ch) {
            // ES5 7.3:
            // The ECMAScript line terminator characters are listed in Table 3.
            //     Table 3: Line Terminator Characters
            //     Code Unit Value     Name                    Formal Name
            //     \u000A              Line Feed               <LF>
            //     \u000D              Carriage Return         <CR>
            //     \u2028              Line separator          <LS>
            //     \u2029              Paragraph separator     <PS>
            // Only the characters in Table 3 are treated as line terminators. Other new line or line
            // breaking characters are treated as white space but not as line terminators.
            return ch === 10 /* lineFeed */ ||
                ch === 13 /* carriageReturn */ ||
                ch === 8232 /* lineSeparator */ ||
                ch === 8233 /* paragraphSeparator */;
        }
        ts.isLineBreak = isLineBreak;
        function isDigit(ch) {
            return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
        }
        /* @internal */
        function isOctalDigit(ch) {
            return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
        }
        ts.isOctalDigit = isOctalDigit;
        function couldStartTrivia(text, pos) {
            // Keep in sync with skipTrivia
            var ch = text.charCodeAt(pos);
            switch (ch) {
                case 13 /* carriageReturn */:
                case 10 /* lineFeed */:
                case 9 /* tab */:
                case 11 /* verticalTab */:
                case 12 /* formFeed */:
                case 32 /* space */:
                case 47 /* slash */:
                // starts of normal trivia
                case 60 /* lessThan */:
                case 124 /* bar */:
                case 61 /* equals */:
                case 62 /* greaterThan */:
                    // Starts of conflict marker trivia
                    return true;
                case 35 /* hash */:
                    // Only if its the beginning can we have #! trivia
                    return pos === 0;
                default:
                    return ch > 127 /* maxAsciiCharacter */;
            }
        }
        ts.couldStartTrivia = couldStartTrivia;
        /* @internal */
        function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
            if (stopAtComments === void 0) {
                stopAtComments = false;
            }
            if (ts.positionIsSynthesized(pos)) {
                return pos;
            }
            // Keep in sync with couldStartTrivia
            while (true) {
                var ch = text.charCodeAt(pos);
                switch (ch) {
                    case 13 /* carriageReturn */:
                        if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
                            pos++;
                        }
                    // falls through
                    case 10 /* lineFeed */:
                        pos++;
                        if (stopAfterLineBreak) {
                            return pos;
                        }
                        continue;
                    case 9 /* tab */:
                    case 11 /* verticalTab */:
                    case 12 /* formFeed */:
                    case 32 /* space */:
                        pos++;
                        continue;
                    case 47 /* slash */:
                        if (stopAtComments) {
                            break;
                        }
                        if (text.charCodeAt(pos + 1) === 47 /* slash */) {
                            pos += 2;
                            while (pos < text.length) {
                                if (isLineBreak(text.charCodeAt(pos))) {
                                    break;
                                }
                                pos++;
                            }
                            continue;
                        }
                        if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
                            pos += 2;
                            while (pos < text.length) {
                                if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
                                    pos += 2;
                                    break;
                                }
                                pos++;
                            }
                            continue;
                        }
                        break;
                    case 60 /* lessThan */:
                    case 124 /* bar */:
                    case 61 /* equals */:
                    case 62 /* greaterThan */:
                        if (isConflictMarkerTrivia(text, pos)) {
                            pos = scanConflictMarkerTrivia(text, pos);
                            continue;
                        }
                        break;
                    case 35 /* hash */:
                        if (pos === 0 && isShebangTrivia(text, pos)) {
                            pos = scanShebangTrivia(text, pos);
                            continue;
                        }
                        break;
                    default:
                        if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
                            pos++;
                            continue;
                        }
                        break;
                }
                return pos;
            }
        }
        ts.skipTrivia = skipTrivia;
        // All conflict markers consist of the same character repeated seven times.  If it is
        // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
        var mergeConflictMarkerLength = "<<<<<<<".length;
        function isConflictMarkerTrivia(text, pos) {
            ts.Debug.assert(pos >= 0);
            // Conflict markers must be at the start of a line.
            if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
                var ch = text.charCodeAt(pos);
                if ((pos + mergeConflictMarkerLength) < text.length) {
                    for (var i = 0; i < mergeConflictMarkerLength; i++) {
                        if (text.charCodeAt(pos + i) !== ch) {
                            return false;
                        }
                    }
                    return ch === 61 /* equals */ ||
                        text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
                }
            }
            return false;
        }
        function scanConflictMarkerTrivia(text, pos, error) {
            if (error) {
                error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
            }
            var ch = text.charCodeAt(pos);
            var len = text.length;
            if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
                while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
                    pos++;
                }
            }
            else {
                ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
                // Consume everything from the start of a ||||||| or ======= marker to the start
                // of the next ======= or >>>>>>> marker.
                while (pos < len) {
                    var currentChar = text.charCodeAt(pos);
                    if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
                        break;
                    }
                    pos++;
                }
            }
            return pos;
        }
        var shebangTriviaRegex = /^#!.*/;
        function isShebangTrivia(text, pos) {
            // Shebangs check must only be done at the start of the file
            ts.Debug.assert(pos === 0);
            return shebangTriviaRegex.test(text);
        }
        function scanShebangTrivia(text, pos) {
            var shebang = shebangTriviaRegex.exec(text)[0];
            pos = pos + shebang.length;
            return pos;
        }
        /**
         * Invokes a callback for each comment range following the provided position.
         *
         * Single-line comment ranges include the leading double-slash characters but not the ending
         * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
         * asterisk-slash characters.
         *
         * @param reduce If true, accumulates the result of calling the callback in a fashion similar
         *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
         * @param text The source text to scan.
         * @param pos The position at which to start scanning.
         * @param trailing If false, whitespace is skipped until the first line break and comments
         *      between that location and the next token are returned. If true, comments occurring
         *      between the given position and the next line break are returned.
         * @param cb The callback to execute as each comment range is encountered.
         * @param state A state value to pass to each iteration of the callback.
         * @param initial An initial value to pass when accumulating results (when "reduce" is true).
         * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
         *      return value of the callback.
         */
        function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
            var pendingPos;
            var pendingEnd;
            var pendingKind;
            var pendingHasTrailingNewLine;
            var hasPendingCommentRange = false;
            var collecting = trailing || pos === 0;
            var accumulator = initial;
            scan: while (pos >= 0 && pos < text.length) {
                var ch = text.charCodeAt(pos);
                switch (ch) {
                    case 13 /* carriageReturn */:
                        if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
                            pos++;
                        }
                    // falls through
                    case 10 /* lineFeed */:
                        pos++;
                        if (trailing) {
                            break scan;
                        }
                        collecting = true;
                        if (hasPendingCommentRange) {
                            pendingHasTrailingNewLine = true;
                        }
                        continue;
                    case 9 /* tab */:
                    case 11 /* verticalTab */:
                    case 12 /* formFeed */:
                    case 32 /* space */:
                        pos++;
                        continue;
                    case 47 /* slash */:
                        var nextChar = text.charCodeAt(pos + 1);
                        var hasTrailingNewLine = false;
                        if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
                            var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
                            var startPos = pos;
                            pos += 2;
                            if (nextChar === 47 /* slash */) {
                                while (pos < text.length) {
                                    if (isLineBreak(text.charCodeAt(pos))) {
                                        hasTrailingNewLine = true;
                                        break;
                                    }
                                    pos++;
                                }
                            }
                            else {
                                while (pos < text.length) {
                                    if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
                                        pos += 2;
                                        break;
                                    }
                                    pos++;
                                }
                            }
                            if (collecting) {
                                if (hasPendingCommentRange) {
                                    accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
                                    if (!reduce && accumulator) {
                                        // If we are not reducing and we have a truthy result, return it.
                                        return accumulator;
                                    }
                                }
                                pendingPos = startPos;
                                pendingEnd = pos;
                                pendingKind = kind;
                                pendingHasTrailingNewLine = hasTrailingNewLine;
                                hasPendingCommentRange = true;
                            }
                            continue;
                        }
                        break scan;
                    default:
                        if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
                            if (hasPendingCommentRange && isLineBreak(ch)) {
                                pendingHasTrailingNewLine = true;
                            }
                            pos++;
                            continue;
                        }
                        break scan;
                }
            }
            if (hasPendingCommentRange) {
                accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
            }
            return accumulator;
        }
        function forEachLeadingCommentRange(text, pos, cb, state) {
            return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
        }
        ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
        function forEachTrailingCommentRange(text, pos, cb, state) {
            return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
        }
        ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
        function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
            return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
        }
        ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
        function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
            return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
        }
        ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
        function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
            if (!comments) {
                comments = [];
            }
            comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
            return comments;
        }
        function getLeadingCommentRanges(text, pos) {
            return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
        }
        ts.getLeadingCommentRanges = getLeadingCommentRanges;
        function getTrailingCommentRanges(text, pos) {
            return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
        }
        ts.getTrailingCommentRanges = getTrailingCommentRanges;
        /** Optionally, get the shebang */
        function getShebang(text) {
            var match = shebangTriviaRegex.exec(text);
            if (match) {
                return match[0];
            }
        }
        ts.getShebang = getShebang;
        function isIdentifierStart(ch, languageVersion) {
            return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
                ch === 36 /* $ */ || ch === 95 /* _ */ ||
                ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
        }
        ts.isIdentifierStart = isIdentifierStart;
        function isIdentifierPart(ch, languageVersion) {
            return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
                ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
                ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
        }
        ts.isIdentifierPart = isIdentifierPart;
        /* @internal */
        function isIdentifierText(name, languageVersion) {
            if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
                return false;
            }
            for (var i = 1; i < name.length; i++) {
                if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) {
                    return false;
                }
            }
            return true;
        }
        ts.isIdentifierText = isIdentifierText;
        // Creates a scanner over a (possibly unspecified) range of a piece of text.
        function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
            if (languageVariant === void 0) {
                languageVariant = 0 /* Standard */;
            }
            var text = textInitial;
            // Current position (end position of text of current token)
            var pos;
            // end of text
            var end;
            // Start position of whitespace before current token
            var startPos;
            // Start position of text of current token
            var tokenPos;
            var token;
            var tokenValue;
            var tokenFlags;
            var inJSDocType = 0;
            setText(text, start, length);
            return {
                getStartPos: function () { return startPos; },
                getTextPos: function () { return pos; },
                getToken: function () { return token; },
                getTokenPos: function () { return tokenPos; },
                getTokenText: function () { return text.substring(tokenPos, pos); },
                getTokenValue: function () { return tokenValue; },
                hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
                hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
                isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; },
                isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; },
                isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
                getTokenFlags: function () { return tokenFlags; },
                reScanGreaterToken: reScanGreaterToken,
                reScanSlashToken: reScanSlashToken,
                reScanTemplateToken: reScanTemplateToken,
                scanJsxIdentifier: scanJsxIdentifier,
                scanJsxAttributeValue: scanJsxAttributeValue,
                reScanJsxToken: reScanJsxToken,
                scanJsxToken: scanJsxToken,
                scanJSDocToken: scanJSDocToken,
                scan: scan,
                getText: getText,
                setText: setText,
                setScriptTarget: setScriptTarget,
                setLanguageVariant: setLanguageVariant,
                setOnError: setOnError,
                setTextPos: setTextPos,
                setInJSDocType: setInJSDocType,
                tryScan: tryScan,
                lookAhead: lookAhead,
                scanRange: scanRange,
            };
            function error(message, errPos, length) {
                if (errPos === void 0) {
                    errPos = pos;
                }
                if (onError) {
                    var oldPos = pos;
                    pos = errPos;
                    onError(message, length || 0);
                    pos = oldPos;
                }
            }
            function scanNumberFragment() {
                var start = pos;
                var allowSeparator = false;
                var isPreviousTokenSeparator = false;
                var result = "";
                while (true) {
                    var ch = text.charCodeAt(pos);
                    if (ch === 95 /* _ */) {
                        tokenFlags |= 512 /* ContainsSeparator */;
                        if (allowSeparator) {
                            allowSeparator = false;
                            isPreviousTokenSeparator = true;
                            result += text.substring(start, pos);
                        }
                        else if (isPreviousTokenSeparator) {
                            error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
                        }
                        else {
                            error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
                        }
                        pos++;
                        start = pos;
                        continue;
                    }
                    if (isDigit(ch)) {
                        allowSeparator = true;
                        isPreviousTokenSeparator = false;
                        pos++;
                        continue;
                    }
                    break;
                }
                if (text.charCodeAt(pos - 1) === 95 /* _ */) {
                    error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
                }
                return result + text.substring(start, pos);
            }
            function scanNumber() {
                var start = pos;
                var mainFragment = scanNumberFragment();
                var decimalFragment;
                var scientificFragment;
                if (text.charCodeAt(pos) === 46 /* dot */) {
                    pos++;
                    decimalFragment = scanNumberFragment();
                }
                var end = pos;
                if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
                    pos++;
                    tokenFlags |= 16 /* Scientific */;
                    if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
                        pos++;
                    var preNumericPart = pos;
                    var finalFragment = scanNumberFragment();
                    if (!finalFragment) {
                        error(ts.Diagnostics.Digit_expected);
                    }
                    else {
                        scientificFragment = text.substring(end, preNumericPart) + finalFragment;
                        end = pos;
                    }
                }
                if (tokenFlags & 512 /* ContainsSeparator */) {
                    var result = mainFragment;
                    if (decimalFragment) {
                        result += "." + decimalFragment;
                    }
                    if (scientificFragment) {
                        result += scientificFragment;
                    }
                    return "" + +result;
                }
                else {
                    return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed
                }
            }
            function scanOctalDigits() {
                var start = pos;
                while (isOctalDigit(text.charCodeAt(pos))) {
                    pos++;
                }
                return +(text.substring(start, pos));
            }
            /**
             * Scans the given number of hexadecimal digits in the text,
             * returning -1 if the given number is unavailable.
             */
            function scanExactNumberOfHexDigits(count, canHaveSeparators) {
                return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
            }
            /**
             * Scans as many hexadecimal digits as are available in the text,
             * returning -1 if the given number of digits was unavailable.
             */
            function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
                return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
            }
            function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
                var digits = 0;
                var value = 0;
                var allowSeparator = false;
                var isPreviousTokenSeparator = false;
                while (digits < minCount || scanAsManyAsPossible) {
                    var ch = text.charCodeAt(pos);
                    if (canHaveSeparators && ch === 95 /* _ */) {
                        tokenFlags |= 512 /* ContainsSeparator */;
                        if (allowSeparator) {
                            allowSeparator = false;
                            isPreviousTokenSeparator = true;
                        }
                        else if (isPreviousTokenSeparator) {
                            error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
                        }
                        else {
                            error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
                        }
                        pos++;
                        continue;
                    }
                    allowSeparator = canHaveSeparators;
                    if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
                        value = value * 16 + ch - 48 /* _0 */;
                    }
                    else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
                        value = value * 16 + ch - 65 /* A */ + 10;
                    }
                    else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
                        value = value * 16 + ch - 97 /* a */ + 10;
                    }
                    else {
                        break;
                    }
                    pos++;
                    digits++;
                    isPreviousTokenSeparator = false;
                }
                if (digits < minCount) {
                    value = -1;
                }
                if (text.charCodeAt(pos - 1) === 95 /* _ */) {
                    error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
                }
                return value;
            }
            function scanString(jsxAttributeString) {
                if (jsxAttributeString === void 0) {
                    jsxAttributeString = false;
                }
                var quote = text.charCodeAt(pos);
                pos++;
                var result = "";
                var start = pos;
                while (true) {
                    if (pos >= end) {
                        result += text.substring(start, pos);
                        tokenFlags |= 4 /* Unterminated */;
                        error(ts.Diagnostics.Unterminated_string_literal);
                        break;
                    }
                    var ch = text.charCodeAt(pos);
                    if (ch === quote) {
                        result += text.substring(start, pos);
                        pos++;
                        break;
                    }
                    if (ch === 92 /* backslash */ && !jsxAttributeString) {
                        result += text.substring(start, pos);
                        result += scanEscapeSequence();
                        start = pos;
                        continue;
                    }
                    if (isLineBreak(ch) && !jsxAttributeString) {
                        result += text.substring(start, pos);
                        tokenFlags |= 4 /* Unterminated */;
                        error(ts.Diagnostics.Unterminated_string_literal);
                        break;
                    }
                    pos++;
                }
                return result;
            }
            /**
             * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
             * a literal component of a TemplateExpression.
             */
            function scanTemplateAndSetTokenValue() {
                var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
                pos++;
                var start = pos;
                var contents = "";
                var resultingToken;
                while (true) {
                    if (pos >= end) {
                        contents += text.substring(start, pos);
                        tokenFlags |= 4 /* Unterminated */;
                        error(ts.Diagnostics.Unterminated_template_literal);
                        resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */;
                        break;
                    }
                    var currChar = text.charCodeAt(pos);
                    // '`'
                    if (currChar === 96 /* backtick */) {
                        contents += text.substring(start, pos);
                        pos++;
                        resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */;
                        break;
                    }
                    // '${'
                    if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
                        contents += text.substring(start, pos);
                        pos += 2;
                        resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */;
                        break;
                    }
                    // Escape character
                    if (currChar === 92 /* backslash */) {
                        contents += text.substring(start, pos);
                        contents += scanEscapeSequence();
                        start = pos;
                        continue;
                    }
                    // Speculated ECMAScript 6 Spec 11.8.6.1:
                    // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
                    if (currChar === 13 /* carriageReturn */) {
                        contents += text.substring(start, pos);
                        pos++;
                        if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
                            pos++;
                        }
                        contents += "\n";
                        start = pos;
                        continue;
                    }
                    pos++;
                }
                ts.Debug.assert(resultingToken !== undefined);
                tokenValue = contents;
                return resultingToken;
            }
            function scanEscapeSequence() {
                pos++;
                if (pos >= end) {
                    error(ts.Diagnostics.Unexpected_end_of_text);
                    return "";
                }
                var ch = text.charCodeAt(pos);
                pos++;
                switch (ch) {
                    case 48 /* _0 */:
                        return "\0";
                    case 98 /* b */:
                        return "\b";
                    case 116 /* t */:
                        return "\t";
                    case 110 /* n */:
                        return "\n";
                    case 118 /* v */:
                        return "\v";
                    case 102 /* f */:
                        return "\f";
                    case 114 /* r */:
                        return "\r";
                    case 39 /* singleQuote */:
                        return "\'";
                    case 34 /* doubleQuote */:
                        return "\"";
                    case 117 /* u */:
                        // '\u{DDDDDDDD}'
                        if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
                            tokenFlags |= 8 /* ExtendedUnicodeEscape */;
                            pos++;
                            return scanExtendedUnicodeEscape();
                        }
                        // '\uDDDD'
                        return scanHexadecimalEscape(/*numDigits*/ 4);
                    case 120 /* x */:
                        // '\xDD'
                        return scanHexadecimalEscape(/*numDigits*/ 2);
                    // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
                    // the line terminator is interpreted to be "the empty code unit sequence".
                    case 13 /* carriageReturn */:
                        if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
                            pos++;
                        }
                    // falls through
                    case 10 /* lineFeed */:
                    case 8232 /* lineSeparator */:
                    case 8233 /* paragraphSeparator */:
                        return "";
                    default:
                        return String.fromCharCode(ch);
                }
            }
            function scanHexadecimalEscape(numDigits) {
                var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
                if (escapedValue >= 0) {
                    return String.fromCharCode(escapedValue);
                }
                else {
                    error(ts.Diagnostics.Hexadecimal_digit_expected);
                    return "";
                }
            }
            function scanExtendedUnicodeEscape() {
                var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
                var isInvalidExtendedEscape = false;
                // Validate the value of the digit
                if (escapedValue < 0) {
                    error(ts.Diagnostics.Hexadecimal_digit_expected);
                    isInvalidExtendedEscape = true;
                }
                else if (escapedValue > 0x10FFFF) {
                    error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
                    isInvalidExtendedEscape = true;
                }
                if (pos >= end) {
                    error(ts.Diagnostics.Unexpected_end_of_text);
                    isInvalidExtendedEscape = true;
                }
                else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
                    // Only swallow the following character up if it's a '}'.
                    pos++;
                }
                else {
                    error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
                    isInvalidExtendedEscape = true;
                }
                if (isInvalidExtendedEscape) {
                    return "";
                }
                return utf16EncodeAsString(escapedValue);
            }
            // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
            function utf16EncodeAsString(codePoint) {
                ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
                if (codePoint <= 65535) {
                    return String.fromCharCode(codePoint);
                }
                var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
                var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
                return String.fromCharCode(codeUnit1, codeUnit2);
            }
            // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
            // and return code point value if valid Unicode escape is found. Otherwise return -1.
            function peekUnicodeEscape() {
                if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
                    var start_1 = pos;
                    pos += 2;
                    var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
                    pos = start_1;
                    return value;
                }
                return -1;
            }
            function scanIdentifierParts() {
                var result = "";
                var start = pos;
                while (pos < end) {
                    var ch = text.charCodeAt(pos);
                    if (isIdentifierPart(ch, languageVersion)) {
                        pos++;
                    }
                    else if (ch === 92 /* backslash */) {
                        ch = peekUnicodeEscape();
                        if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
                            break;
                        }
                        result += text.substring(start, pos);
                        result += String.fromCharCode(ch);
                        // Valid Unicode escape is always six characters
                        pos += 6;
                        start = pos;
                    }
                    else {
                        break;
                    }
                }
                result += text.substring(start, pos);
                return result;
            }
            function getIdentifierToken() {
                // Reserved words are between 2 and 11 characters long and start with a lowercase letter
                var len = tokenValue.length;
                if (len >= 2 && len <= 11) {
                    var ch = tokenValue.charCodeAt(0);
                    if (ch >= 97 /* a */ && ch <= 122 /* z */) {
                        var keyword = textToKeyword.get(tokenValue);
                        if (keyword !== undefined) {
                            return token = keyword;
                        }
                    }
                }
                return token = 71 /* Identifier */;
            }
            function scanBinaryOrOctalDigits(base) {
                ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8");
                var value = 0;
                // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
                // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
                var numberOfDigits = 0;
                var separatorAllowed = false;
                var isPreviousTokenSeparator = false;
                while (true) {
                    var ch = text.charCodeAt(pos);
                    // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
                    if (ch === 95 /* _ */) {
                        tokenFlags |= 512 /* ContainsSeparator */;
                        if (separatorAllowed) {
                            separatorAllowed = false;
                            isPreviousTokenSeparator = true;
                        }
                        else if (isPreviousTokenSeparator) {
                            error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
                        }
                        else {
                            error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
                        }
                        pos++;
                        continue;
                    }
                    separatorAllowed = true;
                    var valueOfCh = ch - 48 /* _0 */;
                    if (!isDigit(ch) || valueOfCh >= base) {
                        break;
                    }
                    value = value * base + valueOfCh;
                    pos++;
                    numberOfDigits++;
                    isPreviousTokenSeparator = false;
                }
                // Invalid binaryIntegerLiteral or octalIntegerLiteral
                if (numberOfDigits === 0) {
                    return -1;
                }
                if (text.charCodeAt(pos - 1) === 95 /* _ */) {
                    // Literal ends with underscore - not allowed
                    error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
                    return value;
                }
                return value;
            }
            function scan() {
                startPos = pos;
                tokenFlags = 0;
                var asteriskSeen = false;
                while (true) {
                    tokenPos = pos;
                    if (pos >= end) {
                        return token = 1 /* EndOfFileToken */;
                    }
                    var ch = text.charCodeAt(pos);
                    // Special handling for shebang
                    if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
                        pos = scanShebangTrivia(text, pos);
                        if (skipTrivia) {
                            continue;
                        }
                        else {
                            return token = 6 /* ShebangTrivia */;
                        }
                    }
                    switch (ch) {
                        case 10 /* lineFeed */:
                        case 13 /* carriageReturn */:
                            tokenFlags |= 1 /* PrecedingLineBreak */;
                            if (skipTrivia) {
                                pos++;
                                continue;
                            }
                            else {
                                if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
                                    // consume both CR and LF
                                    pos += 2;
                                }
                                else {
                                    pos++;
                                }
                                return token = 4 /* NewLineTrivia */;
                            }
                        case 9 /* tab */:
                        case 11 /* verticalTab */:
                        case 12 /* formFeed */:
                        case 32 /* space */:
                        case 160 /* nonBreakingSpace */:
                        case 5760 /* ogham */:
                        case 8192 /* enQuad */:
                        case 8193 /* emQuad */:
                        case 8194 /* enSpace */:
                        case 8195 /* emSpace */:
                        case 8196 /* threePerEmSpace */:
                        case 8197 /* fourPerEmSpace */:
                        case 8198 /* sixPerEmSpace */:
                        case 8199 /* figureSpace */:
                        case 8200 /* punctuationSpace */:
                        case 8201 /* thinSpace */:
                        case 8202 /* hairSpace */:
                        case 8203 /* zeroWidthSpace */:
                        case 8239 /* narrowNoBreakSpace */:
                        case 8287 /* mathematicalSpace */:
                        case 12288 /* ideographicSpace */:
                        case 65279 /* byteOrderMark */:
                            if (skipTrivia) {
                                pos++;
                                continue;
                            }
                            else {
                                while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
                                    pos++;
                                }
                                return token = 5 /* WhitespaceTrivia */;
                            }
                        case 33 /* exclamation */:
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                if (text.charCodeAt(pos + 2) === 61 /* equals */) {
                                    return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */;
                                }
                                return pos += 2, token = 33 /* ExclamationEqualsToken */;
                            }
                            pos++;
                            return token = 51 /* ExclamationToken */;
                        case 34 /* doubleQuote */:
                        case 39 /* singleQuote */:
                            tokenValue = scanString();
                            return token = 9 /* StringLiteral */;
                        case 96 /* backtick */:
                            return token = scanTemplateAndSetTokenValue();
                        case 37 /* percent */:
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 64 /* PercentEqualsToken */;
                            }
                            pos++;
                            return token = 42 /* PercentToken */;
                        case 38 /* ampersand */:
                            if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
                                return pos += 2, token = 53 /* AmpersandAmpersandToken */;
                            }
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 68 /* AmpersandEqualsToken */;
                            }
                            pos++;
                            return token = 48 /* AmpersandToken */;
                        case 40 /* openParen */:
                            pos++;
                            return token = 19 /* OpenParenToken */;
                        case 41 /* closeParen */:
                            pos++;
                            return token = 20 /* CloseParenToken */;
                        case 42 /* asterisk */:
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 61 /* AsteriskEqualsToken */;
                            }
                            if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
                                if (text.charCodeAt(pos + 2) === 61 /* equals */) {
                                    return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */;
                                }
                                return pos += 2, token = 40 /* AsteriskAsteriskToken */;
                            }
                            pos++;
                            if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
                                // decoration at the start of a JSDoc comment line
                                asteriskSeen = true;
                                continue;
                            }
                            return token = 39 /* AsteriskToken */;
                        case 43 /* plus */:
                            if (text.charCodeAt(pos + 1) === 43 /* plus */) {
                                return pos += 2, token = 43 /* PlusPlusToken */;
                            }
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 59 /* PlusEqualsToken */;
                            }
                            pos++;
                            return token = 37 /* PlusToken */;
                        case 44 /* comma */:
                            pos++;
                            return token = 26 /* CommaToken */;
                        case 45 /* minus */:
                            if (text.charCodeAt(pos + 1) === 45 /* minus */) {
                                return pos += 2, token = 44 /* MinusMinusToken */;
                            }
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 60 /* MinusEqualsToken */;
                            }
                            pos++;
                            return token = 38 /* MinusToken */;
                        case 46 /* dot */:
                            if (isDigit(text.charCodeAt(pos + 1))) {
                                tokenValue = scanNumber();
                                return token = 8 /* NumericLiteral */;
                            }
                            if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
                                return pos += 3, token = 24 /* DotDotDotToken */;
                            }
                            pos++;
                            return token = 23 /* DotToken */;
                        case 47 /* slash */:
                            // Single-line comment
                            if (text.charCodeAt(pos + 1) === 47 /* slash */) {
                                pos += 2;
                                while (pos < end) {
                                    if (isLineBreak(text.charCodeAt(pos))) {
                                        break;
                                    }
                                    pos++;
                                }
                                if (skipTrivia) {
                                    continue;
                                }
                                else {
                                    return token = 2 /* SingleLineCommentTrivia */;
                                }
                            }
                            // Multi-line comment
                            if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
                                pos += 2;
                                if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
                                    tokenFlags |= 2 /* PrecedingJSDocComment */;
                                }
                                var commentClosed = false;
                                while (pos < end) {
                                    var ch_1 = text.charCodeAt(pos);
                                    if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
                                        pos += 2;
                                        commentClosed = true;
                                        break;
                                    }
                                    if (isLineBreak(ch_1)) {
                                        tokenFlags |= 1 /* PrecedingLineBreak */;
                                    }
                                    pos++;
                                }
                                if (!commentClosed) {
                                    error(ts.Diagnostics.Asterisk_Slash_expected);
                                }
                                if (skipTrivia) {
                                    continue;
                                }
                                else {
                                    if (!commentClosed) {
                                        tokenFlags |= 4 /* Unterminated */;
                                    }
                                    return token = 3 /* MultiLineCommentTrivia */;
                                }
                            }
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 63 /* SlashEqualsToken */;
                            }
                            pos++;
                            return token = 41 /* SlashToken */;
                        case 48 /* _0 */:
                            if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
                                pos += 2;
                                var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
                                if (value < 0) {
                                    error(ts.Diagnostics.Hexadecimal_digit_expected);
                                    value = 0;
                                }
                                tokenValue = "" + value;
                                tokenFlags |= 64 /* HexSpecifier */;
                                return token = 8 /* NumericLiteral */;
                            }
                            else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
                                pos += 2;
                                var value = scanBinaryOrOctalDigits(/* base */ 2);
                                if (value < 0) {
                                    error(ts.Diagnostics.Binary_digit_expected);
                                    value = 0;
                                }
                                tokenValue = "" + value;
                                tokenFlags |= 128 /* BinarySpecifier */;
                                return token = 8 /* NumericLiteral */;
                            }
                            else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
                                pos += 2;
                                var value = scanBinaryOrOctalDigits(/* base */ 8);
                                if (value < 0) {
                                    error(ts.Diagnostics.Octal_digit_expected);
                                    value = 0;
                                }
                                tokenValue = "" + value;
                                tokenFlags |= 256 /* OctalSpecifier */;
                                return token = 8 /* NumericLiteral */;
                            }
                            // Try to parse as an octal
                            if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
                                tokenValue = "" + scanOctalDigits();
                                tokenFlags |= 32 /* Octal */;
                                return token = 8 /* NumericLiteral */;
                            }
                        // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
                        // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
                        // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
                        // falls through
                        case 49 /* _1 */:
                        case 50 /* _2 */:
                        case 51 /* _3 */:
                        case 52 /* _4 */:
                        case 53 /* _5 */:
                        case 54 /* _6 */:
                        case 55 /* _7 */:
                        case 56 /* _8 */:
                        case 57 /* _9 */:
                            tokenValue = scanNumber();
                            return token = 8 /* NumericLiteral */;
                        case 58 /* colon */:
                            pos++;
                            return token = 56 /* ColonToken */;
                        case 59 /* semicolon */:
                            pos++;
                            return token = 25 /* SemicolonToken */;
                        case 60 /* lessThan */:
                            if (isConflictMarkerTrivia(text, pos)) {
                                pos = scanConflictMarkerTrivia(text, pos, error);
                                if (skipTrivia) {
                                    continue;
                                }
                                else {
                                    return token = 7 /* ConflictMarkerTrivia */;
                                }
                            }
                            if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
                                if (text.charCodeAt(pos + 2) === 61 /* equals */) {
                                    return pos += 3, token = 65 /* LessThanLessThanEqualsToken */;
                                }
                                return pos += 2, token = 45 /* LessThanLessThanToken */;
                            }
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 30 /* LessThanEqualsToken */;
                            }
                            if (languageVariant === 1 /* JSX */ &&
                                text.charCodeAt(pos + 1) === 47 /* slash */ &&
                                text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
                                return pos += 2, token = 28 /* LessThanSlashToken */;
                            }
                            pos++;
                            return token = 27 /* LessThanToken */;
                        case 61 /* equals */:
                            if (isConflictMarkerTrivia(text, pos)) {
                                pos = scanConflictMarkerTrivia(text, pos, error);
                                if (skipTrivia) {
                                    continue;
                                }
                                else {
                                    return token = 7 /* ConflictMarkerTrivia */;
                                }
                            }
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                if (text.charCodeAt(pos + 2) === 61 /* equals */) {
                                    return pos += 3, token = 34 /* EqualsEqualsEqualsToken */;
                                }
                                return pos += 2, token = 32 /* EqualsEqualsToken */;
                            }
                            if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
                                return pos += 2, token = 36 /* EqualsGreaterThanToken */;
                            }
                            pos++;
                            return token = 58 /* EqualsToken */;
                        case 62 /* greaterThan */:
                            if (isConflictMarkerTrivia(text, pos)) {
                                pos = scanConflictMarkerTrivia(text, pos, error);
                                if (skipTrivia) {
                                    continue;
                                }
                                else {
                                    return token = 7 /* ConflictMarkerTrivia */;
                                }
                            }
                            pos++;
                            return token = 29 /* GreaterThanToken */;
                        case 63 /* question */:
                            pos++;
                            return token = 55 /* QuestionToken */;
                        case 91 /* openBracket */:
                            pos++;
                            return token = 21 /* OpenBracketToken */;
                        case 93 /* closeBracket */:
                            pos++;
                            return token = 22 /* CloseBracketToken */;
                        case 94 /* caret */:
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 70 /* CaretEqualsToken */;
                            }
                            pos++;
                            return token = 50 /* CaretToken */;
                        case 123 /* openBrace */:
                            pos++;
                            return token = 17 /* OpenBraceToken */;
                        case 124 /* bar */:
                            if (isConflictMarkerTrivia(text, pos)) {
                                pos = scanConflictMarkerTrivia(text, pos, error);
                                if (skipTrivia) {
                                    continue;
                                }
                                else {
                                    return token = 7 /* ConflictMarkerTrivia */;
                                }
                            }
                            if (text.charCodeAt(pos + 1) === 124 /* bar */) {
                                return pos += 2, token = 54 /* BarBarToken */;
                            }
                            if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                                return pos += 2, token = 69 /* BarEqualsToken */;
                            }
                            pos++;
                            return token = 49 /* BarToken */;
                        case 125 /* closeBrace */:
                            pos++;
                            return token = 18 /* CloseBraceToken */;
                        case 126 /* tilde */:
                            pos++;
                            return token = 52 /* TildeToken */;
                        case 64 /* at */:
                            pos++;
                            return token = 57 /* AtToken */;
                        case 92 /* backslash */:
                            var cookedChar = peekUnicodeEscape();
                            if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
                                pos += 6;
                                tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
                                return token = getIdentifierToken();
                            }
                            error(ts.Diagnostics.Invalid_character);
                            pos++;
                            return token = 0 /* Unknown */;
                        default:
                            if (isIdentifierStart(ch, languageVersion)) {
                                pos++;
                                while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
                                    pos++;
                                tokenValue = text.substring(tokenPos, pos);
                                if (ch === 92 /* backslash */) {
                                    tokenValue += scanIdentifierParts();
                                }
                                return token = getIdentifierToken();
                            }
                            else if (isWhiteSpaceSingleLine(ch)) {
                                pos++;
                                continue;
                            }
                            else if (isLineBreak(ch)) {
                                tokenFlags |= 1 /* PrecedingLineBreak */;
                                pos++;
                                continue;
                            }
                            error(ts.Diagnostics.Invalid_character);
                            pos++;
                            return token = 0 /* Unknown */;
                    }
                }
            }
            function reScanGreaterToken() {
                if (token === 29 /* GreaterThanToken */) {
                    if (text.charCodeAt(pos) === 62 /* greaterThan */) {
                        if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
                            if (text.charCodeAt(pos + 2) === 61 /* equals */) {
                                return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
                            }
                            return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */;
                        }
                        if (text.charCodeAt(pos + 1) === 61 /* equals */) {
                            return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */;
                        }
                        pos++;
                        return token = 46 /* GreaterThanGreaterThanToken */;
                    }
                    if (text.charCodeAt(pos) === 61 /* equals */) {
                        pos++;
                        return token = 31 /* GreaterThanEqualsToken */;
                    }
                }
                return token;
            }
            function reScanSlashToken() {
                if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) {
                    var p = tokenPos + 1;
                    var inEscape = false;
                    var inCharacterClass = false;
                    while (true) {
                        // If we reach the end of a file, or hit a newline, then this is an unterminated
                        // regex.  Report error and return what we have so far.
                        if (p >= end) {
                            tokenFlags |= 4 /* Unterminated */;
                            error(ts.Diagnostics.Unterminated_regular_expression_literal);
                            break;
                        }
                        var ch = text.charCodeAt(p);
                        if (isLineBreak(ch)) {
                            tokenFlags |= 4 /* Unterminated */;
                            error(ts.Diagnostics.Unterminated_regular_expression_literal);
                            break;
                        }
                        if (inEscape) {
                            // Parsing an escape character;
                            // reset the flag and just advance to the next char.
                            inEscape = false;
                        }
                        else if (ch === 47 /* slash */ && !inCharacterClass) {
                            // A slash within a character class is permissible,
                            // but in general it signals the end of the regexp literal.
                            p++;
                            break;
                        }
                        else if (ch === 91 /* openBracket */) {
                            inCharacterClass = true;
                        }
                        else if (ch === 92 /* backslash */) {
                            inEscape = true;
                        }
                        else if (ch === 93 /* closeBracket */) {
                            inCharacterClass = false;
                        }
                        p++;
                    }
                    while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
                        p++;
                    }
                    pos = p;
                    tokenValue = text.substring(tokenPos, pos);
                    token = 12 /* RegularExpressionLiteral */;
                }
                return token;
            }
            /**
             * Unconditionally back up and scan a template expression portion.
             */
            function reScanTemplateToken() {
                ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
                pos = tokenPos;
                return token = scanTemplateAndSetTokenValue();
            }
            function reScanJsxToken() {
                pos = tokenPos = startPos;
                return token = scanJsxToken();
            }
            function scanJsxToken() {
                startPos = tokenPos = pos;
                if (pos >= end) {
                    return token = 1 /* EndOfFileToken */;
                }
                var char = text.charCodeAt(pos);
                if (char === 60 /* lessThan */) {
                    if (text.charCodeAt(pos + 1) === 47 /* slash */) {
                        pos += 2;
                        return token = 28 /* LessThanSlashToken */;
                    }
                    pos++;
                    return token = 27 /* LessThanToken */;
                }
                if (char === 123 /* openBrace */) {
                    pos++;
                    return token = 17 /* OpenBraceToken */;
                }
                // First non-whitespace character on this line.
                var firstNonWhitespace = 0;
                // These initial values are special because the first line is:
                // firstNonWhitespace = 0 to indicate that we want leading whitspace,
                while (pos < end) {
                    char = text.charCodeAt(pos);
                    if (char === 123 /* openBrace */) {
                        break;
                    }
                    if (char === 60 /* lessThan */) {
                        if (isConflictMarkerTrivia(text, pos)) {
                            pos = scanConflictMarkerTrivia(text, pos, error);
                            return token = 7 /* ConflictMarkerTrivia */;
                        }
                        break;
                    }
                    // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
                    // i.e (- : whitespace)
                    //      <div>----
                    //      </div> becomes <div></div>
                    //
                    //      <div>----</div> becomes <div>----</div>
                    if (isLineBreak(char) && firstNonWhitespace === 0) {
                        firstNonWhitespace = -1;
                    }
                    else if (!isWhiteSpaceLike(char)) {
                        firstNonWhitespace = pos;
                    }
                    pos++;
                }
                return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */;
            }
            // Scans a JSX identifier; these differ from normal identifiers in that
            // they allow dashes
            function scanJsxIdentifier() {
                if (tokenIsIdentifierOrKeyword(token)) {
                    var firstCharPosition = pos;
                    while (pos < end) {
                        var ch = text.charCodeAt(pos);
                        if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {
                            pos++;
                        }
                        else {
                            break;
                        }
                    }
                    tokenValue += text.substring(firstCharPosition, pos);
                }
                return token;
            }
            function scanJsxAttributeValue() {
                startPos = pos;
                switch (text.charCodeAt(pos)) {
                    case 34 /* doubleQuote */:
                    case 39 /* singleQuote */:
                        tokenValue = scanString(/*jsxAttributeString*/ true);
                        return token = 9 /* StringLiteral */;
                    default:
                        // If this scans anything other than `{`, it's a parse error.
                        return scan();
                }
            }
            function scanJSDocToken() {
                startPos = tokenPos = pos;
                tokenFlags = 0;
                if (pos >= end) {
                    return token = 1 /* EndOfFileToken */;
                }
                var ch = text.charCodeAt(pos);
                pos++;
                switch (ch) {
                    case 9 /* tab */:
                    case 11 /* verticalTab */:
                    case 12 /* formFeed */:
                    case 32 /* space */:
                        while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
                            pos++;
                        }
                        return token = 5 /* WhitespaceTrivia */;
                    case 64 /* at */:
                        return token = 57 /* AtToken */;
                    case 10 /* lineFeed */:
                    case 13 /* carriageReturn */:
                        tokenFlags |= 1 /* PrecedingLineBreak */;
                        return token = 4 /* NewLineTrivia */;
                    case 42 /* asterisk */:
                        return token = 39 /* AsteriskToken */;
                    case 123 /* openBrace */:
                        return token = 17 /* OpenBraceToken */;
                    case 125 /* closeBrace */:
                        return token = 18 /* CloseBraceToken */;
                    case 91 /* openBracket */:
                        return token = 21 /* OpenBracketToken */;
                    case 93 /* closeBracket */:
                        return token = 22 /* CloseBracketToken */;
                    case 60 /* lessThan */:
                        return token = 27 /* LessThanToken */;
                    case 61 /* equals */:
                        return token = 58 /* EqualsToken */;
                    case 44 /* comma */:
                        return token = 26 /* CommaToken */;
                    case 46 /* dot */:
                        return token = 23 /* DotToken */;
                    case 96 /* backtick */:
                        while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) {
                            pos++;
                        }
                        tokenValue = text.substring(tokenPos + 1, pos);
                        pos++;
                        return token = 13 /* NoSubstitutionTemplateLiteral */;
                }
                if (isIdentifierStart(ch, 6 /* Latest */)) {
                    while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
                        pos++;
                    }
                    tokenValue = text.substring(tokenPos, pos);
                    return token = getIdentifierToken();
                }
                else {
                    return token = 0 /* Unknown */;
                }
            }
            function speculationHelper(callback, isLookahead) {
                var savePos = pos;
                var saveStartPos = startPos;
                var saveTokenPos = tokenPos;
                var saveToken = token;
                var saveTokenValue = tokenValue;
                var saveTokenFlags = tokenFlags;
                var result = callback();
                // If our callback returned something 'falsy' or we're just looking ahead,
                // then unconditionally restore us to where we were.
                if (!result || isLookahead) {
                    pos = savePos;
                    startPos = saveStartPos;
                    tokenPos = saveTokenPos;
                    token = saveToken;
                    tokenValue = saveTokenValue;
                    tokenFlags = saveTokenFlags;
                }
                return result;
            }
            function scanRange(start, length, callback) {
                var saveEnd = end;
                var savePos = pos;
                var saveStartPos = startPos;
                var saveTokenPos = tokenPos;
                var saveToken = token;
                var saveTokenValue = tokenValue;
                var saveTokenFlags = tokenFlags;
                setText(text, start, length);
                var result = callback();
                end = saveEnd;
                pos = savePos;
                startPos = saveStartPos;
                tokenPos = saveTokenPos;
                token = saveToken;
                tokenValue = saveTokenValue;
                tokenFlags = saveTokenFlags;
                return result;
            }
            function lookAhead(callback) {
                return speculationHelper(callback, /*isLookahead*/ true);
            }
            function tryScan(callback) {
                return speculationHelper(callback, /*isLookahead*/ false);
            }
            function getText() {
                return text;
            }
            function setText(newText, start, length) {
                text = newText || "";
                end = length === undefined ? text.length : start + length;
                setTextPos(start || 0);
            }
            function setOnError(errorCallback) {
                onError = errorCallback;
            }
            function setScriptTarget(scriptTarget) {
                languageVersion = scriptTarget;
            }
            function setLanguageVariant(variant) {
                languageVariant = variant;
            }
            function setTextPos(textPos) {
                ts.Debug.assert(textPos >= 0);
                pos = textPos;
                startPos = textPos;
                tokenPos = textPos;
                token = 0 /* Unknown */;
                tokenValue = undefined;
                tokenFlags = 0;
            }
            function setInJSDocType(inType) {
                inJSDocType += inType ? 1 : -1;
            }
        }
        ts.createScanner = createScanner;
    })(ts || (ts = {}));
    /** Non-internal stuff goes here */
    var ts;
    (function (ts) {
        function isExternalModuleNameRelative(moduleName) {
            // TypeScript 1.0 spec (April 2014): 11.2.1
            // An external module name is "relative" if the first term is "." or "..".
            // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module.
            return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
        }
        ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
        function sortAndDeduplicateDiagnostics(diagnostics) {
            return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
        }
        ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
    })(ts || (ts = {}));
    /* @internal */
    (function (ts) {
        ts.resolvingEmptyArray = [];
        ts.emptyMap = ts.createMap();
        ts.emptyUnderscoreEscapedMap = ts.emptyMap;
        ts.externalHelpersModuleNameText = "tslib";
        ts.defaultMaximumTruncationLength = 160;
        function getDeclarationOfKind(symbol, kind) {
            var declarations = symbol.declarations;
            if (declarations) {
                for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
                    var declaration = declarations_1[_i];
                    if (declaration.kind === kind) {
                        return declaration;
                    }
                }
            }
            return undefined;
        }
        ts.getDeclarationOfKind = getDeclarationOfKind;
        /** Create a new escaped identifier map. */
        function createUnderscoreEscapedMap() {
            return new ts.MapCtr();
        }
        ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
        function hasEntries(map) {
            return !!map && !!map.size;
        }
        ts.hasEntries = hasEntries;
        function createSymbolTable(symbols) {
            var result = ts.createMap();
            if (symbols) {
                for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
                    var symbol = symbols_1[_i];
                    result.set(symbol.escapedName, symbol);
                }
            }
            return result;
        }
        ts.createSymbolTable = createSymbolTable;
        var stringWriter = createSingleLineStringWriter();
        function createSingleLineStringWriter() {
            var str = "";
            var writeText = function (text) { return str += text; };
            return {
                getText: function () { return str; },
                write: writeText,
                rawWrite: writeText,
                writeTextOfNode: writeText,
                writeKeyword: writeText,
                writeOperator: writeText,
                writePunctuation: writeText,
                writeSpace: writeText,
                writeStringLiteral: writeText,
                writeLiteral: writeText,
                writeParameter: writeText,
                writeProperty: writeText,
                writeSymbol: writeText,
                getTextPos: function () { return str.length; },
                getLine: function () { return 0; },
                getColumn: function () { return 0; },
                getIndent: function () { return 0; },
                isAtStartOfLine: function () { return false; },
                // Completely ignore indentation for string writers.  And map newlines to
                // a single space.
                writeLine: function () { return str += " "; },
                increaseIndent: ts.noop,
                decreaseIndent: ts.noop,
                clear: function () { return str = ""; },
                trackSymbol: ts.noop,
                reportInaccessibleThisError: ts.noop,
                reportInaccessibleUniqueSymbolError: ts.noop,
                reportPrivateInBaseOfClassExpression: ts.noop,
            };
        }
        function toPath(fileName, basePath, getCanonicalFileName) {
            var nonCanonicalizedPath = ts.isRootedDiskPath(fileName)
                ? ts.normalizePath(fileName)
                : ts.getNormalizedAbsolutePath(fileName, basePath);
            return getCanonicalFileName(nonCanonicalizedPath);
        }
        ts.toPath = toPath;
        function changesAffectModuleResolution(oldOptions, newOptions) {
            return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) {
                return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o));
            });
        }
        ts.changesAffectModuleResolution = changesAffectModuleResolution;
        function findAncestor(node, callback) {
            while (node) {
                var result = callback(node);
                if (result === "quit") {
                    return undefined;
                }
                else if (result) {
                    return node;
                }
                node = node.parent;
            }
            return undefined;
        }
        ts.findAncestor = findAncestor;
        function forEachAncestor(node, callback) {
            while (true) {
                var res = callback(node);
                if (res === "quit")
                    return undefined;
                if (res !== undefined)
                    return res;
                if (ts.isSourceFile(node))
                    return undefined;
                node = node.parent;
            }
        }
        ts.forEachAncestor = forEachAncestor;
        function forEachEntry(map, callback) {
            var _a;
            var iterator = map.entries();
            for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
                var key = pair[0], value = pair[1];
                var result = callback(value, key);
                if (result) {
                    return result;
                }
            }
            return undefined;
        }
        ts.forEachEntry = forEachEntry;
        function forEachKey(map, callback) {
            var _a;
            var iterator = map.keys();
            for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
                var result = callback(key);
                if (result) {
                    return result;
                }
            }
            return undefined;
        }
        ts.forEachKey = forEachKey;
        function copyEntries(source, target) {
            source.forEach(function (value, key) {
                target.set(key, value);
            });
        }
        ts.copyEntries = copyEntries;
        function arrayToSet(array, makeKey) {
            return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; });
        }
        ts.arrayToSet = arrayToSet;
        function cloneMap(map) {
            var clone = ts.createMap();
            copyEntries(map, clone);
            return clone;
        }
        ts.cloneMap = cloneMap;
        function usingSingleLineStringWriter(action) {
            var oldString = stringWriter.getText();
            try {
                action(stringWriter);
                return stringWriter.getText();
            }
            finally {
                stringWriter.clear();
                stringWriter.writeKeyword(oldString);
            }
        }
        ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
        function getFullWidth(node) {
            return node.end - node.pos;
        }
        ts.getFullWidth = getFullWidth;
        function getResolvedModule(sourceFile, moduleNameText) {
            return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
        }
        ts.getResolvedModule = getResolvedModule;
        function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
            if (!sourceFile.resolvedModules) {
                sourceFile.resolvedModules = ts.createMap();
            }
            sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
        }
        ts.setResolvedModule = setResolvedModule;
        function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
            if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
                sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
            }
            sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
        }
        ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
        function projectReferenceIsEqualTo(oldRef, newRef) {
            return oldRef.path === newRef.path &&
                !oldRef.prepend === !newRef.prepend &&
                !oldRef.circular === !newRef.circular;
        }
        ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
        function moduleResolutionIsEqualTo(oldResolution, newResolution) {
            return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
                oldResolution.extension === newResolution.extension &&
                oldResolution.resolvedFileName === newResolution.resolvedFileName &&
                oldResolution.originalPath === newResolution.originalPath &&
                packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
        }
        ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
        function packageIdIsEqual(a, b) {
            return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
        }
        function packageIdToString(_a) {
            var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
            var fullName = subModuleName ? name + "/" + subModuleName : name;
            return fullName + "@" + version;
        }
        ts.packageIdToString = packageIdToString;
        function typeDirectiveIsEqualTo(oldResolution, newResolution) {
            return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
        }
        ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
        function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
            ts.Debug.assert(names.length === newResolutions.length);
            for (var i = 0; i < names.length; i++) {
                var newResolution = newResolutions[i];
                var oldResolution = oldResolutions && oldResolutions.get(names[i]);
                var changed = oldResolution
                    ? !newResolution || !comparer(oldResolution, newResolution)
                    : newResolution;
                if (changed) {
                    return true;
                }
            }
            return false;
        }
        ts.hasChangesInResolutions = hasChangesInResolutions;
        // Returns true if this node contains a parse error anywhere underneath it.
        function containsParseError(node) {
            aggregateChildData(node);
            return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0;
        }
        ts.containsParseError = containsParseError;
        function aggregateChildData(node) {
            if (!(node.flags & 262144 /* HasAggregatedChildData */)) {
                // A node is considered to contain a parse error if:
                //  a) the parser explicitly marked that it had an error
                //  b) any of it's children reported that it had an error.
                var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) ||
                    ts.forEachChild(node, containsParseError);
                // If so, mark ourselves accordingly.
                if (thisNodeOrAnySubNodesHasError) {
                    node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */;
                }
                // Also mark that we've propagated the child information to this node.  This way we can
                // always consult the bit directly on this node without needing to check its children
                // again.
                node.flags |= 262144 /* HasAggregatedChildData */;
            }
        }
        function getSourceFileOfNode(node) {
            while (node && node.kind !== 277 /* SourceFile */) {
                node = node.parent;
            }
            return node;
        }
        ts.getSourceFileOfNode = getSourceFileOfNode;
        function isStatementWithLocals(node) {
            switch (node.kind) {
                case 216 /* Block */:
                case 244 /* CaseBlock */:
                case 223 /* ForStatement */:
                case 224 /* ForInStatement */:
                case 225 /* ForOfStatement */:
                    return true;
            }
            return false;
        }
        ts.isStatementWithLocals = isStatementWithLocals;
        function getStartPositionOfLine(line, sourceFile) {
            ts.Debug.assert(line >= 0);
            return ts.getLineStarts(sourceFile)[line];
        }
        ts.getStartPositionOfLine = getStartPositionOfLine;
        // This is a useful function for debugging purposes.
        function nodePosToString(node) {
            var file = getSourceFileOfNode(node);
            var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
            return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
        }
        ts.nodePosToString = nodePosToString;
        function getEndLinePosition(line, sourceFile) {
            ts.Debug.assert(line >= 0);
            var lineStarts = ts.getLineStarts(sourceFile);
            var lineIndex = line;
            var sourceText = sourceFile.text;
            if (lineIndex + 1 === lineStarts.length) {
                // last line - return EOF
                return sourceText.length - 1;
            }
            else {
                // current line start
                var start = lineStarts[lineIndex];
                // take the start position of the next line - 1 = it should be some line break
                var pos = lineStarts[lineIndex + 1] - 1;
                ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
                // walk backwards skipping line breaks, stop the the beginning of current line.
                // i.e:
                // <some text>
                // $ <- end of line for this position should match the start position
                while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
                    pos--;
                }
                return pos;
            }
        }
        ts.getEndLinePosition = getEndLinePosition;
        /**
         * Returns a value indicating whether a name is unique globally or within the current file.
         * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`.
         */
        function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
            return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
        }
        ts.isFileLevelUniqueName = isFileLevelUniqueName;
        // Returns true if this node is missing from the actual source code. A 'missing' node is different
        // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
        // in the tree), it is definitely missing. However, a node may be defined, but still be
        // missing.  This happens whenever the parser knows it needs to parse something, but can't
        // get anything in the source code that it expects at that location. For example:
        //
        //          let a: ;
        //
        // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
        // code). So the parser will attempt to parse out a type, and will create an actual node.
        // However, this node will be 'missing' in the sense that no actual source-code/tokens are
        // contained within it.
        function nodeIsMissing(node) {
            if (node === undefined) {
                return true;
            }
            return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
        }
        ts.nodeIsMissing = nodeIsMissing;
        function nodeIsPresent(node) {
            return !nodeIsMissing(node);
        }
        ts.nodeIsPresent = nodeIsPresent;
        /**
         * Prepends statements to an array while taking care of prologue directives.
         */
        function addStatementsAfterPrologue(to, from) {
            if (from === undefined || from.length === 0)
                return to;
            var statementIndex = 0;
            // skip all prologue directives to insert at the correct position
            for (; statementIndex < to.length; ++statementIndex) {
                if (!isPrologueDirective(to[statementIndex])) {
                    break;
                }
            }
            to.splice.apply(to, [statementIndex, 0].concat(from));
            return to;
        }
        ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
        /**
         * Determine if the given comment is a triple-slash
         *
         * @return true if the comment is a triple-slash comment else false
         */
        function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
            // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
            // so that we don't end up computing comment string and doing match for all // comments
            if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
                commentPos + 2 < commentEnd &&
                text.charCodeAt(commentPos + 2) === 47 /* slash */) {
                var textSubStr = text.substring(commentPos, commentEnd);
                return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
                    textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
                    textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
                    textSubStr.match(defaultLibReferenceRegEx) ?
                    true : false;
            }
            return false;
        }
        ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
        function isPinnedComment(text, start) {
            return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
                text.charCodeAt(start + 2) === 33 /* exclamation */;
        }
        ts.isPinnedComment = isPinnedComment;
        function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
            // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
            // want to skip trivia because this will launch us forward to the next token.
            if (nodeIsMissing(node)) {
                return node.pos;
            }
            if (ts.isJSDocNode(node)) {
                return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
            }
            if (includeJsDoc && ts.hasJSDocNodes(node)) {
                return getTokenPosOfNode(node.jsDoc[0]);
            }
            // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
            // the syntax list itself considers them as normal trivia. Therefore if we simply skip
            // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
            // first child to determine the actual position of its first token.
            if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) {
                return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
            }
            return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
        }
        ts.getTokenPosOfNode = getTokenPosOfNode;
        function getNonDecoratorTokenPosOfNode(node, sourceFile) {
            if (nodeIsMissing(node) || !node.decorators) {
                return getTokenPosOfNode(node, sourceFile);
            }
            return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
        }
        ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
        function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
            if (includeTrivia === void 0) {
                includeTrivia = false;
            }
            return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
        }
        ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
        function isJSDocTypeExpressionOrChild(node) {
            return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
        }
        function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
            if (includeTrivia === void 0) {
                includeTrivia = false;
            }
            if (nodeIsMissing(node)) {
                return "";
            }
            var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
            if (isJSDocTypeExpressionOrChild(node)) {
                // strip space + asterisk at line start
                text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
            }
            return text;
        }
        ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
        function getTextOfNode(node, includeTrivia) {
            if (includeTrivia === void 0) {
                includeTrivia = false;
            }
            return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
        }
        ts.getTextOfNode = getTextOfNode;
        function getPos(range) {
            return range.pos;
        }
        /**
         * Note: it is expected that the `nodeArray` and the `node` are within the same file.
         * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
         */
        function indexOfNode(nodeArray, node) {
            return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
        }
        ts.indexOfNode = indexOfNode;
        /**
         * Gets flags that control emit behavior of a node.
         */
        function getEmitFlags(node) {
            var emitNode = node.emitNode;
            return emitNode && emitNode.flags || 0;
        }
        ts.getEmitFlags = getEmitFlags;
        function getLiteralText(node, sourceFile, neverAsciiEscape) {
            // If we don't need to downlevel and we can reach the original source text using
            // the node's parent reference, then simply get the text as it was originally written.
            if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) {
                return getSourceTextOfNodeFromSourceFile(sourceFile, node);
            }
            var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString;
            // If we can't reach the original source text, use the canonical form if it's a number,
            // or a (possibly escaped) quoted form of the original text if it's string-like.
            switch (node.kind) {
                case 9 /* StringLiteral */:
                    if (node.singleQuote) {
                        return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
                    }
                    else {
                        return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
                    }
                case 13 /* NoSubstitutionTemplateLiteral */:
                    return "`" + escapeText(node.text, 96 /* backtick */) + "`";
                case 14 /* TemplateHead */:
                    // tslint:disable-next-line no-invalid-template-strings
                    return "`" + escapeText(node.text, 96 /* backtick */) + "${";
                case 15 /* TemplateMiddle */:
                    // tslint:disable-next-line no-invalid-template-strings
                    return "}" + escapeText(node.text, 96 /* backtick */) + "${";
                case 16 /* TemplateTail */:
                    return "}" + escapeText(node.text, 96 /* backtick */) + "`";
                case 8 /* NumericLiteral */:
                case 12 /* RegularExpressionLiteral */:
                    return node.text;
            }
            return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
        }
        ts.getLiteralText = getLiteralText;
        function getTextOfConstantValue(value) {
            return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
        }
        ts.getTextOfConstantValue = getTextOfConstantValue;
        // Make an identifier from an external module name by extracting the string after the last "/" and replacing
        // all non-alphanumeric characters with underscores
        function makeIdentifierFromModuleName(moduleName) {
            return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
        }
        ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
        function isBlockOrCatchScoped(declaration) {
            return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
                isCatchClauseVariableDeclarationOrBindingElement(declaration);
        }
        ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
        function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
            var node = getRootDeclaration(declaration);
            return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */;
        }
        ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
        function isAmbientModule(node) {
            return ts.isModuleDeclaration(node) && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
        }
        ts.isAmbientModule = isAmbientModule;
        function isModuleWithStringLiteralName(node) {
            return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */;
        }
        ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
        function isNonGlobalAmbientModule(node) {
            return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
        }
        ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
        /**
         * An effective module (namespace) declaration is either
         * 1. An actual declaration: namespace X { ... }
         * 2. A Javascript declaration, which is:
         *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
         */
        function isEffectiveModuleDeclaration(node) {
            return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
        }
        ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
        /** Given a symbol for a module, checks that it is a shorthand ambient module. */
        function isShorthandAmbientModuleSymbol(moduleSymbol) {
            return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
        }
        ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
        function isShorthandAmbientModule(node) {
            // The only kind of module that can be missing a body is a shorthand ambient module.
            return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body);
        }
        function isBlockScopedContainerTopLevel(node) {
            return node.kind === 277 /* SourceFile */ ||
                node.kind === 242 /* ModuleDeclaration */ ||
                ts.isFunctionLike(node);
        }
        ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
        function isGlobalScopeAugmentation(module) {
            return !!(module.flags & 512 /* GlobalAugmentation */);
        }
        ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
        function isExternalModuleAugmentation(node) {
            return isAmbientModule(node) && isModuleAugmentationExternal(node);
        }
        ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
        function isModuleAugmentationExternal(node) {
            // external module augmentation is a ambient module declaration that is either:
            // - defined in the top level scope and source file is an external module
            // - defined inside ambient module declaration located in the top level scope and source file not an external module
            switch (node.parent.kind) {
                case 277 /* SourceFile */:
                    return ts.isExternalModule(node.parent);
                case 243 /* ModuleBlock */:
                    return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
            }
            return false;
        }
        ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
        function getNonAugmentationDeclaration(symbol) {
            return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
        }
        ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
        function isEffectiveExternalModule(node, compilerOptions) {
            return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
        }
        ts.isEffectiveExternalModule = isEffectiveExternalModule;
        function isBlockScope(node, parentNode) {
            switch (node.kind) {
                case 277 /* SourceFile */:
                case 244 /* CaseBlock */:
                case 272 /* CatchClause */:
                case 242 /* ModuleDeclaration */:
                case 223 /* ForStatement */:
                case 224 /* ForInStatement */:
                case 225 /* ForOfStatement */:
                case 155 /* Constructor */:
                case 154 /* MethodDeclaration */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                case 195 /* ArrowFunction */:
                    return true;
                case 216 /* Block */:
                    // function block is not considered block-scope container
                    // see comment in binder.ts: bind(...), case for SyntaxKind.Block
                    return !ts.isFunctionLike(parentNode);
            }
            return false;
        }
        ts.isBlockScope = isBlockScope;
        function isDeclarationWithTypeParameters(node) {
            switch (node.kind) {
                case 295 /* JSDocCallbackTag */:
                case 302 /* JSDocTypedefTag */:
                case 291 /* JSDocSignature */:
                    return true;
                default:
                    ts.assertType(node);
                    return isDeclarationWithTypeParameterChildren(node);
            }
        }
        ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
        function isDeclarationWithTypeParameterChildren(node) {
            switch (node.kind) {
                case 158 /* CallSignature */:
                case 159 /* ConstructSignature */:
                case 153 /* MethodSignature */:
                case 160 /* IndexSignature */:
                case 163 /* FunctionType */:
                case 164 /* ConstructorType */:
                case 287 /* JSDocFunctionType */:
                case 238 /* ClassDeclaration */:
                case 207 /* ClassExpression */:
                case 239 /* InterfaceDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                case 301 /* JSDocTemplateTag */:
                case 237 /* FunctionDeclaration */:
                case 154 /* MethodDeclaration */:
                case 155 /* Constructor */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 194 /* FunctionExpression */:
                case 195 /* ArrowFunction */:
                    return true;
                default:
                    ts.assertType(node);
                    return false;
            }
        }
        ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
        function isAnyImportSyntax(node) {
            switch (node.kind) {
                case 247 /* ImportDeclaration */:
                case 246 /* ImportEqualsDeclaration */:
                    return true;
                default:
                    return false;
            }
        }
        ts.isAnyImportSyntax = isAnyImportSyntax;
        function isLateVisibilityPaintedStatement(node) {
            switch (node.kind) {
                case 247 /* ImportDeclaration */:
                case 246 /* ImportEqualsDeclaration */:
                case 217 /* VariableStatement */:
                case 238 /* ClassDeclaration */:
                case 237 /* FunctionDeclaration */:
                case 242 /* ModuleDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                case 239 /* InterfaceDeclaration */:
                case 241 /* EnumDeclaration */:
                    return true;
                default:
                    return false;
            }
        }
        ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
        function isAnyImportOrReExport(node) {
            return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
        }
        ts.isAnyImportOrReExport = isAnyImportOrReExport;
        // Gets the nearest enclosing block scope container that has the provided node
        // as a descendant, that is not the provided node.
        function getEnclosingBlockScopeContainer(node) {
            return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
        }
        ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
        // Return display name of an identifier
        // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
        // text of the expression in the computed property.
        function declarationNameToString(name) {
            return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
        }
        ts.declarationNameToString = declarationNameToString;
        function getNameFromIndexInfo(info) {
            return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
        }
        ts.getNameFromIndexInfo = getNameFromIndexInfo;
        function getTextOfPropertyName(name) {
            switch (name.kind) {
                case 71 /* Identifier */:
                    return name.escapedText;
                case 9 /* StringLiteral */:
                case 8 /* NumericLiteral */:
                    return ts.escapeLeadingUnderscores(name.text);
                case 147 /* ComputedPropertyName */:
                    return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined!
                default:
                    return ts.Debug.assertNever(name);
            }
        }
        ts.getTextOfPropertyName = getTextOfPropertyName;
        function entityNameToString(name) {
            switch (name.kind) {
                case 71 /* Identifier */:
                    return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
                case 146 /* QualifiedName */:
                    return entityNameToString(name.left) + "." + entityNameToString(name.right);
                case 187 /* PropertyAccessExpression */:
                    return entityNameToString(name.expression) + "." + entityNameToString(name.name);
                default:
                    throw ts.Debug.assertNever(name);
            }
        }
        ts.entityNameToString = entityNameToString;
        function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
            var sourceFile = getSourceFileOfNode(node);
            return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
        }
        ts.createDiagnosticForNode = createDiagnosticForNode;
        function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
            var start = ts.skipTrivia(sourceFile.text, nodes.pos);
            return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
        }
        ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
        function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
            var span = getErrorSpanForNode(sourceFile, node);
            return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
        }
        ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
        function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
            var sourceFile = getSourceFileOfNode(node);
            var span = getErrorSpanForNode(sourceFile, node);
            return {
                file: sourceFile,
                start: span.start,
                length: span.length,
                code: messageChain.code,
                category: messageChain.category,
                messageText: messageChain.next ? messageChain : messageChain.messageText,
                relatedInformation: relatedInformation
            };
        }
        ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
        function getSpanOfTokenAtPosition(sourceFile, pos) {
            var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
            scanner.scan();
            var start = scanner.getTokenPos();
            return ts.createTextSpanFromBounds(start, scanner.getTextPos());
        }
        ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
        function getErrorSpanForArrowFunction(sourceFile, node) {
            var pos = ts.skipTrivia(sourceFile.text, node.pos);
            if (node.body && node.body.kind === 216 /* Block */) {
                var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
                var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
                if (startLine < endLine) {
                    // The arrow function spans multiple lines,
                    // make the error span be the first line, inclusive.
                    return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
                }
            }
            return ts.createTextSpanFromBounds(pos, node.end);
        }
        function getErrorSpanForNode(sourceFile, node) {
            var errorNode = node;
            switch (node.kind) {
                case 277 /* SourceFile */:
                    var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
                    if (pos_1 === sourceFile.text.length) {
                        // file is empty - return span for the beginning of the file
                        return ts.createTextSpan(0, 0);
                    }
                    return getSpanOfTokenAtPosition(sourceFile, pos_1);
                // This list is a work in progress. Add missing node kinds to improve their error
                // spans.
                case 235 /* VariableDeclaration */:
                case 184 /* BindingElement */:
                case 238 /* ClassDeclaration */:
                case 207 /* ClassExpression */:
                case 239 /* InterfaceDeclaration */:
                case 242 /* ModuleDeclaration */:
                case 241 /* EnumDeclaration */:
                case 276 /* EnumMember */:
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                case 154 /* MethodDeclaration */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 240 /* TypeAliasDeclaration */:
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                    errorNode = node.name;
                    break;
                case 195 /* ArrowFunction */:
                    return getErrorSpanForArrowFunction(sourceFile, node);
            }
            if (errorNode === undefined) {
                // If we don't have a better node, then just set the error on the first token of
                // construct.
                return getSpanOfTokenAtPosition(sourceFile, node.pos);
            }
            var isMissing = nodeIsMissing(errorNode);
            var pos = isMissing
                ? errorNode.pos
                : ts.skipTrivia(sourceFile.text, errorNode.pos);
            // These asserts should all be satisfied for a properly constructed `errorNode`.
            if (isMissing) {
                ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
                ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
            }
            else {
                ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
                ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
            }
            return ts.createTextSpanFromBounds(pos, errorNode.end);
        }
        ts.getErrorSpanForNode = getErrorSpanForNode;
        function isExternalOrCommonJsModule(file) {
            return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
        }
        ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
        function isJsonSourceFile(file) {
            return file.scriptKind === 6 /* JSON */;
        }
        ts.isJsonSourceFile = isJsonSourceFile;
        function isEnumConst(node) {
            return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
        }
        ts.isEnumConst = isEnumConst;
        function isDeclarationReadonly(declaration) {
            return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration));
        }
        ts.isDeclarationReadonly = isDeclarationReadonly;
        function isVarConst(node) {
            return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
        }
        ts.isVarConst = isVarConst;
        function isLet(node) {
            return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
        }
        ts.isLet = isLet;
        function isSuperCall(n) {
            return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */;
        }
        ts.isSuperCall = isSuperCall;
        function isImportCall(n) {
            return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */;
        }
        ts.isImportCall = isImportCall;
        function isLiteralImportTypeNode(n) {
            return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
        }
        ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
        function isPrologueDirective(node) {
            return node.kind === 219 /* ExpressionStatement */
                && node.expression.kind === 9 /* StringLiteral */;
        }
        ts.isPrologueDirective = isPrologueDirective;
        function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
            return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
        }
        ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
        function getJSDocCommentRanges(node, text) {
            var commentRanges = (node.kind === 149 /* Parameter */ ||
                node.kind === 148 /* TypeParameter */ ||
                node.kind === 194 /* FunctionExpression */ ||
                node.kind === 195 /* ArrowFunction */ ||
                node.kind === 193 /* ParenthesizedExpression */) ?
                ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
                ts.getLeadingCommentRanges(text, node.pos);
            // True if the comment starts with '/**' but not if it is '/**/'
            return ts.filter(commentRanges, function (comment) {
                return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
                    text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
                    text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
            });
        }
        ts.getJSDocCommentRanges = getJSDocCommentRanges;
        ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
        var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
        ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
        var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
        function isPartOfTypeNode(node) {
            if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) {
                return true;
            }
            switch (node.kind) {
                case 119 /* AnyKeyword */:
                case 142 /* UnknownKeyword */:
                case 134 /* NumberKeyword */:
                case 137 /* StringKeyword */:
                case 122 /* BooleanKeyword */:
                case 138 /* SymbolKeyword */:
                case 140 /* UndefinedKeyword */:
                case 131 /* NeverKeyword */:
                    return true;
                case 105 /* VoidKeyword */:
                    return node.parent.kind !== 198 /* VoidExpression */;
                case 209 /* ExpressionWithTypeArguments */:
                    return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
                case 148 /* TypeParameter */:
                    return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */;
                // Identifiers and qualified names may be type nodes, depending on their context. Climb
                // above them to find the lowest container
                case 71 /* Identifier */:
                    // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
                    if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) {
                        node = node.parent;
                    }
                    else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) {
                        node = node.parent;
                    }
                    // At this point, node is either a qualified name or an identifier
                    ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
                // falls through
                case 146 /* QualifiedName */:
                case 187 /* PropertyAccessExpression */:
                case 99 /* ThisKeyword */: {
                    var parent = node.parent;
                    if (parent.kind === 165 /* TypeQuery */) {
                        return false;
                    }
                    if (parent.kind === 181 /* ImportType */) {
                        return !parent.isTypeOf;
                    }
                    // Do not recursively call isPartOfTypeNode on the parent. In the example:
                    //
                    //     let a: A.B.C;
                    //
                    // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
                    // Only C and A.B.C are type nodes.
                    if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) {
                        return true;
                    }
                    switch (parent.kind) {
                        case 209 /* ExpressionWithTypeArguments */:
                            return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
                        case 148 /* TypeParameter */:
                            return node === parent.constraint;
                        case 301 /* JSDocTemplateTag */:
                            return node === parent.constraint;
                        case 152 /* PropertyDeclaration */:
                        case 151 /* PropertySignature */:
                        case 149 /* Parameter */:
                        case 235 /* VariableDeclaration */:
                            return node === parent.type;
                        case 237 /* FunctionDeclaration */:
                        case 194 /* FunctionExpression */:
                        case 195 /* ArrowFunction */:
                        case 155 /* Constructor */:
                        case 154 /* MethodDeclaration */:
                        case 153 /* MethodSignature */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            return node === parent.type;
                        case 158 /* CallSignature */:
                        case 159 /* ConstructSignature */:
                        case 160 /* IndexSignature */:
                            return node === parent.type;
                        case 192 /* TypeAssertionExpression */:
                            return node === parent.type;
                        case 189 /* CallExpression */:
                        case 190 /* NewExpression */:
                            return ts.contains(parent.typeArguments, node);
                        case 191 /* TaggedTemplateExpression */:
                            // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
                            return false;
                    }
                }
            }
            return false;
        }
        ts.isPartOfTypeNode = isPartOfTypeNode;
        function isChildOfNodeWithKind(node, kind) {
            while (node) {
                if (node.kind === kind) {
                    return true;
                }
                node = node.parent;
            }
            return false;
        }
        ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
        // Warning: This has the same semantics as the forEach family of functions,
        //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
        function forEachReturnStatement(body, visitor) {
            return traverse(body);
            function traverse(node) {
                switch (node.kind) {
                    case 228 /* ReturnStatement */:
                        return visitor(node);
                    case 244 /* CaseBlock */:
                    case 216 /* Block */:
                    case 220 /* IfStatement */:
                    case 221 /* DoStatement */:
                    case 222 /* WhileStatement */:
                    case 223 /* ForStatement */:
                    case 224 /* ForInStatement */:
                    case 225 /* ForOfStatement */:
                    case 229 /* WithStatement */:
                    case 230 /* SwitchStatement */:
                    case 269 /* CaseClause */:
                    case 270 /* DefaultClause */:
                    case 231 /* LabeledStatement */:
                    case 233 /* TryStatement */:
                    case 272 /* CatchClause */:
                        return ts.forEachChild(node, traverse);
                }
            }
        }
        ts.forEachReturnStatement = forEachReturnStatement;
        function forEachYieldExpression(body, visitor) {
            return traverse(body);
            function traverse(node) {
                switch (node.kind) {
                    case 205 /* YieldExpression */:
                        visitor(node);
                        var operand = node.expression;
                        if (operand) {
                            traverse(operand);
                        }
                        return;
                    case 241 /* EnumDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 242 /* ModuleDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                        // These are not allowed inside a generator now, but eventually they may be allowed
                        // as local types. Regardless, any yield statements contained within them should be
                        // skipped in this traversal.
                        return;
                    default:
                        if (ts.isFunctionLike(node)) {
                            if (node.name && node.name.kind === 147 /* ComputedPropertyName */) {
                                // Note that we will not include methods/accessors of a class because they would require
                                // first descending into the class. This is by design.
                                traverse(node.name.expression);
                                return;
                            }
                        }
                        else if (!isPartOfTypeNode(node)) {
                            // This is the general case, which should include mostly expressions and statements.
                            // Also includes NodeArrays.
                            ts.forEachChild(node, traverse);
                        }
                }
            }
        }
        ts.forEachYieldExpression = forEachYieldExpression;
        /**
         * Gets the most likely element type for a TypeNode. This is not an exhaustive test
         * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
         *
         * @param node The type node.
         */
        function getRestParameterElementType(node) {
            if (node && node.kind === 167 /* ArrayType */) {
                return node.elementType;
            }
            else if (node && node.kind === 162 /* TypeReference */) {
                return ts.singleOrUndefined(node.typeArguments);
            }
            else {
                return undefined;
            }
        }
        ts.getRestParameterElementType = getRestParameterElementType;
        function getMembersOfDeclaration(node) {
            switch (node.kind) {
                case 239 /* InterfaceDeclaration */:
                case 238 /* ClassDeclaration */:
                case 207 /* ClassExpression */:
                case 166 /* TypeLiteral */:
                    return node.members;
                case 186 /* ObjectLiteralExpression */:
                    return node.properties;
            }
        }
        ts.getMembersOfDeclaration = getMembersOfDeclaration;
        function isVariableLike(node) {
            if (node) {
                switch (node.kind) {
                    case 184 /* BindingElement */:
                    case 276 /* EnumMember */:
                    case 149 /* Parameter */:
                    case 273 /* PropertyAssignment */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                    case 274 /* ShorthandPropertyAssignment */:
                    case 235 /* VariableDeclaration */:
                        return true;
                }
            }
            return false;
        }
        ts.isVariableLike = isVariableLike;
        function isVariableLikeOrAccessor(node) {
            return isVariableLike(node) || ts.isAccessor(node);
        }
        ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
        function isVariableDeclarationInVariableStatement(node) {
            return node.parent.kind === 236 /* VariableDeclarationList */
                && node.parent.parent.kind === 217 /* VariableStatement */;
        }
        ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
        function isValidESSymbolDeclaration(node) {
            return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
                ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
                    ts.isPropertySignature(node) && hasReadonlyModifier(node);
        }
        ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
        function introducesArgumentsExoticObject(node) {
            switch (node.kind) {
                case 154 /* MethodDeclaration */:
                case 153 /* MethodSignature */:
                case 155 /* Constructor */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                    return true;
            }
            return false;
        }
        ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
        function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
            while (true) {
                if (beforeUnwrapLabelCallback) {
                    beforeUnwrapLabelCallback(node);
                }
                if (node.statement.kind !== 231 /* LabeledStatement */) {
                    return node.statement;
                }
                node = node.statement;
            }
        }
        ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
        function isFunctionBlock(node) {
            return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent);
        }
        ts.isFunctionBlock = isFunctionBlock;
        function isObjectLiteralMethod(node) {
            return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */;
        }
        ts.isObjectLiteralMethod = isObjectLiteralMethod;
        function isObjectLiteralOrClassExpressionMethod(node) {
            return node.kind === 154 /* MethodDeclaration */ &&
                (node.parent.kind === 186 /* ObjectLiteralExpression */ ||
                    node.parent.kind === 207 /* ClassExpression */);
        }
        ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
        function isIdentifierTypePredicate(predicate) {
            return predicate && predicate.kind === 1 /* Identifier */;
        }
        ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
        function isThisTypePredicate(predicate) {
            return predicate && predicate.kind === 0 /* This */;
        }
        ts.isThisTypePredicate = isThisTypePredicate;
        function getPropertyAssignment(objectLiteral, key, key2) {
            return objectLiteral.properties.filter(function (property) {
                if (property.kind === 273 /* PropertyAssignment */) {
                    var propName = getTextOfPropertyName(property.name);
                    return key === propName || (!!key2 && key2 === propName);
                }
                return false;
            });
        }
        ts.getPropertyAssignment = getPropertyAssignment;
        function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
            if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
                var expression = tsConfigSourceFile.statements[0].expression;
                return ts.tryCast(expression, ts.isObjectLiteralExpression);
            }
        }
        ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
        function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
            return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
                return ts.isArrayLiteralExpression(property.initializer) ?
                    ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
                    undefined;
            });
        }
        ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
        function getTsConfigPropArray(tsConfigSourceFile, propKey) {
            var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
            return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
        }
        ts.getTsConfigPropArray = getTsConfigPropArray;
        function getContainingFunction(node) {
            return findAncestor(node.parent, ts.isFunctionLike);
        }
        ts.getContainingFunction = getContainingFunction;
        function getContainingClass(node) {
            return findAncestor(node.parent, ts.isClassLike);
        }
        ts.getContainingClass = getContainingClass;
        function getThisContainer(node, includeArrowFunctions) {
            ts.Debug.assert(node.kind !== 277 /* SourceFile */);
            while (true) {
                node = node.parent;
                if (!node) {
                    return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
                }
                switch (node.kind) {
                    case 147 /* ComputedPropertyName */:
                        // If the grandparent node is an object literal (as opposed to a class),
                        // then the computed property is not a 'this' container.
                        // A computed property name in a class needs to be a this container
                        // so that we can error on it.
                        if (ts.isClassLike(node.parent.parent)) {
                            return node;
                        }
                        // If this is a computed property, then the parent should not
                        // make it a this container. The parent might be a property
                        // in an object literal, like a method or accessor. But in order for
                        // such a parent to be a this container, the reference must be in
                        // the *body* of the container.
                        node = node.parent;
                        break;
                    case 150 /* Decorator */:
                        // Decorators are always applied outside of the body of a class or method.
                        if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
                            // If the decorator's parent is a Parameter, we resolve the this container from
                            // the grandparent class declaration.
                            node = node.parent.parent;
                        }
                        else if (ts.isClassElement(node.parent)) {
                            // If the decorator's parent is a class element, we resolve the 'this' container
                            // from the parent class declaration.
                            node = node.parent;
                        }
                        break;
                    case 195 /* ArrowFunction */:
                        if (!includeArrowFunctions) {
                            continue;
                        }
                    // falls through
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 242 /* ModuleDeclaration */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 155 /* Constructor */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 158 /* CallSignature */:
                    case 159 /* ConstructSignature */:
                    case 160 /* IndexSignature */:
                    case 241 /* EnumDeclaration */:
                    case 277 /* SourceFile */:
                        return node;
                }
            }
        }
        ts.getThisContainer = getThisContainer;
        function getNewTargetContainer(node) {
            var container = getThisContainer(node, /*includeArrowFunctions*/ false);
            if (container) {
                switch (container.kind) {
                    case 155 /* Constructor */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                        return container;
                }
            }
            return undefined;
        }
        ts.getNewTargetContainer = getNewTargetContainer;
        /**
         * Given an super call/property node, returns the closest node where
         * - a super call/property access is legal in the node and not legal in the parent node the node.
         *   i.e. super call is legal in constructor but not legal in the class body.
         * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
         * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
         *   i.e. super property access is illegal in function declaration but can be legal in the statement list
         */
        function getSuperContainer(node, stopOnFunctions) {
            while (true) {
                node = node.parent;
                if (!node) {
                    return node;
                }
                switch (node.kind) {
                    case 147 /* ComputedPropertyName */:
                        node = node.parent;
                        break;
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        if (!stopOnFunctions) {
                            continue;
                        }
                    // falls through
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 155 /* Constructor */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return node;
                    case 150 /* Decorator */:
                        // Decorators are always applied outside of the body of a class or method.
                        if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
                            // If the decorator's parent is a Parameter, we resolve the this container from
                            // the grandparent class declaration.
                            node = node.parent.parent;
                        }
                        else if (ts.isClassElement(node.parent)) {
                            // If the decorator's parent is a class element, we resolve the 'this' container
                            // from the parent class declaration.
                            node = node.parent;
                        }
                        break;
                }
            }
        }
        ts.getSuperContainer = getSuperContainer;
        function getImmediatelyInvokedFunctionExpression(func) {
            if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) {
                var prev = func;
                var parent = func.parent;
                while (parent.kind === 193 /* ParenthesizedExpression */) {
                    prev = parent;
                    parent = parent.parent;
                }
                if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) {
                    return parent;
                }
            }
        }
        ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
        /**
         * Determines whether a node is a property or element access expression for `super`.
         */
        function isSuperProperty(node) {
            var kind = node.kind;
            return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */)
                && node.expression.kind === 97 /* SuperKeyword */;
        }
        ts.isSuperProperty = isSuperProperty;
        /**
         * Determines whether a node is a property or element access expression for `this`.
         */
        function isThisProperty(node) {
            var kind = node.kind;
            return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */)
                && node.expression.kind === 99 /* ThisKeyword */;
        }
        ts.isThisProperty = isThisProperty;
        function getEntityNameFromTypeNode(node) {
            switch (node.kind) {
                case 162 /* TypeReference */:
                    return node.typeName;
                case 209 /* ExpressionWithTypeArguments */:
                    return isEntityNameExpression(node.expression)
                        ? node.expression
                        : undefined;
                case 71 /* Identifier */:
                case 146 /* QualifiedName */:
                    return node;
            }
            return undefined;
        }
        ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
        function getInvokedExpression(node) {
            switch (node.kind) {
                case 191 /* TaggedTemplateExpression */:
                    return node.tag;
                case 260 /* JsxOpeningElement */:
                case 259 /* JsxSelfClosingElement */:
                    return node.tagName;
                default:
                    return node.expression;
            }
        }
        ts.getInvokedExpression = getInvokedExpression;
        function nodeCanBeDecorated(node, parent, grandparent) {
            switch (node.kind) {
                case 238 /* ClassDeclaration */:
                    // classes are valid targets
                    return true;
                case 152 /* PropertyDeclaration */:
                    // property declarations are valid if their parent is a class declaration.
                    return parent.kind === 238 /* ClassDeclaration */;
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 154 /* MethodDeclaration */:
                    // if this method has a body and its parent is a class declaration, this is a valid target.
                    return node.body !== undefined
                        && parent.kind === 238 /* ClassDeclaration */;
                case 149 /* Parameter */:
                    // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
                    return parent.body !== undefined
                        && (parent.kind === 155 /* Constructor */
                            || parent.kind === 154 /* MethodDeclaration */
                            || parent.kind === 157 /* SetAccessor */)
                        && grandparent.kind === 238 /* ClassDeclaration */;
            }
            return false;
        }
        ts.nodeCanBeDecorated = nodeCanBeDecorated;
        function nodeIsDecorated(node, parent, grandparent) {
            return node.decorators !== undefined
                && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
        }
        ts.nodeIsDecorated = nodeIsDecorated;
        function nodeOrChildIsDecorated(node, parent, grandparent) {
            return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
        }
        ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
        function childIsDecorated(node, parent) {
            switch (node.kind) {
                case 238 /* ClassDeclaration */:
                    return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
                case 154 /* MethodDeclaration */:
                case 157 /* SetAccessor */:
                    return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
                default:
                    return false;
            }
        }
        ts.childIsDecorated = childIsDecorated;
        function isJSXTagName(node) {
            var parent = node.parent;
            if (parent.kind === 260 /* JsxOpeningElement */ ||
                parent.kind === 259 /* JsxSelfClosingElement */ ||
                parent.kind === 261 /* JsxClosingElement */) {
                return parent.tagName === node;
            }
            return false;
        }
        ts.isJSXTagName = isJSXTagName;
        function isExpressionNode(node) {
            switch (node.kind) {
                case 97 /* SuperKeyword */:
                case 95 /* NullKeyword */:
                case 101 /* TrueKeyword */:
                case 86 /* FalseKeyword */:
                case 12 /* RegularExpressionLiteral */:
                case 185 /* ArrayLiteralExpression */:
                case 186 /* ObjectLiteralExpression */:
                case 187 /* PropertyAccessExpression */:
                case 188 /* ElementAccessExpression */:
                case 189 /* CallExpression */:
                case 190 /* NewExpression */:
                case 191 /* TaggedTemplateExpression */:
                case 210 /* AsExpression */:
                case 192 /* TypeAssertionExpression */:
                case 211 /* NonNullExpression */:
                case 193 /* ParenthesizedExpression */:
                case 194 /* FunctionExpression */:
                case 207 /* ClassExpression */:
                case 195 /* ArrowFunction */:
                case 198 /* VoidExpression */:
                case 196 /* DeleteExpression */:
                case 197 /* TypeOfExpression */:
                case 200 /* PrefixUnaryExpression */:
                case 201 /* PostfixUnaryExpression */:
                case 202 /* BinaryExpression */:
                case 203 /* ConditionalExpression */:
                case 206 /* SpreadElement */:
                case 204 /* TemplateExpression */:
                case 13 /* NoSubstitutionTemplateLiteral */:
                case 208 /* OmittedExpression */:
                case 258 /* JsxElement */:
                case 259 /* JsxSelfClosingElement */:
                case 262 /* JsxFragment */:
                case 205 /* YieldExpression */:
                case 199 /* AwaitExpression */:
                case 212 /* MetaProperty */:
                    return true;
                case 146 /* QualifiedName */:
                    while (node.parent.kind === 146 /* QualifiedName */) {
                        node = node.parent;
                    }
                    return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node);
                case 71 /* Identifier */:
                    if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) {
                        return true;
                    }
                // falls through
                case 8 /* NumericLiteral */:
                case 9 /* StringLiteral */:
                case 99 /* ThisKeyword */:
                    return isInExpressionContext(node);
                default:
                    return false;
            }
        }
        ts.isExpressionNode = isExpressionNode;
        function isInExpressionContext(node) {
            var parent = node.parent;
            switch (parent.kind) {
                case 235 /* VariableDeclaration */:
                case 149 /* Parameter */:
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                case 276 /* EnumMember */:
                case 273 /* PropertyAssignment */:
                case 184 /* BindingElement */:
                    return parent.initializer === node;
                case 219 /* ExpressionStatement */:
                case 220 /* IfStatement */:
                case 221 /* DoStatement */:
                case 222 /* WhileStatement */:
                case 228 /* ReturnStatement */:
                case 229 /* WithStatement */:
                case 230 /* SwitchStatement */:
                case 269 /* CaseClause */:
                case 232 /* ThrowStatement */:
                    return parent.expression === node;
                case 223 /* ForStatement */:
                    var forStatement = parent;
                    return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) ||
                        forStatement.condition === node ||
                        forStatement.incrementor === node;
                case 224 /* ForInStatement */:
                case 225 /* ForOfStatement */:
                    var forInStatement = parent;
                    return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) ||
                        forInStatement.expression === node;
                case 192 /* TypeAssertionExpression */:
                case 210 /* AsExpression */:
                    return node === parent.expression;
                case 214 /* TemplateSpan */:
                    return node === parent.expression;
                case 147 /* ComputedPropertyName */:
                    return node === parent.expression;
                case 150 /* Decorator */:
                case 268 /* JsxExpression */:
                case 267 /* JsxSpreadAttribute */:
                case 275 /* SpreadAssignment */:
                    return true;
                case 209 /* ExpressionWithTypeArguments */:
                    return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
                case 274 /* ShorthandPropertyAssignment */:
                    return parent.objectAssignmentInitializer === node;
                default:
                    return isExpressionNode(parent);
            }
        }
        ts.isInExpressionContext = isInExpressionContext;
        function isExternalModuleImportEqualsDeclaration(node) {
            return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */;
        }
        ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
        function getExternalModuleImportEqualsDeclarationExpression(node) {
            ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
            return node.moduleReference.expression;
        }
        ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
        function isInternalModuleImportEqualsDeclaration(node) {
            return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */;
        }
        ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
        function isSourceFileJS(file) {
            return isInJSFile(file);
        }
        ts.isSourceFileJS = isSourceFileJS;
        function isSourceFileNotJS(file) {
            return !isInJSFile(file);
        }
        ts.isSourceFileNotJS = isSourceFileNotJS;
        function isInJSFile(node) {
            return !!node && !!(node.flags & 65536 /* JavaScriptFile */);
        }
        ts.isInJSFile = isInJSFile;
        function isInJsonFile(node) {
            return !!node && !!(node.flags & 16777216 /* JsonFile */);
        }
        ts.isInJsonFile = isInJsonFile;
        function isInJSDoc(node) {
            return !!node && !!(node.flags & 2097152 /* JSDoc */);
        }
        ts.isInJSDoc = isInJSDoc;
        function isJSDocIndexSignature(node) {
            return ts.isTypeReferenceNode(node) &&
                ts.isIdentifier(node.typeName) &&
                node.typeName.escapedText === "Object" &&
                node.typeArguments && node.typeArguments.length === 2 &&
                (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */);
        }
        ts.isJSDocIndexSignature = isJSDocIndexSignature;
        function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) {
            if (callExpression.kind !== 189 /* CallExpression */) {
                return false;
            }
            var _a = callExpression, expression = _a.expression, args = _a.arguments;
            if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") {
                return false;
            }
            if (args.length !== 1) {
                return false;
            }
            var arg = args[0];
            return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg);
        }
        ts.isRequireCall = isRequireCall;
        function isSingleOrDoubleQuote(charCode) {
            return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
        }
        ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
        function isStringDoubleQuoted(str, sourceFile) {
            return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
        }
        ts.isStringDoubleQuoted = isStringDoubleQuoted;
        function getDeclarationOfExpando(node) {
            if (!node.parent) {
                return undefined;
            }
            var name;
            var decl;
            if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
                if (!isInJSFile(node) && !isVarConst(node.parent)) {
                    return undefined;
                }
                name = node.parent.name;
                decl = node.parent;
            }
            else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) {
                name = node.parent.left;
                decl = name;
            }
            else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) {
                if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) {
                    name = node.parent.parent.name;
                    decl = node.parent.parent;
                }
                else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) {
                    name = node.parent.parent.left;
                    decl = name;
                }
                if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) {
                    return undefined;
                }
            }
            if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
                return undefined;
            }
            return decl;
        }
        ts.getDeclarationOfExpando = getDeclarationOfExpando;
        function isAssignmentDeclaration(decl) {
            return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl);
        }
        ts.isAssignmentDeclaration = isAssignmentDeclaration;
        /** Get the initializer, taking into account defaulted Javascript initializers */
        function getEffectiveInitializer(node) {
            if (isInJSFile(node) && node.initializer &&
                ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ &&
                node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
                return node.initializer.right;
            }
            return node.initializer;
        }
        ts.getEffectiveInitializer = getEffectiveInitializer;
        /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
        function getDeclaredExpandoInitializer(node) {
            var init = getEffectiveInitializer(node);
            return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
        }
        ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
        /**
         * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
         * We treat the right hand side of assignments with container-like initalizers as declarations.
         */
        function getAssignedExpandoInitializer(node) {
            if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) {
                var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
                return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
                    getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
            }
        }
        ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
        /**
         * Recognized expando initializers are:
         * 1. (function() {})() -- IIFEs
         * 2. function() { } -- Function expressions
         * 3. class { } -- Class expressions
         * 4. {} -- Empty object literals
         * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
         *
         * This function returns the provided initializer, or undefined if it is not valid.
         */
        function getExpandoInitializer(initializer, isPrototypeAssignment) {
            if (ts.isCallExpression(initializer)) {
                var e = skipParentheses(initializer.expression);
                return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined;
            }
            if (initializer.kind === 194 /* FunctionExpression */ ||
                initializer.kind === 207 /* ClassExpression */ ||
                initializer.kind === 195 /* ArrowFunction */) {
                return initializer;
            }
            if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
                return initializer;
            }
        }
        ts.getExpandoInitializer = getExpandoInitializer;
        /**
         * A defaulted expando initializer matches the pattern
         * `Lhs = Lhs || ExpandoInitializer`
         * or `var Lhs = Lhs || ExpandoInitializer`
         *
         * The second Lhs is required to be the same as the first except that it may be prefixed with
         * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
         */
        function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
            var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment);
            if (e && isSameEntityName(name, initializer.left)) {
                return e;
            }
        }
        function isDefaultedExpandoInitializer(node) {
            var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
                ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left :
                    undefined;
            return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
        }
        ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
        /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
        function getNameOfExpando(node) {
            if (ts.isBinaryExpression(node.parent)) {
                var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
                if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
                    return parent.left;
                }
            }
            else if (ts.isVariableDeclaration(node.parent)) {
                return node.parent.name;
            }
        }
        ts.getNameOfExpando = getNameOfExpando;
        /**
         * Is the 'declared' name the same as the one in the initializer?
         * @return true for identical entity names, as well as ones where the initializer is prefixed with
         * 'window', 'self' or 'global'. For example:
         *
         * var my = my || {}
         * var min = window.min || {}
         * my.app = self.my.app || class { }
         */
        function isSameEntityName(name, initializer) {
            if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) {
                return name.escapedText === initializer.escapedText;
            }
            if (ts.isIdentifier(name) && ts.isPropertyAccessExpression(initializer)) {
                return (initializer.expression.kind === 99 /* ThisKeyword */ ||
                    ts.isIdentifier(initializer.expression) &&
                        (initializer.expression.escapedText === "window" ||
                            initializer.expression.escapedText === "self" ||
                            initializer.expression.escapedText === "global")) &&
                    isSameEntityName(name, initializer.name);
            }
            if (ts.isPropertyAccessExpression(name) && ts.isPropertyAccessExpression(initializer)) {
                return name.name.escapedText === initializer.name.escapedText && isSameEntityName(name.expression, initializer.expression);
            }
            return false;
        }
        function getRightMostAssignedExpression(node) {
            while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
                node = node.right;
            }
            return node;
        }
        ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
        function isExportsIdentifier(node) {
            return ts.isIdentifier(node) && node.escapedText === "exports";
        }
        ts.isExportsIdentifier = isExportsIdentifier;
        function isModuleExportsPropertyAccessExpression(node) {
            return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports";
        }
        ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression;
        /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
        /// assignments we treat as special in the binder
        function getAssignmentDeclarationKind(expr) {
            var special = getAssignmentDeclarationKindWorker(expr);
            return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
        }
        ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
        function getAssignmentDeclarationKindWorker(expr) {
            if (expr.operatorToken.kind !== 58 /* EqualsToken */ ||
                !ts.isPropertyAccessExpression(expr.left)) {
                return 0 /* None */;
            }
            var lhs = expr.left;
            if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
                // F.prototype = { ... }
                return 6 /* Prototype */;
            }
            return getAssignmentDeclarationPropertyAccessKind(lhs);
        }
        function getAssignmentDeclarationPropertyAccessKind(lhs) {
            if (lhs.expression.kind === 99 /* ThisKeyword */) {
                return 4 /* ThisProperty */;
            }
            else if (ts.isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") {
                // module.exports = expr
                return 2 /* ModuleExports */;
            }
            else if (isEntityNameExpression(lhs.expression)) {
                if (isPrototypeAccess(lhs.expression)) {
                    // F.G....prototype.x = expr
                    return 3 /* PrototypeProperty */;
                }
                var nextToLast = lhs;
                while (ts.isPropertyAccessExpression(nextToLast.expression)) {
                    nextToLast = nextToLast.expression;
                }
                ts.Debug.assert(ts.isIdentifier(nextToLast.expression));
                var id = nextToLast.expression;
                if (id.escapedText === "exports" ||
                    id.escapedText === "module" && nextToLast.name.escapedText === "exports") {
                    // exports.name = expr OR module.exports.name = expr
                    return 1 /* ExportsProperty */;
                }
                // F.G...x = expr
                return 5 /* Property */;
            }
            return 0 /* None */;
        }
        ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
        function getInitializerOfBinaryExpression(expr) {
            while (ts.isBinaryExpression(expr.right)) {
                expr = expr.right;
            }
            return expr.right;
        }
        ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
        function isPrototypePropertyAssignment(node) {
            return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
        }
        ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
        function isSpecialPropertyDeclaration(expr) {
            return isInJSFile(expr) &&
                expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ &&
                !!ts.getJSDocTypeTag(expr.parent);
        }
        ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
        function isFunctionSymbol(symbol) {
            if (!symbol || !symbol.valueDeclaration) {
                return false;
            }
            var decl = symbol.valueDeclaration;
            return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
        }
        ts.isFunctionSymbol = isFunctionSymbol;
        function importFromModuleSpecifier(node) {
            return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
        }
        ts.importFromModuleSpecifier = importFromModuleSpecifier;
        function tryGetImportFromModuleSpecifier(node) {
            switch (node.parent.kind) {
                case 247 /* ImportDeclaration */:
                case 253 /* ExportDeclaration */:
                    return node.parent;
                case 257 /* ExternalModuleReference */:
                    return node.parent.parent;
                case 189 /* CallExpression */:
                    return node.parent;
                case 180 /* LiteralType */:
                    ts.Debug.assert(ts.isStringLiteral(node));
                    return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
                default:
                    return undefined;
            }
        }
        ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
        function getExternalModuleName(node) {
            switch (node.kind) {
                case 247 /* ImportDeclaration */:
                case 253 /* ExportDeclaration */:
                    return node.moduleSpecifier;
                case 246 /* ImportEqualsDeclaration */:
                    return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
                case 181 /* ImportType */:
                    return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
                default:
                    return ts.Debug.assertNever(node);
            }
        }
        ts.getExternalModuleName = getExternalModuleName;
        function getNamespaceDeclarationNode(node) {
            switch (node.kind) {
                case 247 /* ImportDeclaration */:
                    return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
                case 246 /* ImportEqualsDeclaration */:
                    return node;
                case 253 /* ExportDeclaration */:
                    return undefined;
                default:
                    return ts.Debug.assertNever(node);
            }
        }
        ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
        function isDefaultImport(node) {
            return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
        }
        ts.isDefaultImport = isDefaultImport;
        function hasQuestionToken(node) {
            if (node) {
                switch (node.kind) {
                    case 149 /* Parameter */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 274 /* ShorthandPropertyAssignment */:
                    case 273 /* PropertyAssignment */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                        return node.questionToken !== undefined;
                }
            }
            return false;
        }
        ts.hasQuestionToken = hasQuestionToken;
        function isJSDocConstructSignature(node) {
            return node.kind === 287 /* JSDocFunctionType */ &&
                node.parameters.length > 0 &&
                node.parameters[0].name &&
                node.parameters[0].name.escapedText === "new";
        }
        ts.isJSDocConstructSignature = isJSDocConstructSignature;
        function isJSDocTypeAlias(node) {
            return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */;
        }
        ts.isJSDocTypeAlias = isJSDocTypeAlias;
        function isTypeAlias(node) {
            return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
        }
        ts.isTypeAlias = isTypeAlias;
        function getSourceOfAssignment(node) {
            return ts.isExpressionStatement(node) &&
                node.expression && ts.isBinaryExpression(node.expression) &&
                node.expression.operatorToken.kind === 58 /* EqualsToken */
                ? node.expression.right
                : undefined;
        }
        function getSourceOfDefaultedAssignment(node) {
            return ts.isExpressionStatement(node) &&
                ts.isBinaryExpression(node.expression) &&
                getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
                ts.isBinaryExpression(node.expression.right) &&
                node.expression.right.operatorToken.kind === 54 /* BarBarToken */
                ? node.expression.right.right
                : undefined;
        }
        function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
            switch (node.kind) {
                case 217 /* VariableStatement */:
                    var v = getSingleVariableOfVariableStatement(node);
                    return v && v.initializer;
                case 152 /* PropertyDeclaration */:
                    return node.initializer;
                case 273 /* PropertyAssignment */:
                    return node.initializer;
            }
        }
        function getSingleVariableOfVariableStatement(node) {
            return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
        }
        function getNestedModuleDeclaration(node) {
            return ts.isModuleDeclaration(node) &&
                node.body &&
                node.body.kind === 242 /* ModuleDeclaration */
                ? node.body
                : undefined;
        }
        function getJSDocCommentsAndTags(hostNode) {
            var result;
            // Pull parameter comments from declaring function as well
            if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
                result = ts.addRange(result, hostNode.initializer.jsDoc);
            }
            var node = hostNode;
            while (node && node.parent) {
                if (ts.hasJSDocNodes(node)) {
                    result = ts.addRange(result, node.jsDoc);
                }
                if (node.kind === 149 /* Parameter */) {
                    result = ts.addRange(result, ts.getJSDocParameterTags(node));
                    break;
                }
                if (node.kind === 148 /* TypeParameter */) {
                    result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
                    break;
                }
                node = getNextJSDocCommentLocation(node);
            }
            return result || ts.emptyArray;
        }
        ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
        function getNextJSDocCommentLocation(node) {
            var parent = node.parent;
            if (parent.kind === 273 /* PropertyAssignment */ ||
                parent.kind === 152 /* PropertyDeclaration */ ||
                parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ ||
                getNestedModuleDeclaration(parent) ||
                ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) {
                return parent;
            }
            // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
            // /**
            //   * @param {number} name
            //   * @returns {number}
            //   */
            // var x = function(name) { return name.length; }
            else if (parent.parent &&
                (getSingleVariableOfVariableStatement(parent.parent) === node ||
                    ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) {
                return parent.parent;
            }
            else if (parent.parent && parent.parent.parent &&
                (getSingleVariableOfVariableStatement(parent.parent.parent) ||
                    getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
                    getSourceOfDefaultedAssignment(parent.parent.parent))) {
                return parent.parent.parent;
            }
        }
        /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
        function getParameterSymbolFromJSDoc(node) {
            if (node.symbol) {
                return node.symbol;
            }
            if (!ts.isIdentifier(node.name)) {
                return undefined;
            }
            var name = node.name.escapedText;
            var decl = getHostSignatureFromJSDoc(node);
            if (!decl) {
                return undefined;
            }
            var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; });
            return parameter && parameter.symbol;
        }
        ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
        function getHostSignatureFromJSDoc(node) {
            return getHostSignatureFromJSDocHost(getJSDocHost(node));
        }
        ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
        function getHostSignatureFromJSDocHost(host) {
            var decl = getSourceOfDefaultedAssignment(host) ||
                getSourceOfAssignment(host) ||
                getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
                getSingleVariableOfVariableStatement(host) ||
                getNestedModuleDeclaration(host) ||
                host;
            return decl && ts.isFunctionLike(decl) ? decl : undefined;
        }
        ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
        function getJSDocHost(node) {
            return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
        }
        ts.getJSDocHost = getJSDocHost;
        function getTypeParameterFromJsDoc(node) {
            var name = node.name.escapedText;
            var typeParameters = node.parent.parent.parent.typeParameters;
            return ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
        }
        ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
        function hasRestParameter(s) {
            var last = ts.lastOrUndefined(s.parameters);
            return !!last && isRestParameter(last);
        }
        ts.hasRestParameter = hasRestParameter;
        function isRestParameter(node) {
            var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
            return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */;
        }
        ts.isRestParameter = isRestParameter;
        var AssignmentKind;
        (function (AssignmentKind) {
            AssignmentKind[AssignmentKind["None"] = 0] = "None";
            AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
            AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
        })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
        function getAssignmentTargetKind(node) {
            var parent = node.parent;
            while (true) {
                switch (parent.kind) {
                    case 202 /* BinaryExpression */:
                        var binaryOperator = parent.operatorToken.kind;
                        return isAssignmentOperator(binaryOperator) && parent.left === node ?
                            binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
                            0 /* None */;
                    case 200 /* PrefixUnaryExpression */:
                    case 201 /* PostfixUnaryExpression */:
                        var unaryOperator = parent.operator;
                        return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
                    case 224 /* ForInStatement */:
                    case 225 /* ForOfStatement */:
                        return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
                    case 193 /* ParenthesizedExpression */:
                    case 185 /* ArrayLiteralExpression */:
                    case 206 /* SpreadElement */:
                    case 211 /* NonNullExpression */:
                        node = parent;
                        break;
                    case 274 /* ShorthandPropertyAssignment */:
                        if (parent.name !== node) {
                            return 0 /* None */;
                        }
                        node = parent.parent;
                        break;
                    case 273 /* PropertyAssignment */:
                        if (parent.name === node) {
                            return 0 /* None */;
                        }
                        node = parent.parent;
                        break;
                    default:
                        return 0 /* None */;
                }
                parent = node.parent;
            }
        }
        ts.getAssignmentTargetKind = getAssignmentTargetKind;
        // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
        // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
        // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
        // (Note that `p` is not a target in the above examples, only `a`.)
        function isAssignmentTarget(node) {
            return getAssignmentTargetKind(node) !== 0 /* None */;
        }
        ts.isAssignmentTarget = isAssignmentTarget;
        /**
         * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
         * the same `var` declaration scope as the node's parent.
         */
        function isNodeWithPossibleHoistedDeclaration(node) {
            switch (node.kind) {
                case 216 /* Block */:
                case 217 /* VariableStatement */:
                case 229 /* WithStatement */:
                case 220 /* IfStatement */:
                case 230 /* SwitchStatement */:
                case 244 /* CaseBlock */:
                case 269 /* CaseClause */:
                case 270 /* DefaultClause */:
                case 231 /* LabeledStatement */:
                case 223 /* ForStatement */:
                case 224 /* ForInStatement */:
                case 225 /* ForOfStatement */:
                case 221 /* DoStatement */:
                case 222 /* WhileStatement */:
                case 233 /* TryStatement */:
                case 272 /* CatchClause */:
                    return true;
            }
            return false;
        }
        ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
        function isValueSignatureDeclaration(node) {
            return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
        }
        ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
        function walkUp(node, kind) {
            while (node && node.kind === kind) {
                node = node.parent;
            }
            return node;
        }
        function walkUpParenthesizedTypes(node) {
            return walkUp(node, 175 /* ParenthesizedType */);
        }
        ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
        function walkUpParenthesizedExpressions(node) {
            return walkUp(node, 193 /* ParenthesizedExpression */);
        }
        ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
        function skipParentheses(node) {
            while (node.kind === 193 /* ParenthesizedExpression */) {
                node = node.expression;
            }
            return node;
        }
        ts.skipParentheses = skipParentheses;
        function skipParenthesesUp(node) {
            while (node.kind === 193 /* ParenthesizedExpression */) {
                node = node.parent;
            }
            return node;
        }
        // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
        function isDeleteTarget(node) {
            if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) {
                return false;
            }
            node = walkUpParenthesizedExpressions(node.parent);
            return node && node.kind === 196 /* DeleteExpression */;
        }
        ts.isDeleteTarget = isDeleteTarget;
        function isNodeDescendantOf(node, ancestor) {
            while (node) {
                if (node === ancestor)
                    return true;
                node = node.parent;
            }
            return false;
        }
        ts.isNodeDescendantOf = isNodeDescendantOf;
        // True if `name` is the name of a declaration node
        function isDeclarationName(name) {
            return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
        }
        ts.isDeclarationName = isDeclarationName;
        // See GH#16030
        function getDeclarationFromName(name) {
            var parent = name.parent;
            switch (name.kind) {
                case 9 /* StringLiteral */:
                case 8 /* NumericLiteral */:
                    if (ts.isComputedPropertyName(parent))
                        return parent.parent;
                // falls through
                case 71 /* Identifier */:
                    if (ts.isDeclaration(parent)) {
                        return parent.name === name ? parent : undefined;
                    }
                    else if (ts.isQualifiedName(parent)) {
                        var tag = parent.parent;
                        return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
                    }
                    else {
                        var binExp = parent.parent;
                        return ts.isBinaryExpression(binExp) &&
                            getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
                            (binExp.left.symbol || binExp.symbol) &&
                            ts.getNameOfDeclaration(binExp) === name
                            ? binExp
                            : undefined;
                    }
                default:
                    return undefined;
            }
        }
        ts.getDeclarationFromName = getDeclarationFromName;
        function isLiteralComputedPropertyDeclarationName(node) {
            return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) &&
                node.parent.kind === 147 /* ComputedPropertyName */ &&
                ts.isDeclaration(node.parent.parent);
        }
        ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
        // Return true if the given identifier is classified as an IdentifierName
        function isIdentifierName(node) {
            var parent = node.parent;
            switch (parent.kind) {
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                case 154 /* MethodDeclaration */:
                case 153 /* MethodSignature */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 276 /* EnumMember */:
                case 273 /* PropertyAssignment */:
                case 187 /* PropertyAccessExpression */:
                    // Name in member declaration or property name in property access
                    return parent.name === node;
                case 146 /* QualifiedName */:
                    // Name on right hand side of dot in a type query or type reference
                    if (parent.right === node) {
                        while (parent.kind === 146 /* QualifiedName */) {
                            parent = parent.parent;
                        }
                        return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */;
                    }
                    return false;
                case 184 /* BindingElement */:
                case 251 /* ImportSpecifier */:
                    // Property name in binding element or import specifier
                    return parent.propertyName === node;
                case 255 /* ExportSpecifier */:
                case 265 /* JsxAttribute */:
                    // Any name in an export specifier or JSX Attribute
                    return true;
            }
            return false;
        }
        ts.isIdentifierName = isIdentifierName;
        // An alias symbol is created by one of the following declarations:
        // import <symbol> = ...
        // import <symbol> from ...
        // import * as <symbol> from ...
        // import { x as <symbol> } from ...
        // export { x as <symbol> } from ...
        // export = <EntityNameExpression>
        // export default <EntityNameExpression>
        function isAliasSymbolDeclaration(node) {
            return node.kind === 246 /* ImportEqualsDeclaration */ ||
                node.kind === 245 /* NamespaceExportDeclaration */ ||
                node.kind === 248 /* ImportClause */ && !!node.name ||
                node.kind === 249 /* NamespaceImport */ ||
                node.kind === 251 /* ImportSpecifier */ ||
                node.kind === 255 /* ExportSpecifier */ ||
                node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
                ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */;
        }
        ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
        function exportAssignmentIsAlias(node) {
            var e = ts.isExportAssignment(node) ? node.expression : node.right;
            return isEntityNameExpression(e) || ts.isClassExpression(e);
        }
        ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
        function getEffectiveBaseTypeNode(node) {
            if (isInJSFile(node)) {
                // Prefer an @augments tag because it may have type parameters.
                var tag = ts.getJSDocAugmentsTag(node);
                if (tag) {
                    return tag.class;
                }
            }
            return getClassExtendsHeritageElement(node);
        }
        ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
        function getClassExtendsHeritageElement(node) {
            var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */);
            return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
        }
        ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
        function getClassImplementsHeritageClauseElements(node) {
            var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */);
            return heritageClause ? heritageClause.types : undefined;
        }
        ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements;
        /** Returns the node in an `extends` or `implements` clause of a class or interface. */
        function getAllSuperTypeNodes(node) {
            return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray
                : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray
                    : ts.emptyArray;
        }
        ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
        function getInterfaceBaseTypeNodes(node) {
            var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */);
            return heritageClause ? heritageClause.types : undefined;
        }
        ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
        function getHeritageClause(clauses, kind) {
            if (clauses) {
                for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
                    var clause = clauses_1[_i];
                    if (clause.token === kind) {
                        return clause;
                    }
                }
            }
            return undefined;
        }
        ts.getHeritageClause = getHeritageClause;
        function tryResolveScriptReference(host, sourceFile, reference) {
            if (!host.getCompilerOptions().noResolve) {
                var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName);
                return host.getSourceFile(referenceFileName);
            }
        }
        ts.tryResolveScriptReference = tryResolveScriptReference;
        function getAncestor(node, kind) {
            while (node) {
                if (node.kind === kind) {
                    return node;
                }
                node = node.parent;
            }
            return undefined;
        }
        ts.getAncestor = getAncestor;
        function isKeyword(token) {
            return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */;
        }
        ts.isKeyword = isKeyword;
        function isContextualKeyword(token) {
            return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */;
        }
        ts.isContextualKeyword = isContextualKeyword;
        function isNonContextualKeyword(token) {
            return isKeyword(token) && !isContextualKeyword(token);
        }
        ts.isNonContextualKeyword = isNonContextualKeyword;
        function isStringANonContextualKeyword(name) {
            var token = ts.stringToToken(name);
            return token !== undefined && isNonContextualKeyword(token);
        }
        ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
        function isTrivia(token) {
            return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
        }
        ts.isTrivia = isTrivia;
        var FunctionFlags;
        (function (FunctionFlags) {
            FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
            FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
            FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
            FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
            FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
        })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
        function getFunctionFlags(node) {
            if (!node) {
                return 4 /* Invalid */;
            }
            var flags = 0 /* Normal */;
            switch (node.kind) {
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                case 154 /* MethodDeclaration */:
                    if (node.asteriskToken) {
                        flags |= 1 /* Generator */;
                    }
                // falls through
                case 195 /* ArrowFunction */:
                    if (hasModifier(node, 256 /* Async */)) {
                        flags |= 2 /* Async */;
                    }
                    break;
            }
            if (!node.body) {
                flags |= 4 /* Invalid */;
            }
            return flags;
        }
        ts.getFunctionFlags = getFunctionFlags;
        function isAsyncFunction(node) {
            switch (node.kind) {
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                case 195 /* ArrowFunction */:
                case 154 /* MethodDeclaration */:
                    return node.body !== undefined
                        && node.asteriskToken === undefined
                        && hasModifier(node, 256 /* Async */);
            }
            return false;
        }
        ts.isAsyncFunction = isAsyncFunction;
        function isStringOrNumericLiteralLike(node) {
            return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
        }
        ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
        /**
         * A declaration has a dynamic name if both of the following are true:
         *   1. The declaration has a computed property name
         *   2. The computed name is *not* expressed as Symbol.<name>, where name
         *      is a property of the Symbol constructor that denotes a built in
         *      Symbol.
         */
        function hasDynamicName(declaration) {
            var name = ts.getNameOfDeclaration(declaration);
            return !!name && isDynamicName(name);
        }
        ts.hasDynamicName = hasDynamicName;
        function isDynamicName(name) {
            return name.kind === 147 /* ComputedPropertyName */ &&
                !isStringOrNumericLiteralLike(name.expression) &&
                !isWellKnownSymbolSyntactically(name.expression);
        }
        ts.isDynamicName = isDynamicName;
        /**
         * Checks if the expression is of the form:
         *    Symbol.name
         * where Symbol is literally the word "Symbol", and name is any identifierName
         */
        function isWellKnownSymbolSyntactically(node) {
            return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
        }
        ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
        function getPropertyNameForPropertyNameNode(name) {
            switch (name.kind) {
                case 71 /* Identifier */:
                    return name.escapedText;
                case 9 /* StringLiteral */:
                case 8 /* NumericLiteral */:
                    return ts.escapeLeadingUnderscores(name.text);
                case 147 /* ComputedPropertyName */:
                    var nameExpression = name.expression;
                    if (isWellKnownSymbolSyntactically(nameExpression)) {
                        return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
                    }
                    else if (isStringOrNumericLiteralLike(nameExpression)) {
                        return ts.escapeLeadingUnderscores(nameExpression.text);
                    }
                    return undefined;
                default:
                    return ts.Debug.assertNever(name);
            }
        }
        ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
        function isPropertyNameLiteral(node) {
            switch (node.kind) {
                case 71 /* Identifier */:
                case 9 /* StringLiteral */:
                case 13 /* NoSubstitutionTemplateLiteral */:
                case 8 /* NumericLiteral */:
                    return true;
                default:
                    return false;
            }
        }
        ts.isPropertyNameLiteral = isPropertyNameLiteral;
        function getTextOfIdentifierOrLiteral(node) {
            return node.kind === 71 /* Identifier */ ? ts.idText(node) : node.text;
        }
        ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
        function getEscapedTextOfIdentifierOrLiteral(node) {
            return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
        }
        ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
        function getPropertyNameForKnownSymbolName(symbolName) {
            return "__@" + symbolName;
        }
        ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
        function isKnownSymbol(symbol) {
            return ts.startsWith(symbol.escapedName, "__@");
        }
        ts.isKnownSymbol = isKnownSymbol;
        /**
         * Includes the word "Symbol" with unicode escapes
         */
        function isESSymbolIdentifier(node) {
            return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol";
        }
        ts.isESSymbolIdentifier = isESSymbolIdentifier;
        function isPushOrUnshiftIdentifier(node) {
            return node.escapedText === "push" || node.escapedText === "unshift";
        }
        ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
        function isParameterDeclaration(node) {
            var root = getRootDeclaration(node);
            return root.kind === 149 /* Parameter */;
        }
        ts.isParameterDeclaration = isParameterDeclaration;
        function getRootDeclaration(node) {
            while (node.kind === 184 /* BindingElement */) {
                node = node.parent.parent;
            }
            return node;
        }
        ts.getRootDeclaration = getRootDeclaration;
        function nodeStartsNewLexicalEnvironment(node) {
            var kind = node.kind;
            return kind === 155 /* Constructor */
                || kind === 194 /* FunctionExpression */
                || kind === 237 /* FunctionDeclaration */
                || kind === 195 /* ArrowFunction */
                || kind === 154 /* MethodDeclaration */
                || kind === 156 /* GetAccessor */
                || kind === 157 /* SetAccessor */
                || kind === 242 /* ModuleDeclaration */
                || kind === 277 /* SourceFile */;
        }
        ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
        function nodeIsSynthesized(range) {
            return ts.positionIsSynthesized(range.pos)
                || ts.positionIsSynthesized(range.end);
        }
        ts.nodeIsSynthesized = nodeIsSynthesized;
        function getOriginalSourceFile(sourceFile) {
            return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
        }
        ts.getOriginalSourceFile = getOriginalSourceFile;
        var Associativity;
        (function (Associativity) {
            Associativity[Associativity["Left"] = 0] = "Left";
            Associativity[Associativity["Right"] = 1] = "Right";
        })(Associativity = ts.Associativity || (ts.Associativity = {}));
        function getExpressionAssociativity(expression) {
            var operator = getOperator(expression);
            var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined;
            return getOperatorAssociativity(expression.kind, operator, hasArguments);
        }
        ts.getExpressionAssociativity = getExpressionAssociativity;
        function getOperatorAssociativity(kind, operator, hasArguments) {
            switch (kind) {
                case 190 /* NewExpression */:
                    return hasArguments ? 0 /* Left */ : 1 /* Right */;
                case 200 /* PrefixUnaryExpression */:
                case 197 /* TypeOfExpression */:
                case 198 /* VoidExpression */:
                case 196 /* DeleteExpression */:
                case 199 /* AwaitExpression */:
                case 203 /* ConditionalExpression */:
                case 205 /* YieldExpression */:
                    return 1 /* Right */;
                case 202 /* BinaryExpression */:
                    switch (operator) {
                        case 40 /* AsteriskAsteriskToken */:
                        case 58 /* EqualsToken */:
                        case 59 /* PlusEqualsToken */:
                        case 60 /* MinusEqualsToken */:
                        case 62 /* AsteriskAsteriskEqualsToken */:
                        case 61 /* AsteriskEqualsToken */:
                        case 63 /* SlashEqualsToken */:
                        case 64 /* PercentEqualsToken */:
                        case 65 /* LessThanLessThanEqualsToken */:
                        case 66 /* GreaterThanGreaterThanEqualsToken */:
                        case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                        case 68 /* AmpersandEqualsToken */:
                        case 70 /* CaretEqualsToken */:
                        case 69 /* BarEqualsToken */:
                            return 1 /* Right */;
                    }
            }
            return 0 /* Left */;
        }
        ts.getOperatorAssociativity = getOperatorAssociativity;
        function getExpressionPrecedence(expression) {
            var operator = getOperator(expression);
            var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined;
            return getOperatorPrecedence(expression.kind, operator, hasArguments);
        }
        ts.getExpressionPrecedence = getExpressionPrecedence;
        function getOperator(expression) {
            if (expression.kind === 202 /* BinaryExpression */) {
                return expression.operatorToken.kind;
            }
            else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) {
                return expression.operator;
            }
            else {
                return expression.kind;
            }
        }
        ts.getOperator = getOperator;
        function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
            switch (nodeKind) {
                case 307 /* CommaListExpression */:
                    return 0;
                case 206 /* SpreadElement */:
                    return 1;
                case 205 /* YieldExpression */:
                    return 2;
                case 203 /* ConditionalExpression */:
                    return 4;
                case 202 /* BinaryExpression */:
                    switch (operatorKind) {
                        case 26 /* CommaToken */:
                            return 0;
                        case 58 /* EqualsToken */:
                        case 59 /* PlusEqualsToken */:
                        case 60 /* MinusEqualsToken */:
                        case 62 /* AsteriskAsteriskEqualsToken */:
                        case 61 /* AsteriskEqualsToken */:
                        case 63 /* SlashEqualsToken */:
                        case 64 /* PercentEqualsToken */:
                        case 65 /* LessThanLessThanEqualsToken */:
                        case 66 /* GreaterThanGreaterThanEqualsToken */:
                        case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                        case 68 /* AmpersandEqualsToken */:
                        case 70 /* CaretEqualsToken */:
                        case 69 /* BarEqualsToken */:
                            return 3;
                        default:
                            return getBinaryOperatorPrecedence(operatorKind);
                    }
                case 200 /* PrefixUnaryExpression */:
                case 197 /* TypeOfExpression */:
                case 198 /* VoidExpression */:
                case 196 /* DeleteExpression */:
                case 199 /* AwaitExpression */:
                    return 16;
                case 201 /* PostfixUnaryExpression */:
                    return 17;
                case 189 /* CallExpression */:
                    return 18;
                case 190 /* NewExpression */:
                    return hasArguments ? 19 : 18;
                case 191 /* TaggedTemplateExpression */:
                case 187 /* PropertyAccessExpression */:
                case 188 /* ElementAccessExpression */:
                    return 19;
                case 99 /* ThisKeyword */:
                case 97 /* SuperKeyword */:
                case 71 /* Identifier */:
                case 95 /* NullKeyword */:
                case 101 /* TrueKeyword */:
                case 86 /* FalseKeyword */:
                case 8 /* NumericLiteral */:
                case 9 /* StringLiteral */:
                case 185 /* ArrayLiteralExpression */:
                case 186 /* ObjectLiteralExpression */:
                case 194 /* FunctionExpression */:
                case 195 /* ArrowFunction */:
                case 207 /* ClassExpression */:
                case 258 /* JsxElement */:
                case 259 /* JsxSelfClosingElement */:
                case 262 /* JsxFragment */:
                case 12 /* RegularExpressionLiteral */:
                case 13 /* NoSubstitutionTemplateLiteral */:
                case 204 /* TemplateExpression */:
                case 193 /* ParenthesizedExpression */:
                case 208 /* OmittedExpression */:
                    return 20;
                default:
                    return -1;
            }
        }
        ts.getOperatorPrecedence = getOperatorPrecedence;
        /* @internal */
        function getBinaryOperatorPrecedence(kind) {
            switch (kind) {
                case 54 /* BarBarToken */:
                    return 5;
                case 53 /* AmpersandAmpersandToken */:
                    return 6;
                case 49 /* BarToken */:
                    return 7;
                case 50 /* CaretToken */:
                    return 8;
                case 48 /* AmpersandToken */:
                    return 9;
                case 32 /* EqualsEqualsToken */:
                case 33 /* ExclamationEqualsToken */:
                case 34 /* EqualsEqualsEqualsToken */:
                case 35 /* ExclamationEqualsEqualsToken */:
                    return 10;
                case 27 /* LessThanToken */:
                case 29 /* GreaterThanToken */:
                case 30 /* LessThanEqualsToken */:
                case 31 /* GreaterThanEqualsToken */:
                case 93 /* InstanceOfKeyword */:
                case 92 /* InKeyword */:
                case 118 /* AsKeyword */:
                    return 11;
                case 45 /* LessThanLessThanToken */:
                case 46 /* GreaterThanGreaterThanToken */:
                case 47 /* GreaterThanGreaterThanGreaterThanToken */:
                    return 12;
                case 37 /* PlusToken */:
                case 38 /* MinusToken */:
                    return 13;
                case 39 /* AsteriskToken */:
                case 41 /* SlashToken */:
                case 42 /* PercentToken */:
                    return 14;
                case 40 /* AsteriskAsteriskToken */:
                    return 15;
            }
            // -1 is lower than all other precedences.  Returning it will cause binary expression
            // parsing to stop.
            return -1;
        }
        ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
        function createDiagnosticCollection() {
            var nonFileDiagnostics = []; // See GH#19873
            var filesWithDiagnostics = [];
            var fileDiagnostics = ts.createMap();
            var hasReadNonFileDiagnostics = false;
            return {
                add: add,
                lookup: lookup,
                getGlobalDiagnostics: getGlobalDiagnostics,
                getDiagnostics: getDiagnostics,
                reattachFileDiagnostics: reattachFileDiagnostics
            };
            function reattachFileDiagnostics(newFile) {
                ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
            }
            function lookup(diagnostic) {
                var diagnostics;
                if (diagnostic.file) {
                    diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
                }
                else {
                    diagnostics = nonFileDiagnostics;
                }
                if (!diagnostics) {
                    return undefined;
                }
                var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation);
                if (result >= 0) {
                    return diagnostics[result];
                }
                return undefined;
            }
            function add(diagnostic) {
                var diagnostics;
                if (diagnostic.file) {
                    diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
                    if (!diagnostics) {
                        diagnostics = []; // See GH#19873
                        fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
                        ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
                    }
                }
                else {
                    // If we've already read the non-file diagnostics, do not modify the existing array.
                    if (hasReadNonFileDiagnostics) {
                        hasReadNonFileDiagnostics = false;
                        nonFileDiagnostics = nonFileDiagnostics.slice();
                    }
                    diagnostics = nonFileDiagnostics;
                }
                ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics);
            }
            function getGlobalDiagnostics() {
                hasReadNonFileDiagnostics = true;
                return nonFileDiagnostics;
            }
            function getDiagnostics(fileName) {
                if (fileName) {
                    return fileDiagnostics.get(fileName) || [];
                }
                var fileDiags = ts.flatMap(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
                if (!nonFileDiagnostics.length) {
                    return fileDiags;
                }
                fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
                return fileDiags;
            }
        }
        ts.createDiagnosticCollection = createDiagnosticCollection;
        // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
        // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
        // the language service. These characters should be escaped when printing, and if any characters are added,
        // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
        // There is no reason for this other than that JSON.stringify does not handle it either.
        var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
        var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
        var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
        var escapedCharsMap = ts.createMapFromTemplate({
            "\t": "\\t",
            "\v": "\\v",
            "\f": "\\f",
            "\b": "\\b",
            "\r": "\\r",
            "\n": "\\n",
            "\\": "\\\\",
            "\"": "\\\"",
            "\'": "\\\'",
            "\`": "\\\`",
            "\u2028": "\\u2028",
            "\u2029": "\\u2029",
            "\u0085": "\\u0085" // nextLine
        });
        /**
         * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
         * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
         * Note that this doesn't actually wrap the input in double quotes.
         */
        function escapeString(s, quoteChar) {
            var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
                quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
                    doubleQuoteEscapedCharsRegExp;
            return s.replace(escapedCharsRegExp, getReplacement);
        }
        ts.escapeString = escapeString;
        function getReplacement(c, offset, input) {
            if (c.charCodeAt(0) === 0 /* nullCharacter */) {
                var lookAhead = input.charCodeAt(offset + c.length);
                if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
                    // If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode)
                    return "\\x00";
                }
                // Otherwise, keep printing a literal \0 for the null character
                return "\\0";
            }
            return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0));
        }
        function isIntrinsicJsxName(name) {
            var ch = name.charCodeAt(0);
            return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1;
        }
        ts.isIntrinsicJsxName = isIntrinsicJsxName;
        function get16BitUnicodeEscapeSequence(charCode) {
            var hexCharCode = charCode.toString(16).toUpperCase();
            var paddedHexCode = ("0000" + hexCharCode).slice(-4);
            return "\\u" + paddedHexCode;
        }
        var nonAsciiCharacters = /[^\u0000-\u007F]/g;
        function escapeNonAsciiString(s, quoteChar) {
            s = escapeString(s, quoteChar);
            // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
            // Otherwise just return the original string.
            return nonAsciiCharacters.test(s) ?
                s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) :
                s;
        }
        ts.escapeNonAsciiString = escapeNonAsciiString;
        var indentStrings = ["", "    "];
        function getIndentString(level) {
            if (indentStrings[level] === undefined) {
                indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
            }
            return indentStrings[level];
        }
        ts.getIndentString = getIndentString;
        function getIndentSize() {
            return indentStrings[1].length;
        }
        ts.getIndentSize = getIndentSize;
        function createTextWriter(newLine) {
            var output;
            var indent;
            var lineStart;
            var lineCount;
            var linePos;
            function updateLineCountAndPosFor(s) {
                var lineStartsOfS = ts.computeLineStarts(s);
                if (lineStartsOfS.length > 1) {
                    lineCount = lineCount + lineStartsOfS.length - 1;
                    linePos = output.length - s.length + ts.last(lineStartsOfS);
                    lineStart = (linePos - output.length) === 0;
                }
                else {
                    lineStart = false;
                }
            }
            function write(s) {
                if (s && s.length) {
                    if (lineStart) {
                        s = getIndentString(indent) + s;
                        lineStart = false;
                    }
                    output += s;
                    updateLineCountAndPosFor(s);
                }
            }
            function reset() {
                output = "";
                indent = 0;
                lineStart = true;
                lineCount = 0;
                linePos = 0;
            }
            function rawWrite(s) {
                if (s !== undefined) {
                    output += s;
                    updateLineCountAndPosFor(s);
                }
            }
            function writeLiteral(s) {
                if (s && s.length) {
                    write(s);
                }
            }
            function writeLine() {
                if (!lineStart) {
                    output += newLine;
                    lineCount++;
                    linePos = output.length;
                    lineStart = true;
                }
            }
            function writeTextOfNode(text, node) {
                var s = getTextOfNodeFromSourceText(text, node);
                write(s);
                updateLineCountAndPosFor(s);
            }
            reset();
            return {
                write: write,
                rawWrite: rawWrite,
                writeTextOfNode: writeTextOfNode,
                writeLiteral: writeLiteral,
                writeLine: writeLine,
                increaseIndent: function () { indent++; },
                decreaseIndent: function () { indent--; },
                getIndent: function () { return indent; },
                getTextPos: function () { return output.length; },
                getLine: function () { return lineCount; },
                getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
                getText: function () { return output; },
                isAtStartOfLine: function () { return lineStart; },
                clear: reset,
                reportInaccessibleThisError: ts.noop,
                reportPrivateInBaseOfClassExpression: ts.noop,
                reportInaccessibleUniqueSymbolError: ts.noop,
                trackSymbol: ts.noop,
                writeKeyword: write,
                writeOperator: write,
                writeParameter: write,
                writeProperty: write,
                writePunctuation: write,
                writeSpace: write,
                writeStringLiteral: write,
                writeSymbol: write
            };
        }
        ts.createTextWriter = createTextWriter;
        function getResolvedExternalModuleName(host, file, referenceFile) {
            return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
        }
        ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
        function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
            var file = resolver.getExternalModuleFileFromDeclaration(declaration);
            if (!file || file.isDeclarationFile) {
                return undefined;
            }
            return getResolvedExternalModuleName(host, file);
        }
        ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
        /**
         * Resolves a local path to a path which is absolute to the base of the emit
         */
        function getExternalModuleNameFromPath(host, fileName, referencePath) {
            var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
            var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
            var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
            var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
            var extensionless = ts.removeFileExtension(relativePath);
            return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
        }
        ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
        function getOwnEmitOutputFilePath(fileName, host, extension) {
            var compilerOptions = host.getCompilerOptions();
            var emitOutputFilePathWithoutExtension;
            if (compilerOptions.outDir) {
                emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
            }
            else {
                emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName);
            }
            return emitOutputFilePathWithoutExtension + extension;
        }
        ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
        function getDeclarationEmitOutputFilePath(fileName, host) {
            return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
        }
        ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
        function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
            var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
            var path = outputDir
                ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
                : fileName;
            return ts.removeFileExtension(path) + ".d.ts" /* Dts */;
        }
        ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
        /**
         * Gets the source files that are expected to have an emit output.
         *
         * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
         * transformations.
         *
         * @param host An EmitHost.
         * @param targetSourceFile An optional target source file to emit.
         */
        function getSourceFilesToEmit(host, targetSourceFile) {
            var options = host.getCompilerOptions();
            var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
            if (options.outFile || options.out) {
                var moduleKind = ts.getEmitModuleKind(options);
                var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
                // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
                return ts.filter(host.getSourceFiles(), function (sourceFile) {
                    return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
                });
            }
            else {
                var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
                return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
            }
        }
        ts.getSourceFilesToEmit = getSourceFilesToEmit;
        /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
        function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
            return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
        }
        ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
        function getSourceFilePathInNewDir(fileName, host, newDirPath) {
            return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
        }
        ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
        function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
            var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
            var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
            sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
            return ts.combinePaths(newDirPath, sourceFilePath);
        }
        ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
        function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
            host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
                diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
            }, sourceFiles);
        }
        ts.writeFile = writeFile;
        function getLineOfLocalPosition(currentSourceFile, pos) {
            return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line;
        }
        ts.getLineOfLocalPosition = getLineOfLocalPosition;
        function getLineOfLocalPositionFromLineMap(lineMap, pos) {
            return ts.computeLineAndCharacterOfPosition(lineMap, pos).line;
        }
        ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
        function getFirstConstructorWithBody(node) {
            return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
        }
        ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
        function getSetAccessorValueParameter(accessor) {
            if (accessor && accessor.parameters.length > 0) {
                var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
                return accessor.parameters[hasThis ? 1 : 0];
            }
        }
        /** Get the type annotation for the value parameter. */
        function getSetAccessorTypeAnnotationNode(accessor) {
            var parameter = getSetAccessorValueParameter(accessor);
            return parameter && parameter.type;
        }
        ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
        function getThisParameter(signature) {
            // callback tags do not currently support this parameters
            if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
                var thisParameter = signature.parameters[0];
                if (parameterIsThisKeyword(thisParameter)) {
                    return thisParameter;
                }
            }
        }
        ts.getThisParameter = getThisParameter;
        function parameterIsThisKeyword(parameter) {
            return isThisIdentifier(parameter.name);
        }
        ts.parameterIsThisKeyword = parameterIsThisKeyword;
        function isThisIdentifier(node) {
            return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node);
        }
        ts.isThisIdentifier = isThisIdentifier;
        function identifierIsThisKeyword(id) {
            return id.originalKeywordKind === 99 /* ThisKeyword */;
        }
        ts.identifierIsThisKeyword = identifierIsThisKeyword;
        function getAllAccessorDeclarations(declarations, accessor) {
            // TODO: GH#18217
            var firstAccessor;
            var secondAccessor;
            var getAccessor;
            var setAccessor;
            if (hasDynamicName(accessor)) {
                firstAccessor = accessor;
                if (accessor.kind === 156 /* GetAccessor */) {
                    getAccessor = accessor;
                }
                else if (accessor.kind === 157 /* SetAccessor */) {
                    setAccessor = accessor;
                }
                else {
                    ts.Debug.fail("Accessor has wrong kind");
                }
            }
            else {
                ts.forEach(declarations, function (member) {
                    if (ts.isAccessor(member)
                        && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
                        var memberName = getPropertyNameForPropertyNameNode(member.name);
                        var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
                        if (memberName === accessorName) {
                            if (!firstAccessor) {
                                firstAccessor = member;
                            }
                            else if (!secondAccessor) {
                                secondAccessor = member;
                            }
                            if (member.kind === 156 /* GetAccessor */ && !getAccessor) {
                                getAccessor = member;
                            }
                            if (member.kind === 157 /* SetAccessor */ && !setAccessor) {
                                setAccessor = member;
                            }
                        }
                    }
                });
            }
            return {
                firstAccessor: firstAccessor,
                secondAccessor: secondAccessor,
                getAccessor: getAccessor,
                setAccessor: setAccessor
            };
        }
        ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
        /**
         * Gets the effective type annotation of a variable, parameter, or property. If the node was
         * parsed in a JavaScript file, gets the type annotation from JSDoc.
         */
        function getEffectiveTypeAnnotationNode(node) {
            var type = node.type;
            if (type || !isInJSFile(node))
                return type;
            return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
        }
        ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
        function getTypeAnnotationNode(node) {
            return node.type;
        }
        ts.getTypeAnnotationNode = getTypeAnnotationNode;
        /**
         * Gets the effective return type annotation of a signature. If the node was parsed in a
         * JavaScript file, gets the return type annotation from JSDoc.
         */
        function getEffectiveReturnTypeNode(node) {
            return ts.isJSDocSignature(node) ?
                node.type && node.type.typeExpression && node.type.typeExpression.type :
                node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
        }
        ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
        function getJSDocTypeParameterDeclarations(node) {
            return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
        }
        ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
        /** template tags are only available when a typedef isn't already using them */
        function isNonTypeAliasTemplate(tag) {
            return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
        }
        /**
         * Gets the effective type annotation of the value parameter of a set accessor. If the node
         * was parsed in a JavaScript file, gets the type annotation from JSDoc.
         */
        function getEffectiveSetAccessorTypeAnnotationNode(node) {
            var parameter = getSetAccessorValueParameter(node);
            return parameter && getEffectiveTypeAnnotationNode(parameter);
        }
        ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
        function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
            emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
        }
        ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
        function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
            // If the leading comments start on different line than the start of node, write new line
            if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
                getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
                writer.writeLine();
            }
        }
        ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
        function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
            // If the leading comments start on different line than the start of node, write new line
            if (pos !== commentPos &&
                getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
                writer.writeLine();
            }
        }
        ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
        function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
            if (comments && comments.length > 0) {
                if (leadingSeparator) {
                    writer.write(" ");
                }
                var emitInterveningSeparator = false;
                for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
                    var comment = comments_1[_i];
                    if (emitInterveningSeparator) {
                        writer.write(" ");
                        emitInterveningSeparator = false;
                    }
                    writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
                    if (comment.hasTrailingNewLine) {
                        writer.writeLine();
                    }
                    else {
                        emitInterveningSeparator = true;
                    }
                }
                if (emitInterveningSeparator && trailingSeparator) {
                    writer.write(" ");
                }
            }
        }
        ts.emitComments = emitComments;
        /**
         * Detached comment is a comment at the top of file or function body that is separated from
         * the next statement by space.
         */
        function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
            var leadingComments;
            var currentDetachedCommentInfo;
            if (removeComments) {
                // removeComments is true, only reserve pinned comment at the top of file
                // For example:
                //      /*! Pinned Comment */
                //
                //      var x = 10;
                if (node.pos === 0) {
                    leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
                }
            }
            else {
                // removeComments is false, just get detached as normal and bypass the process to filter comment
                leadingComments = ts.getLeadingCommentRanges(text, node.pos);
            }
            if (leadingComments) {
                var detachedComments = [];
                var lastComment = void 0;
                for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
                    var comment = leadingComments_1[_i];
                    if (lastComment) {
                        var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
                        var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
                        if (commentLine >= lastCommentLine + 2) {
                            // There was a blank line between the last comment and this comment.  This
                            // comment is not part of the copyright comments.  Return what we have so
                            // far.
                            break;
                        }
                    }
                    detachedComments.push(comment);
                    lastComment = comment;
                }
                if (detachedComments.length) {
                    // All comments look like they could have been part of the copyright header.  Make
                    // sure there is at least one blank line between it and the node.  If not, it's not
                    // a copyright header.
                    var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
                    var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
                    if (nodeLine >= lastCommentLine + 2) {
                        // Valid detachedComments
                        emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
                        emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
                        currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
                    }
                }
            }
            return currentDetachedCommentInfo;
            function isPinnedCommentLocal(comment) {
                return isPinnedComment(text, comment.pos);
            }
        }
        ts.emitDetachedComments = emitDetachedComments;
        function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
            if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
                var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
                var lineCount = lineMap.length;
                var firstCommentLineIndent = void 0;
                for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
                    var nextLineStart = (currentLine + 1) === lineCount
                        ? text.length + 1
                        : lineMap[currentLine + 1];
                    if (pos !== commentPos) {
                        // If we are not emitting first line, we need to write the spaces to adjust the alignment
                        if (firstCommentLineIndent === undefined) {
                            firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
                        }
                        // These are number of spaces writer is going to write at current indent
                        var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
                        // Number of spaces we want to be writing
                        // eg: Assume writer indent
                        // module m {
                        //         /* starts at character 9 this is line 1
                        //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
                        //   More left indented comment */                            --2  = 8 - 8 + 2
                        //     class c { }
                        // }
                        // module m {
                        //     /* this is line 1 -- Assume current writer indent 8
                        //      * line                                                --3 = 8 - 4 + 5
                        //            More right indented comment */                  --4 = 8 - 4 + 11
                        //     class c { }
                        // }
                        var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
                        if (spacesToEmit > 0) {
                            var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
                            var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
                            // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
                            writer.rawWrite(indentSizeSpaceString);
                            // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
                            while (numberOfSingleSpacesToEmit) {
                                writer.rawWrite(" ");
                                numberOfSingleSpacesToEmit--;
                            }
                        }
                        else {
                            // No spaces to emit write empty string
                            writer.rawWrite("");
                        }
                    }
                    // Write the comment line text
                    writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
                    pos = nextLineStart;
                }
            }
            else {
                // Single line comment of style //....
                writer.write(text.substring(commentPos, commentEnd));
            }
        }
        ts.writeCommentRange = writeCommentRange;
        function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
            var end = Math.min(commentEnd, nextLineStart - 1);
            var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
            if (currentLineText) {
                // trimmed forward and ending spaces text
                writer.write(currentLineText);
                if (end !== commentEnd) {
                    writer.writeLine();
                }
            }
            else {
                // Empty string - make sure we write empty line
                writer.writeLiteral(newLine);
            }
        }
        function calculateIndent(text, pos, end) {
            var currentLineIndent = 0;
            for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
                if (text.charCodeAt(pos) === 9 /* tab */) {
                    // Tabs = TabSize = indent size and go to next tabStop
                    currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
                }
                else {
                    // Single space
                    currentLineIndent++;
                }
            }
            return currentLineIndent;
        }
        function hasModifiers(node) {
            return getModifierFlags(node) !== 0 /* None */;
        }
        ts.hasModifiers = hasModifiers;
        function hasModifier(node, flags) {
            return !!getSelectedModifierFlags(node, flags);
        }
        ts.hasModifier = hasModifier;
        function hasStaticModifier(node) {
            return hasModifier(node, 32 /* Static */);
        }
        ts.hasStaticModifier = hasStaticModifier;
        function hasReadonlyModifier(node) {
            return hasModifier(node, 64 /* Readonly */);
        }
        ts.hasReadonlyModifier = hasReadonlyModifier;
        function getSelectedModifierFlags(node, flags) {
            return getModifierFlags(node) & flags;
        }
        ts.getSelectedModifierFlags = getSelectedModifierFlags;
        function getModifierFlags(node) {
            if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
                return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
            }
            var flags = getModifierFlagsNoCache(node);
            node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
            return flags;
        }
        ts.getModifierFlags = getModifierFlags;
        function getModifierFlagsNoCache(node) {
            var flags = 0 /* None */;
            if (node.modifiers) {
                for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
                    var modifier = _a[_i];
                    flags |= modifierToFlag(modifier.kind);
                }
            }
            if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) {
                flags |= 1 /* Export */;
            }
            return flags;
        }
        ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
        function modifierToFlag(token) {
            switch (token) {
                case 115 /* StaticKeyword */: return 32 /* Static */;
                case 114 /* PublicKeyword */: return 4 /* Public */;
                case 113 /* ProtectedKeyword */: return 16 /* Protected */;
                case 112 /* PrivateKeyword */: return 8 /* Private */;
                case 117 /* AbstractKeyword */: return 128 /* Abstract */;
                case 84 /* ExportKeyword */: return 1 /* Export */;
                case 124 /* DeclareKeyword */: return 2 /* Ambient */;
                case 76 /* ConstKeyword */: return 2048 /* Const */;
                case 79 /* DefaultKeyword */: return 512 /* Default */;
                case 120 /* AsyncKeyword */: return 256 /* Async */;
                case 132 /* ReadonlyKeyword */: return 64 /* Readonly */;
            }
            return 0 /* None */;
        }
        ts.modifierToFlag = modifierToFlag;
        function isLogicalOperator(token) {
            return token === 54 /* BarBarToken */
                || token === 53 /* AmpersandAmpersandToken */
                || token === 51 /* ExclamationToken */;
        }
        ts.isLogicalOperator = isLogicalOperator;
        function isAssignmentOperator(token) {
            return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */;
        }
        ts.isAssignmentOperator = isAssignmentOperator;
        /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
        function tryGetClassExtendingExpressionWithTypeArguments(node) {
            if (ts.isExpressionWithTypeArguments(node) &&
                node.parent.token === 85 /* ExtendsKeyword */ &&
                ts.isClassLike(node.parent.parent)) {
                return node.parent.parent;
            }
        }
        ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
        function isAssignmentExpression(node, excludeCompoundAssignment) {
            return ts.isBinaryExpression(node)
                && (excludeCompoundAssignment
                    ? node.operatorToken.kind === 58 /* EqualsToken */
                    : isAssignmentOperator(node.operatorToken.kind))
                && ts.isLeftHandSideExpression(node.left);
        }
        ts.isAssignmentExpression = isAssignmentExpression;
        function isDestructuringAssignment(node) {
            if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
                var kind = node.left.kind;
                return kind === 186 /* ObjectLiteralExpression */
                    || kind === 185 /* ArrayLiteralExpression */;
            }
            return false;
        }
        ts.isDestructuringAssignment = isDestructuringAssignment;
        function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
            return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
        }
        ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
        function isExpressionWithTypeArgumentsInClassImplementsClause(node) {
            return node.kind === 209 /* ExpressionWithTypeArguments */
                && isEntityNameExpression(node.expression)
                && node.parent
                && node.parent.token === 108 /* ImplementsKeyword */
                && node.parent.parent
                && ts.isClassLike(node.parent.parent);
        }
        ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause;
        function isEntityNameExpression(node) {
            return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
        }
        ts.isEntityNameExpression = isEntityNameExpression;
        function isPropertyAccessEntityNameExpression(node) {
            return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression);
        }
        ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
        function isPrototypeAccess(node) {
            return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype";
        }
        ts.isPrototypeAccess = isPrototypeAccess;
        function isRightSideOfQualifiedNameOrPropertyAccess(node) {
            return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) ||
                (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node);
        }
        ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
        function isEmptyObjectLiteral(expression) {
            return expression.kind === 186 /* ObjectLiteralExpression */ &&
                expression.properties.length === 0;
        }
        ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
        function isEmptyArrayLiteral(expression) {
            return expression.kind === 185 /* ArrayLiteralExpression */ &&
                expression.elements.length === 0;
        }
        ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
        function getLocalSymbolForExportDefault(symbol) {
            return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
        }
        ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
        function isExportDefaultSymbol(symbol) {
            return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
        }
        /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
        function tryExtractTSExtension(fileName) {
            return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
        }
        ts.tryExtractTSExtension = tryExtractTSExtension;
        /**
         * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
         * representing the UTF-8 encoding of the character, and return the expanded char code list.
         */
        function getExpandedCharCodes(input) {
            var output = [];
            var length = input.length;
            for (var i = 0; i < length; i++) {
                var charCode = input.charCodeAt(i);
                // handle utf8
                if (charCode < 0x80) {
                    output.push(charCode);
                }
                else if (charCode < 0x800) {
                    output.push((charCode >> 6) | 192);
                    output.push((charCode & 63) | 128);
                }
                else if (charCode < 0x10000) {
                    output.push((charCode >> 12) | 224);
                    output.push(((charCode >> 6) & 63) | 128);
                    output.push((charCode & 63) | 128);
                }
                else if (charCode < 0x20000) {
                    output.push((charCode >> 18) | 240);
                    output.push(((charCode >> 12) & 63) | 128);
                    output.push(((charCode >> 6) & 63) | 128);
                    output.push((charCode & 63) | 128);
                }
                else {
                    ts.Debug.assert(false, "Unexpected code point");
                }
            }
            return output;
        }
        var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        /**
         * Converts a string to a base-64 encoded ASCII string.
         */
        function convertToBase64(input) {
            var result = "";
            var charCodes = getExpandedCharCodes(input);
            var i = 0;
            var length = charCodes.length;
            var byte1, byte2, byte3, byte4;
            while (i < length) {
                // Convert every 6-bits in the input 3 character points
                // into a base64 digit
                byte1 = charCodes[i] >> 2;
                byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
                byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
                byte4 = charCodes[i + 2] & 63;
                // We are out of characters in the input, set the extra
                // digits to 64 (padding character).
                if (i + 1 >= length) {
                    byte3 = byte4 = 64;
                }
                else if (i + 2 >= length) {
                    byte4 = 64;
                }
                // Write to the output
                result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
                i += 3;
            }
            return result;
        }
        ts.convertToBase64 = convertToBase64;
        function getStringFromExpandedCharCodes(codes) {
            var output = "";
            var i = 0;
            var length = codes.length;
            while (i < length) {
                var charCode = codes[i];
                if (charCode < 0x80) {
                    output += String.fromCharCode(charCode);
                    i++;
                }
                else if ((charCode & 192) === 192) {
                    var value = charCode & 63;
                    i++;
                    var nextCode = codes[i];
                    while ((nextCode & 192) === 128) {
                        value = (value << 6) | (nextCode & 63);
                        i++;
                        nextCode = codes[i];
                    }
                    // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
                    output += String.fromCharCode(value);
                }
                else {
                    // We don't want to kill the process when decoding fails (due to a following char byte not
                    // following a leading char), so we just print the (bad) value
                    output += String.fromCharCode(charCode);
                    i++;
                }
            }
            return output;
        }
        function base64encode(host, input) {
            if (host && host.base64encode) {
                return host.base64encode(input);
            }
            return convertToBase64(input);
        }
        ts.base64encode = base64encode;
        function base64decode(host, input) {
            if (host && host.base64decode) {
                return host.base64decode(input);
            }
            var length = input.length;
            var expandedCharCodes = [];
            var i = 0;
            while (i < length) {
                // Stop decoding once padding characters are present
                if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
                    break;
                }
                // convert 4 input digits into three characters, ignoring padding characters at the end
                var ch1 = base64Digits.indexOf(input[i]);
                var ch2 = base64Digits.indexOf(input[i + 1]);
                var ch3 = base64Digits.indexOf(input[i + 2]);
                var ch4 = base64Digits.indexOf(input[i + 3]);
                var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
                var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
                var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
                if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
                    expandedCharCodes.push(code1);
                }
                else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
                    expandedCharCodes.push(code1, code2);
                }
                else {
                    expandedCharCodes.push(code1, code2, code3);
                }
                i += 4;
            }
            return getStringFromExpandedCharCodes(expandedCharCodes);
        }
        ts.base64decode = base64decode;
        function readJson(path, host) {
            try {
                var jsonText = host.readFile(path);
                if (!jsonText)
                    return {};
                var result = ts.parseConfigFileTextToJson(path, jsonText);
                if (result.error) {
                    return {};
                }
                return result.config;
            }
            catch (e) {
                // gracefully handle if readFile fails or returns not JSON
                return {};
            }
        }
        ts.readJson = readJson;
        function directoryProbablyExists(directoryName, host) {
            // if host does not support 'directoryExists' assume that directory will exist
            return !host.directoryExists || host.directoryExists(directoryName);
        }
        ts.directoryProbablyExists = directoryProbablyExists;
        var carriageReturnLineFeed = "\r\n";
        var lineFeed = "\n";
        function getNewLineCharacter(options, getNewLine) {
            switch (options.newLine) {
                case 0 /* CarriageReturnLineFeed */:
                    return carriageReturnLineFeed;
                case 1 /* LineFeed */:
                    return lineFeed;
            }
            return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
        }
        ts.getNewLineCharacter = getNewLineCharacter;
        /**
         * Formats an enum value as a string for debugging and debug assertions.
         */
        function formatEnum(value, enumObject, isFlags) {
            if (value === void 0) {
                value = 0;
            }
            var members = getEnumMembers(enumObject);
            if (value === 0) {
                return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
            }
            if (isFlags) {
                var result = "";
                var remainingFlags = value;
                for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) {
                    var _a = members[i], enumValue = _a[0], enumName = _a[1];
                    if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) {
                        remainingFlags &= ~enumValue;
                        result = "" + enumName + (result ? ", " : "") + result;
                    }
                }
                if (remainingFlags === 0) {
                    return result;
                }
            }
            else {
                for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
                    var _b = members_1[_i], enumValue = _b[0], enumName = _b[1];
                    if (enumValue === value) {
                        return enumName;
                    }
                }
            }
            return value.toString();
        }
        function getEnumMembers(enumObject) {
            var result = [];
            for (var name in enumObject) {
                var value = enumObject[name];
                if (typeof value === "number") {
                    result.push([value, name]);
                }
            }
            return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
        }
        function formatSyntaxKind(kind) {
            return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
        }
        ts.formatSyntaxKind = formatSyntaxKind;
        function formatModifierFlags(flags) {
            return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
        }
        ts.formatModifierFlags = formatModifierFlags;
        function formatTransformFlags(flags) {
            return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
        }
        ts.formatTransformFlags = formatTransformFlags;
        function formatEmitFlags(flags) {
            return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
        }
        ts.formatEmitFlags = formatEmitFlags;
        function formatSymbolFlags(flags) {
            return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
        }
        ts.formatSymbolFlags = formatSymbolFlags;
        function formatTypeFlags(flags) {
            return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
        }
        ts.formatTypeFlags = formatTypeFlags;
        function formatObjectFlags(flags) {
            return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
        }
        ts.formatObjectFlags = formatObjectFlags;
        /**
         * Creates a new TextRange from the provided pos and end.
         *
         * @param pos The start position.
         * @param end The end position.
         */
        function createRange(pos, end) {
            if (end === void 0) {
                end = pos;
            }
            ts.Debug.assert(end >= pos || end === -1);
            return { pos: pos, end: end };
        }
        ts.createRange = createRange;
        /**
         * Creates a new TextRange from a provided range with a new end position.
         *
         * @param range A TextRange.
         * @param end The new end position.
         */
        function moveRangeEnd(range, end) {
            return createRange(range.pos, end);
        }
        ts.moveRangeEnd = moveRangeEnd;
        /**
         * Creates a new TextRange from a provided range with a new start position.
         *
         * @param range A TextRange.
         * @param pos The new Start position.
         */
        function moveRangePos(range, pos) {
            return createRange(pos, range.end);
        }
        ts.moveRangePos = moveRangePos;
        /**
         * Moves the start position of a range past any decorators.
         */
        function moveRangePastDecorators(node) {
            return node.decorators && node.decorators.length > 0
                ? moveRangePos(node, node.decorators.end)
                : node;
        }
        ts.moveRangePastDecorators = moveRangePastDecorators;
        /**
         * Moves the start position of a range past any decorators or modifiers.
         */
        function moveRangePastModifiers(node) {
            return node.modifiers && node.modifiers.length > 0
                ? moveRangePos(node, node.modifiers.end)
                : moveRangePastDecorators(node);
        }
        ts.moveRangePastModifiers = moveRangePastModifiers;
        /**
         * Determines whether a TextRange has the same start and end positions.
         *
         * @param range A TextRange.
         */
        function isCollapsedRange(range) {
            return range.pos === range.end;
        }
        ts.isCollapsedRange = isCollapsedRange;
        /**
         * Creates a new TextRange for a token at the provides start position.
         *
         * @param pos The start position.
         * @param token The token.
         */
        function createTokenRange(pos, token) {
            return createRange(pos, pos + ts.tokenToString(token).length);
        }
        ts.createTokenRange = createTokenRange;
        function rangeIsOnSingleLine(range, sourceFile) {
            return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
        }
        ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
        function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
            return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile);
        }
        ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
        function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
            return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
        }
        ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
        function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
            return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile);
        }
        ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
        function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
            return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile);
        }
        ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
        function positionsAreOnSameLine(pos1, pos2, sourceFile) {
            return pos1 === pos2 ||
                getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2);
        }
        ts.positionsAreOnSameLine = positionsAreOnSameLine;
        function getStartPositionOfRange(range, sourceFile) {
            return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos);
        }
        ts.getStartPositionOfRange = getStartPositionOfRange;
        /**
         * Determines whether a name was originally the declaration name of an enum or namespace
         * declaration.
         */
        function isDeclarationNameOfEnumOrNamespace(node) {
            var parseNode = ts.getParseTreeNode(node);
            if (parseNode) {
                switch (parseNode.parent.kind) {
                    case 241 /* EnumDeclaration */:
                    case 242 /* ModuleDeclaration */:
                        return parseNode === parseNode.parent.name;
                }
            }
            return false;
        }
        ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
        function getInitializedVariables(node) {
            return ts.filter(node.declarations, isInitializedVariable);
        }
        ts.getInitializedVariables = getInitializedVariables;
        function isInitializedVariable(node) {
            return node.initializer !== undefined;
        }
        function isWatchSet(options) {
            // Firefox has Object.prototype.watch
            return options.watch && options.hasOwnProperty("watch");
        }
        ts.isWatchSet = isWatchSet;
        function closeFileWatcher(watcher) {
            watcher.close();
        }
        ts.closeFileWatcher = closeFileWatcher;
        function getCheckFlags(symbol) {
            return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
        }
        ts.getCheckFlags = getCheckFlags;
        function getDeclarationModifierFlagsFromSymbol(s) {
            if (s.valueDeclaration) {
                var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
                return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
            }
            if (getCheckFlags(s) & 6 /* Synthetic */) {
                var checkFlags = s.checkFlags;
                var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ :
                    checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ :
                        16 /* Protected */;
                var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0;
                return accessModifier | staticModifier;
            }
            if (s.flags & 4194304 /* Prototype */) {
                return 4 /* Public */ | 32 /* Static */;
            }
            return 0;
        }
        ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
        function skipAlias(symbol, checker) {
            return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
        }
        ts.skipAlias = skipAlias;
        /** See comment on `declareModuleMember` in `binder.ts`. */
        function getCombinedLocalAndExportSymbolFlags(symbol) {
            return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
        }
        ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
        function isWriteOnlyAccess(node) {
            return accessKind(node) === 1 /* Write */;
        }
        ts.isWriteOnlyAccess = isWriteOnlyAccess;
        function isWriteAccess(node) {
            return accessKind(node) !== 0 /* Read */;
        }
        ts.isWriteAccess = isWriteAccess;
        var AccessKind;
        (function (AccessKind) {
            /** Only reads from a variable. */
            AccessKind[AccessKind["Read"] = 0] = "Read";
            /** Only writes to a variable without using the result. E.g.: `x++;`. */
            AccessKind[AccessKind["Write"] = 1] = "Write";
            /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
            AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
        })(AccessKind || (AccessKind = {}));
        function accessKind(node) {
            var parent = node.parent;
            if (!parent)
                return 0 /* Read */;
            switch (parent.kind) {
                case 193 /* ParenthesizedExpression */:
                    return accessKind(parent);
                case 201 /* PostfixUnaryExpression */:
                case 200 /* PrefixUnaryExpression */:
                    var operator = parent.operator;
                    return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
                case 202 /* BinaryExpression */:
                    var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
                    return left === node && isAssignmentOperator(operatorToken.kind) ?
                        operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
                        : 0 /* Read */;
                case 187 /* PropertyAccessExpression */:
                    return parent.name !== node ? 0 /* Read */ : accessKind(parent);
                case 273 /* PropertyAssignment */: {
                    var parentAccess = accessKind(parent.parent);
                    // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
                    return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
                }
                case 274 /* ShorthandPropertyAssignment */:
                    // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
                    return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
                case 185 /* ArrayLiteralExpression */:
                    return accessKind(parent);
                default:
                    return 0 /* Read */;
            }
            function writeOrReadWrite() {
                // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
                return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
            }
        }
        function reverseAccessKind(a) {
            switch (a) {
                case 0 /* Read */:
                    return 1 /* Write */;
                case 1 /* Write */:
                    return 0 /* Read */;
                case 2 /* ReadWrite */:
                    return 2 /* ReadWrite */;
                default:
                    return ts.Debug.assertNever(a);
            }
        }
        function compareDataObjects(dst, src) {
            if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
                return false;
            }
            for (var e in dst) {
                if (typeof dst[e] === "object") {
                    if (!compareDataObjects(dst[e], src[e])) {
                        return false;
                    }
                }
                else if (typeof dst[e] !== "function") {
                    if (dst[e] !== src[e]) {
                        return false;
                    }
                }
            }
            return true;
        }
        ts.compareDataObjects = compareDataObjects;
        /**
         * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
         */
        function clearMap(map, onDeleteValue) {
            // Remove all
            map.forEach(onDeleteValue);
            map.clear();
        }
        ts.clearMap = clearMap;
        /**
         * Mutates the map with newMap such that keys in map will be same as newMap.
         */
        function mutateMap(map, newMap, options) {
            var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
            // Needs update
            map.forEach(function (existingValue, key) {
                var valueInNewMap = newMap.get(key);
                // Not present any more in new map, remove it
                if (valueInNewMap === undefined) {
                    map.delete(key);
                    onDeleteValue(existingValue, key);
                }
                // If present notify about existing values
                else if (onExistingValue) {
                    onExistingValue(existingValue, valueInNewMap, key);
                }
            });
            // Add new values that are not already present
            newMap.forEach(function (valueInNewMap, key) {
                if (!map.has(key)) {
                    // New values
                    map.set(key, createNewValue(key, valueInNewMap));
                }
            });
        }
        ts.mutateMap = mutateMap;
        /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
        function forEachAncestorDirectory(directory, callback) {
            while (true) {
                var result = callback(directory);
                if (result !== undefined) {
                    return result;
                }
                var parentPath = ts.getDirectoryPath(directory);
                if (parentPath === directory) {
                    return undefined;
                }
                directory = parentPath;
            }
        }
        ts.forEachAncestorDirectory = forEachAncestorDirectory;
        // Return true if the given type is the constructor type for an abstract class
        function isAbstractConstructorType(type) {
            return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
        }
        ts.isAbstractConstructorType = isAbstractConstructorType;
        function isAbstractConstructorSymbol(symbol) {
            if (symbol.flags & 32 /* Class */) {
                var declaration = getClassLikeDeclarationOfSymbol(symbol);
                return !!declaration && hasModifier(declaration, 128 /* Abstract */);
            }
            return false;
        }
        ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
        function getClassLikeDeclarationOfSymbol(symbol) {
            return ts.find(symbol.declarations, ts.isClassLike);
        }
        ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
        function getObjectFlags(type) {
            return type.flags & 131072 /* Object */ ? type.objectFlags : 0;
        }
        ts.getObjectFlags = getObjectFlags;
        function typeHasCallOrConstructSignatures(type, checker) {
            return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
        }
        ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
        function forSomeAncestorDirectory(directory, callback) {
            return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
        }
        ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
        function isUMDExportSymbol(symbol) {
            return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
        }
        ts.isUMDExportSymbol = isUMDExportSymbol;
        function showModuleSpecifier(_a) {
            var moduleSpecifier = _a.moduleSpecifier;
            return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
        }
        ts.showModuleSpecifier = showModuleSpecifier;
        function getLastChild(node) {
            var lastChild;
            ts.forEachChild(node, function (child) {
                if (nodeIsPresent(child))
                    lastChild = child;
            }, function (children) {
                // As an optimization, jump straight to the end of the list.
                for (var i = children.length - 1; i >= 0; i--) {
                    if (nodeIsPresent(children[i])) {
                        lastChild = children[i];
                        break;
                    }
                }
            });
            return lastChild;
        }
        ts.getLastChild = getLastChild;
        function addToSeen(seen, key, value) {
            if (value === void 0) {
                value = true;
            }
            key = String(key);
            if (seen.has(key)) {
                return false;
            }
            seen.set(key, value);
            return true;
        }
        ts.addToSeen = addToSeen;
        function isObjectTypeDeclaration(node) {
            return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
        }
        ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
    })(ts || (ts = {}));
    (function (ts) {
        function getDefaultLibFileName(options) {
            switch (options.target) {
                case 6 /* ESNext */:
                    return "lib.esnext.full.d.ts";
                case 5 /* ES2018 */:
                    return "lib.es2018.full.d.ts";
                case 4 /* ES2017 */:
                    return "lib.es2017.full.d.ts";
                case 3 /* ES2016 */:
                    return "lib.es2016.full.d.ts";
                case 2 /* ES2015 */:
                    return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
                default:
                    return "lib.d.ts";
            }
        }
        ts.getDefaultLibFileName = getDefaultLibFileName;
        function textSpanEnd(span) {
            return span.start + span.length;
        }
        ts.textSpanEnd = textSpanEnd;
        function textSpanIsEmpty(span) {
            return span.length === 0;
        }
        ts.textSpanIsEmpty = textSpanIsEmpty;
        function textSpanContainsPosition(span, position) {
            return position >= span.start && position < textSpanEnd(span);
        }
        ts.textSpanContainsPosition = textSpanContainsPosition;
        /* @internal */
        function textRangeContainsPositionInclusive(span, position) {
            return position >= span.pos && position <= span.end;
        }
        ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
        // Returns true if 'span' contains 'other'.
        function textSpanContainsTextSpan(span, other) {
            return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
        }
        ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
        function textSpanOverlapsWith(span, other) {
            return textSpanOverlap(span, other) !== undefined;
        }
        ts.textSpanOverlapsWith = textSpanOverlapsWith;
        function textSpanOverlap(span1, span2) {
            var overlap = textSpanIntersection(span1, span2);
            return overlap && overlap.length === 0 ? undefined : overlap;
        }
        ts.textSpanOverlap = textSpanOverlap;
        function textSpanIntersectsWithTextSpan(span, other) {
            return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
        }
        ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
        function textSpanIntersectsWith(span, start, length) {
            return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
        }
        ts.textSpanIntersectsWith = textSpanIntersectsWith;
        function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
            var end1 = start1 + length1;
            var end2 = start2 + length2;
            return start2 <= end1 && end2 >= start1;
        }
        ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
        function textSpanIntersectsWithPosition(span, position) {
            return position <= textSpanEnd(span) && position >= span.start;
        }
        ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
        function textSpanIntersection(span1, span2) {
            var start = Math.max(span1.start, span2.start);
            var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
            return start <= end ? createTextSpanFromBounds(start, end) : undefined;
        }
        ts.textSpanIntersection = textSpanIntersection;
        function createTextSpan(start, length) {
            if (start < 0) {
                throw new Error("start < 0");
            }
            if (length < 0) {
                throw new Error("length < 0");
            }
            return { start: start, length: length };
        }
        ts.createTextSpan = createTextSpan;
        function createTextSpanFromBounds(start, end) {
            return createTextSpan(start, end - start);
        }
        ts.createTextSpanFromBounds = createTextSpanFromBounds;
        function textChangeRangeNewSpan(range) {
            return createTextSpan(range.span.start, range.newLength);
        }
        ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
        function textChangeRangeIsUnchanged(range) {
            return textSpanIsEmpty(range.span) && range.newLength === 0;
        }
        ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
        function createTextChangeRange(span, newLength) {
            if (newLength < 0) {
                throw new Error("newLength < 0");
            }
            return { span: span, newLength: newLength };
        }
        ts.createTextChangeRange = createTextChangeRange;
        ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0);
        /**
         * Called to merge all the changes that occurred across several versions of a script snapshot
         * into a single change.  i.e. if a user keeps making successive edits to a script we will
         * have a text change from V1 to V2, V2 to V3, ..., Vn.
         *
         * This function will then merge those changes into a single change range valid between V1 and
         * Vn.
         */
        function collapseTextChangeRangesAcrossMultipleVersions(changes) {
            if (changes.length === 0) {
                return ts.unchangedTextChangeRange;
            }
            if (changes.length === 1) {
                return changes[0];
            }
            // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
            // as it makes things much easier to reason about.
            var change0 = changes[0];
            var oldStartN = change0.span.start;
            var oldEndN = textSpanEnd(change0.span);
            var newEndN = oldStartN + change0.newLength;
            for (var i = 1; i < changes.length; i++) {
                var nextChange = changes[i];
                // Consider the following case:
                // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
                // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
                // i.e. the span starting at 30 with length 30 is increased to length 40.
                //
                //      0         10        20        30        40        50        60        70        80        90        100
                //      -------------------------------------------------------------------------------------------------------
                //                |                                                 /
                //                |                                            /----
                //  T1            |                                       /----
                //                |                                  /----
                //                |                             /----
                //      -------------------------------------------------------------------------------------------------------
                //                                     |                            \
                //                                     |                               \
                //   T2                                |                                 \
                //                                     |                                   \
                //                                     |                                      \
                //      -------------------------------------------------------------------------------------------------------
                //
                // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
                // it's just the min of the old and new starts.  i.e.:
                //
                //      0         10        20        30        40        50        60        70        80        90        100
                //      ------------------------------------------------------------*------------------------------------------
                //                |                                                 /
                //                |                                            /----
                //  T1            |                                       /----
                //                |                                  /----
                //                |                             /----
                //      ----------------------------------------$-------------------$------------------------------------------
                //                .                    |                            \
                //                .                    |                               \
                //   T2           .                    |                                 \
                //                .                    |                                   \
                //                .                    |                                      \
                //      ----------------------------------------------------------------------*--------------------------------
                //
                // (Note the dots represent the newly inferred start.
                // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
                // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
                // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
                // means:
                //
                //      0         10        20        30        40        50        60        70        80        90        100
                //      --------------------------------------------------------------------------------*----------------------
                //                |                                                                     /
                //                |                                                                /----
                //  T1            |                                                           /----
                //                |                                                      /----
                //                |                                                 /----
                //      ------------------------------------------------------------$------------------------------------------
                //                .                    |                            \
                //                .                    |                               \
                //   T2           .                    |                                 \
                //                .                    |                                   \
                //                .                    |                                      \
                //      ----------------------------------------------------------------------*--------------------------------
                //
                // In other words (in this case), we're recognizing that the second edit happened after where the first edit
                // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
                // that's the same as if we started at char 80 instead of 60.
                //
                // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
                // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
                // first.
                //
                // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
                // semantics: { { start: 10, length: 70 }, newLength: 60 }
                //
                // The math then works out as follows.
                // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
                // final result like so:
                //
                // {
                //      oldStart3: Min(oldStart1, oldStart2),
                //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
                //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
                // }
                var oldStart1 = oldStartN;
                var oldEnd1 = oldEndN;
                var newEnd1 = newEndN;
                var oldStart2 = nextChange.span.start;
                var oldEnd2 = textSpanEnd(nextChange.span);
                var newEnd2 = oldStart2 + nextChange.newLength;
                oldStartN = Math.min(oldStart1, oldStart2);
                oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
                newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
            }
            return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
        }
        ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
        function getTypeParameterOwner(d) {
            if (d && d.kind === 148 /* TypeParameter */) {
                for (var current = d; current; current = current.parent) {
                    if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) {
                        return current;
                    }
                }
            }
        }
        ts.getTypeParameterOwner = getTypeParameterOwner;
        function isParameterPropertyDeclaration(node) {
            return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */;
        }
        ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
        function isEmptyBindingPattern(node) {
            if (ts.isBindingPattern(node)) {
                return ts.every(node.elements, isEmptyBindingElement);
            }
            return false;
        }
        ts.isEmptyBindingPattern = isEmptyBindingPattern;
        function isEmptyBindingElement(node) {
            if (ts.isOmittedExpression(node)) {
                return true;
            }
            return isEmptyBindingPattern(node.name);
        }
        ts.isEmptyBindingElement = isEmptyBindingElement;
        function walkUpBindingElementsAndPatterns(binding) {
            var node = binding.parent;
            while (ts.isBindingElement(node.parent)) {
                node = node.parent.parent;
            }
            return node.parent;
        }
        ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
        function getCombinedFlags(node, getFlags) {
            if (ts.isBindingElement(node)) {
                node = walkUpBindingElementsAndPatterns(node);
            }
            var flags = getFlags(node);
            if (node.kind === 235 /* VariableDeclaration */) {
                node = node.parent;
            }
            if (node && node.kind === 236 /* VariableDeclarationList */) {
                flags |= getFlags(node);
                node = node.parent;
            }
            if (node && node.kind === 217 /* VariableStatement */) {
                flags |= getFlags(node);
            }
            return flags;
        }
        function getCombinedModifierFlags(node) {
            return getCombinedFlags(node, ts.getModifierFlags);
        }
        ts.getCombinedModifierFlags = getCombinedModifierFlags;
        // Returns the node flags for this node and all relevant parent nodes.  This is done so that
        // nodes like variable declarations and binding elements can returned a view of their flags
        // that includes the modifiers from their container.  i.e. flags like export/declare aren't
        // stored on the variable declaration directly, but on the containing variable statement
        // (if it has one).  Similarly, flags for let/const are store on the variable declaration
        // list.  By calling this function, all those flags are combined so that the client can treat
        // the node as if it actually had those flags.
        function getCombinedNodeFlags(node) {
            return getCombinedFlags(node, function (n) { return n.flags; });
        }
        ts.getCombinedNodeFlags = getCombinedNodeFlags;
        /**
         * Checks to see if the locale is in the appropriate format,
         * and if it is, attempts to set the appropriate language.
         */
        function validateLocaleAndSetLanguage(locale, sys, errors) {
            var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
            if (!matchResult) {
                if (errors) {
                    errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
                }
                return;
            }
            var language = matchResult[1];
            var territory = matchResult[3];
            // First try the entire locale, then fall back to just language if that's all we have.
            // Either ways do not fail, and fallback to the English diagnostic strings.
            if (!trySetLanguageAndTerritory(language, territory, errors)) {
                trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
            }
            // Set the UI locale for string collation
            ts.setUILocale(locale);
            function trySetLanguageAndTerritory(language, territory, errors) {
                var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
                var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
                var filePath = ts.combinePaths(containingDirectoryPath, language);
                if (territory) {
                    filePath = filePath + "-" + territory;
                }
                filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
                if (!sys.fileExists(filePath)) {
                    return false;
                }
                // TODO: Add codePage support for readFile?
                var fileContents = "";
                try {
                    fileContents = sys.readFile(filePath);
                }
                catch (e) {
                    if (errors) {
                        errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
                    }
                    return false;
                }
                try {
                    // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!)
                    ts.localizedDiagnosticMessages = JSON.parse(fileContents);
                }
                catch (_a) {
                    if (errors) {
                        errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
                    }
                    return false;
                }
                return true;
            }
        }
        ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
        function getOriginalNode(node, nodeTest) {
            if (node) {
                while (node.original !== undefined) {
                    node = node.original;
                }
            }
            return !nodeTest || nodeTest(node) ? node : undefined;
        }
        ts.getOriginalNode = getOriginalNode;
        /**
         * Gets a value indicating whether a node originated in the parse tree.
         *
         * @param node The node to test.
         */
        function isParseTreeNode(node) {
            return (node.flags & 8 /* Synthesized */) === 0;
        }
        ts.isParseTreeNode = isParseTreeNode;
        function getParseTreeNode(node, nodeTest) {
            if (node === undefined || isParseTreeNode(node)) {
                return node;
            }
            node = getOriginalNode(node);
            if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
                return node;
            }
            return undefined;
        }
        ts.getParseTreeNode = getParseTreeNode;
        /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
        function escapeLeadingUnderscores(identifier) {
            return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
        }
        ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
        /**
         * Remove extra underscore from escaped identifier text content.
         *
         * @param identifier The escaped identifier text.
         * @returns The unescaped identifier text.
         */
        function unescapeLeadingUnderscores(identifier) {
            var id = identifier;
            return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
        }
        ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
        function idText(identifier) {
            return unescapeLeadingUnderscores(identifier.escapedText);
        }
        ts.idText = idText;
        function symbolName(symbol) {
            return unescapeLeadingUnderscores(symbol.escapedName);
        }
        ts.symbolName = symbolName;
        /**
         * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
         * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
         * will be merged with)
         */
        function nameForNamelessJSDocTypedef(declaration) {
            var hostNode = declaration.parent.parent;
            if (!hostNode) {
                return undefined;
            }
            // Covers classes, functions - any named declaration host node
            if (ts.isDeclaration(hostNode)) {
                return getDeclarationIdentifier(hostNode);
            }
            // Covers remaining cases (returning undefined if none match).
            switch (hostNode.kind) {
                case 217 /* VariableStatement */:
                    if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
                        return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
                    }
                    break;
                case 219 /* ExpressionStatement */:
                    var expr = hostNode.expression;
                    switch (expr.kind) {
                        case 187 /* PropertyAccessExpression */:
                            return expr.name;
                        case 188 /* ElementAccessExpression */:
                            var arg = expr.argumentExpression;
                            if (ts.isIdentifier(arg)) {
                                return arg;
                            }
                    }
                    break;
                case 193 /* ParenthesizedExpression */: {
                    return getDeclarationIdentifier(hostNode.expression);
                }
                case 231 /* LabeledStatement */: {
                    if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) {
                        return getDeclarationIdentifier(hostNode.statement);
                    }
                    break;
                }
            }
        }
        function getDeclarationIdentifier(node) {
            var name = getNameOfDeclaration(node);
            return name && ts.isIdentifier(name) ? name : undefined;
        }
        function getNameOfJSDocTypedef(declaration) {
            return declaration.name || nameForNamelessJSDocTypedef(declaration);
        }
        ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
        /** @internal */
        function isNamedDeclaration(node) {
            return !!node.name; // A 'name' property should always be a DeclarationName.
        }
        ts.isNamedDeclaration = isNamedDeclaration;
        /** @internal */
        function getNonAssignedNameOfDeclaration(declaration) {
            switch (declaration.kind) {
                case 71 /* Identifier */:
                    return declaration;
                case 303 /* JSDocPropertyTag */:
                case 297 /* JSDocParameterTag */: {
                    var name = declaration.name;
                    if (name.kind === 146 /* QualifiedName */) {
                        return name.right;
                    }
                    break;
                }
                case 202 /* BinaryExpression */: {
                    var expr = declaration;
                    switch (ts.getAssignmentDeclarationKind(expr)) {
                        case 1 /* ExportsProperty */:
                        case 4 /* ThisProperty */:
                        case 5 /* Property */:
                        case 3 /* PrototypeProperty */:
                            return expr.left.name;
                        default:
                            return undefined;
                    }
                }
                case 302 /* JSDocTypedefTag */:
                    return getNameOfJSDocTypedef(declaration);
                case 252 /* ExportAssignment */: {
                    var expression = declaration.expression;
                    return ts.isIdentifier(expression) ? expression : undefined;
                }
            }
            return declaration.name;
        }
        ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
        function getNameOfDeclaration(declaration) {
            if (declaration === undefined)
                return undefined;
            return getNonAssignedNameOfDeclaration(declaration) ||
                (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
        }
        ts.getNameOfDeclaration = getNameOfDeclaration;
        function getAssignedName(node) {
            if (!node.parent) {
                return undefined;
            }
            else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
                return node.parent.name;
            }
            else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
                if (ts.isIdentifier(node.parent.left)) {
                    return node.parent.left;
                }
                else if (ts.isPropertyAccessExpression(node.parent.left)) {
                    return node.parent.left.name;
                }
            }
        }
        /**
         * Gets the JSDoc parameter tags for the node if present.
         *
         * @remarks Returns any JSDoc param tag whose name matches the provided
         * parameter, whether a param tag on a containing function
         * expression, or a param tag on a variable declaration whose
         * initializer is the containing function. The tags closest to the
         * node are returned first, so in the previous example, the param
         * tag on the containing function expression would be first.
         *
         * For binding patterns, parameter tags are matched by position.
         */
        function getJSDocParameterTags(param) {
            if (param.name) {
                if (ts.isIdentifier(param.name)) {
                    var name_1 = param.name.escapedText;
                    return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
                }
                else {
                    var i = param.parent.parameters.indexOf(param);
                    ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
                    var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag);
                    if (i < paramTags.length) {
                        return [paramTags[i]];
                    }
                }
            }
            // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
            return ts.emptyArray;
        }
        ts.getJSDocParameterTags = getJSDocParameterTags;
        /**
         * Gets the JSDoc type parameter tags for the node if present.
         *
         * @remarks Returns any JSDoc template tag whose names match the provided
         * parameter, whether a template tag on a containing function
         * expression, or a template tag on a variable declaration whose
         * initializer is the containing function. The tags closest to the
         * node are returned first, so in the previous example, the template
         * tag on the containing function expression would be first.
         */
        function getJSDocTypeParameterTags(param) {
            var name = param.name.escapedText;
            return getJSDocTags(param.parent).filter(function (tag) {
                return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
            });
        }
        ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
        /**
         * Return true if the node has JSDoc parameter tags.
         *
         * @remarks Includes parameter tags that are not directly on the node,
         * for example on a variable declaration whose initializer is a function expression.
         */
        function hasJSDocParameterTags(node) {
            return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
        }
        ts.hasJSDocParameterTags = hasJSDocParameterTags;
        /** Gets the JSDoc augments tag for the node if present */
        function getJSDocAugmentsTag(node) {
            return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
        }
        ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
        /** Gets the JSDoc class tag for the node if present */
        function getJSDocClassTag(node) {
            return getFirstJSDocTag(node, ts.isJSDocClassTag);
        }
        ts.getJSDocClassTag = getJSDocClassTag;
        /** Gets the JSDoc enum tag for the node if present */
        function getJSDocEnumTag(node) {
            return getFirstJSDocTag(node, ts.isJSDocEnumTag);
        }
        ts.getJSDocEnumTag = getJSDocEnumTag;
        /** Gets the JSDoc this tag for the node if present */
        function getJSDocThisTag(node) {
            return getFirstJSDocTag(node, ts.isJSDocThisTag);
        }
        ts.getJSDocThisTag = getJSDocThisTag;
        /** Gets the JSDoc return tag for the node if present */
        function getJSDocReturnTag(node) {
            return getFirstJSDocTag(node, ts.isJSDocReturnTag);
        }
        ts.getJSDocReturnTag = getJSDocReturnTag;
        /** Gets the JSDoc template tag for the node if present */
        function getJSDocTemplateTag(node) {
            return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
        }
        ts.getJSDocTemplateTag = getJSDocTemplateTag;
        /** Gets the JSDoc type tag for the node if present and valid */
        function getJSDocTypeTag(node) {
            // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
            var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
            if (tag && tag.typeExpression && tag.typeExpression.type) {
                return tag;
            }
            return undefined;
        }
        ts.getJSDocTypeTag = getJSDocTypeTag;
        /**
         * Gets the type node for the node if provided via JSDoc.
         *
         * @remarks The search includes any JSDoc param tag that relates
         * to the provided parameter, for example a type tag on the
         * parameter itself, or a param tag on a containing function
         * expression, or a param tag on a variable declaration whose
         * initializer is the containing function. The tags closest to the
         * node are examined first, so in the previous example, the type
         * tag directly on the node would be returned.
         */
        function getJSDocType(node) {
            var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
            if (!tag && ts.isParameter(node)) {
                tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
            }
            return tag && tag.typeExpression && tag.typeExpression.type;
        }
        ts.getJSDocType = getJSDocType;
        /**
         * Gets the return type node for the node if provided via JSDoc return tag or type tag.
         *
         * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
         * gets the type from inside the braces, after the fat arrow, etc.
         */
        function getJSDocReturnType(node) {
            var returnTag = getJSDocReturnTag(node);
            if (returnTag && returnTag.typeExpression) {
                return returnTag.typeExpression.type;
            }
            var typeTag = getJSDocTypeTag(node);
            if (typeTag && typeTag.typeExpression) {
                var type = typeTag.typeExpression.type;
                if (ts.isTypeLiteralNode(type)) {
                    var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
                    return sig && sig.type;
                }
                if (ts.isFunctionTypeNode(type)) {
                    return type.type;
                }
            }
        }
        ts.getJSDocReturnType = getJSDocReturnType;
        /** Get all JSDoc tags related to a node, including those on parent nodes. */
        function getJSDocTags(node) {
            var tags = node.jsDocCache;
            // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
            if (tags === undefined) {
                var comments = ts.getJSDocCommentsAndTags(node);
                ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
                node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
            }
            return tags;
        }
        ts.getJSDocTags = getJSDocTags;
        /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
        function getFirstJSDocTag(node, predicate) {
            return ts.find(getJSDocTags(node), predicate);
        }
        /** Gets all JSDoc tags of a specified kind, or undefined if not present. */
        function getAllJSDocTagsOfKind(node, kind) {
            return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
        }
        ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
        /**
         * Gets the effective type parameters. If the node was parsed in a
         * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
         */
        function getEffectiveTypeParameterDeclarations(node) {
            if (ts.isJSDocSignature(node)) {
                return ts.emptyArray;
            }
            if (ts.isJSDocTypeAlias(node)) {
                ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */);
                return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
            }
            if (node.typeParameters) {
                return node.typeParameters;
            }
            if (ts.isInJSFile(node)) {
                var decls = ts.getJSDocTypeParameterDeclarations(node);
                if (decls.length) {
                    return decls;
                }
                var typeTag = getJSDocType(node);
                if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
                    return typeTag.typeParameters;
                }
            }
            return ts.emptyArray;
        }
        ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
        function getEffectiveConstraintOfTypeParameter(node) {
            return node.constraint ? node.constraint
                : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0]
                    ? node.parent.constraint
                    : undefined;
        }
        ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
    })(ts || (ts = {}));
    // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
    (function (ts) {
        // Literals
        function isNumericLiteral(node) {
            return node.kind === 8 /* NumericLiteral */;
        }
        ts.isNumericLiteral = isNumericLiteral;
        function isStringLiteral(node) {
            return node.kind === 9 /* StringLiteral */;
        }
        ts.isStringLiteral = isStringLiteral;
        function isJsxText(node) {
            return node.kind === 10 /* JsxText */;
        }
        ts.isJsxText = isJsxText;
        function isRegularExpressionLiteral(node) {
            return node.kind === 12 /* RegularExpressionLiteral */;
        }
        ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
        function isNoSubstitutionTemplateLiteral(node) {
            return node.kind === 13 /* NoSubstitutionTemplateLiteral */;
        }
        ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
        // Pseudo-literals
        function isTemplateHead(node) {
            return node.kind === 14 /* TemplateHead */;
        }
        ts.isTemplateHead = isTemplateHead;
        function isTemplateMiddle(node) {
            return node.kind === 15 /* TemplateMiddle */;
        }
        ts.isTemplateMiddle = isTemplateMiddle;
        function isTemplateTail(node) {
            return node.kind === 16 /* TemplateTail */;
        }
        ts.isTemplateTail = isTemplateTail;
        function isIdentifier(node) {
            return node.kind === 71 /* Identifier */;
        }
        ts.isIdentifier = isIdentifier;
        // Names
        function isQualifiedName(node) {
            return node.kind === 146 /* QualifiedName */;
        }
        ts.isQualifiedName = isQualifiedName;
        function isComputedPropertyName(node) {
            return node.kind === 147 /* ComputedPropertyName */;
        }
        ts.isComputedPropertyName = isComputedPropertyName;
        // Signature elements
        function isTypeParameterDeclaration(node) {
            return node.kind === 148 /* TypeParameter */;
        }
        ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
        function isParameter(node) {
            return node.kind === 149 /* Parameter */;
        }
        ts.isParameter = isParameter;
        function isDecorator(node) {
            return node.kind === 150 /* Decorator */;
        }
        ts.isDecorator = isDecorator;
        // TypeMember
        function isPropertySignature(node) {
            return node.kind === 151 /* PropertySignature */;
        }
        ts.isPropertySignature = isPropertySignature;
        function isPropertyDeclaration(node) {
            return node.kind === 152 /* PropertyDeclaration */;
        }
        ts.isPropertyDeclaration = isPropertyDeclaration;
        function isMethodSignature(node) {
            return node.kind === 153 /* MethodSignature */;
        }
        ts.isMethodSignature = isMethodSignature;
        function isMethodDeclaration(node) {
            return node.kind === 154 /* MethodDeclaration */;
        }
        ts.isMethodDeclaration = isMethodDeclaration;
        function isConstructorDeclaration(node) {
            return node.kind === 155 /* Constructor */;
        }
        ts.isConstructorDeclaration = isConstructorDeclaration;
        function isGetAccessorDeclaration(node) {
            return node.kind === 156 /* GetAccessor */;
        }
        ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
        function isSetAccessorDeclaration(node) {
            return node.kind === 157 /* SetAccessor */;
        }
        ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
        function isCallSignatureDeclaration(node) {
            return node.kind === 158 /* CallSignature */;
        }
        ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
        function isConstructSignatureDeclaration(node) {
            return node.kind === 159 /* ConstructSignature */;
        }
        ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
        function isIndexSignatureDeclaration(node) {
            return node.kind === 160 /* IndexSignature */;
        }
        ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
        /* @internal */
        function isGetOrSetAccessorDeclaration(node) {
            return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */;
        }
        ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
        // Type
        function isTypePredicateNode(node) {
            return node.kind === 161 /* TypePredicate */;
        }
        ts.isTypePredicateNode = isTypePredicateNode;
        function isTypeReferenceNode(node) {
            return node.kind === 162 /* TypeReference */;
        }
        ts.isTypeReferenceNode = isTypeReferenceNode;
        function isFunctionTypeNode(node) {
            return node.kind === 163 /* FunctionType */;
        }
        ts.isFunctionTypeNode = isFunctionTypeNode;
        function isConstructorTypeNode(node) {
            return node.kind === 164 /* ConstructorType */;
        }
        ts.isConstructorTypeNode = isConstructorTypeNode;
        function isTypeQueryNode(node) {
            return node.kind === 165 /* TypeQuery */;
        }
        ts.isTypeQueryNode = isTypeQueryNode;
        function isTypeLiteralNode(node) {
            return node.kind === 166 /* TypeLiteral */;
        }
        ts.isTypeLiteralNode = isTypeLiteralNode;
        function isArrayTypeNode(node) {
            return node.kind === 167 /* ArrayType */;
        }
        ts.isArrayTypeNode = isArrayTypeNode;
        function isTupleTypeNode(node) {
            return node.kind === 168 /* TupleType */;
        }
        ts.isTupleTypeNode = isTupleTypeNode;
        function isUnionTypeNode(node) {
            return node.kind === 171 /* UnionType */;
        }
        ts.isUnionTypeNode = isUnionTypeNode;
        function isIntersectionTypeNode(node) {
            return node.kind === 172 /* IntersectionType */;
        }
        ts.isIntersectionTypeNode = isIntersectionTypeNode;
        function isConditionalTypeNode(node) {
            return node.kind === 173 /* ConditionalType */;
        }
        ts.isConditionalTypeNode = isConditionalTypeNode;
        function isInferTypeNode(node) {
            return node.kind === 174 /* InferType */;
        }
        ts.isInferTypeNode = isInferTypeNode;
        function isParenthesizedTypeNode(node) {
            return node.kind === 175 /* ParenthesizedType */;
        }
        ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
        function isThisTypeNode(node) {
            return node.kind === 176 /* ThisType */;
        }
        ts.isThisTypeNode = isThisTypeNode;
        function isTypeOperatorNode(node) {
            return node.kind === 177 /* TypeOperator */;
        }
        ts.isTypeOperatorNode = isTypeOperatorNode;
        function isIndexedAccessTypeNode(node) {
            return node.kind === 178 /* IndexedAccessType */;
        }
        ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
        function isMappedTypeNode(node) {
            return node.kind === 179 /* MappedType */;
        }
        ts.isMappedTypeNode = isMappedTypeNode;
        function isLiteralTypeNode(node) {
            return node.kind === 180 /* LiteralType */;
        }
        ts.isLiteralTypeNode = isLiteralTypeNode;
        function isImportTypeNode(node) {
            return node.kind === 181 /* ImportType */;
        }
        ts.isImportTypeNode = isImportTypeNode;
        // Binding patterns
        function isObjectBindingPattern(node) {
            return node.kind === 182 /* ObjectBindingPattern */;
        }
        ts.isObjectBindingPattern = isObjectBindingPattern;
        function isArrayBindingPattern(node) {
            return node.kind === 183 /* ArrayBindingPattern */;
        }
        ts.isArrayBindingPattern = isArrayBindingPattern;
        function isBindingElement(node) {
            return node.kind === 184 /* BindingElement */;
        }
        ts.isBindingElement = isBindingElement;
        // Expression
        function isArrayLiteralExpression(node) {
            return node.kind === 185 /* ArrayLiteralExpression */;
        }
        ts.isArrayLiteralExpression = isArrayLiteralExpression;
        function isObjectLiteralExpression(node) {
            return node.kind === 186 /* ObjectLiteralExpression */;
        }
        ts.isObjectLiteralExpression = isObjectLiteralExpression;
        function isPropertyAccessExpression(node) {
            return node.kind === 187 /* PropertyAccessExpression */;
        }
        ts.isPropertyAccessExpression = isPropertyAccessExpression;
        function isElementAccessExpression(node) {
            return node.kind === 188 /* ElementAccessExpression */;
        }
        ts.isElementAccessExpression = isElementAccessExpression;
        function isCallExpression(node) {
            return node.kind === 189 /* CallExpression */;
        }
        ts.isCallExpression = isCallExpression;
        function isNewExpression(node) {
            return node.kind === 190 /* NewExpression */;
        }
        ts.isNewExpression = isNewExpression;
        function isTaggedTemplateExpression(node) {
            return node.kind === 191 /* TaggedTemplateExpression */;
        }
        ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
        function isTypeAssertion(node) {
            return node.kind === 192 /* TypeAssertionExpression */;
        }
        ts.isTypeAssertion = isTypeAssertion;
        function isParenthesizedExpression(node) {
            return node.kind === 193 /* ParenthesizedExpression */;
        }
        ts.isParenthesizedExpression = isParenthesizedExpression;
        function skipPartiallyEmittedExpressions(node) {
            while (node.kind === 306 /* PartiallyEmittedExpression */) {
                node = node.expression;
            }
            return node;
        }
        ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
        function isFunctionExpression(node) {
            return node.kind === 194 /* FunctionExpression */;
        }
        ts.isFunctionExpression = isFunctionExpression;
        function isArrowFunction(node) {
            return node.kind === 195 /* ArrowFunction */;
        }
        ts.isArrowFunction = isArrowFunction;
        function isDeleteExpression(node) {
            return node.kind === 196 /* DeleteExpression */;
        }
        ts.isDeleteExpression = isDeleteExpression;
        function isTypeOfExpression(node) {
            return node.kind === 197 /* TypeOfExpression */;
        }
        ts.isTypeOfExpression = isTypeOfExpression;
        function isVoidExpression(node) {
            return node.kind === 198 /* VoidExpression */;
        }
        ts.isVoidExpression = isVoidExpression;
        function isAwaitExpression(node) {
            return node.kind === 199 /* AwaitExpression */;
        }
        ts.isAwaitExpression = isAwaitExpression;
        function isPrefixUnaryExpression(node) {
            return node.kind === 200 /* PrefixUnaryExpression */;
        }
        ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
        function isPostfixUnaryExpression(node) {
            return node.kind === 201 /* PostfixUnaryExpression */;
        }
        ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
        function isBinaryExpression(node) {
            return node.kind === 202 /* BinaryExpression */;
        }
        ts.isBinaryExpression = isBinaryExpression;
        function isConditionalExpression(node) {
            return node.kind === 203 /* ConditionalExpression */;
        }
        ts.isConditionalExpression = isConditionalExpression;
        function isTemplateExpression(node) {
            return node.kind === 204 /* TemplateExpression */;
        }
        ts.isTemplateExpression = isTemplateExpression;
        function isYieldExpression(node) {
            return node.kind === 205 /* YieldExpression */;
        }
        ts.isYieldExpression = isYieldExpression;
        function isSpreadElement(node) {
            return node.kind === 206 /* SpreadElement */;
        }
        ts.isSpreadElement = isSpreadElement;
        function isClassExpression(node) {
            return node.kind === 207 /* ClassExpression */;
        }
        ts.isClassExpression = isClassExpression;
        function isOmittedExpression(node) {
            return node.kind === 208 /* OmittedExpression */;
        }
        ts.isOmittedExpression = isOmittedExpression;
        function isExpressionWithTypeArguments(node) {
            return node.kind === 209 /* ExpressionWithTypeArguments */;
        }
        ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
        function isAsExpression(node) {
            return node.kind === 210 /* AsExpression */;
        }
        ts.isAsExpression = isAsExpression;
        function isNonNullExpression(node) {
            return node.kind === 211 /* NonNullExpression */;
        }
        ts.isNonNullExpression = isNonNullExpression;
        function isMetaProperty(node) {
            return node.kind === 212 /* MetaProperty */;
        }
        ts.isMetaProperty = isMetaProperty;
        // Misc
        function isTemplateSpan(node) {
            return node.kind === 214 /* TemplateSpan */;
        }
        ts.isTemplateSpan = isTemplateSpan;
        function isSemicolonClassElement(node) {
            return node.kind === 215 /* SemicolonClassElement */;
        }
        ts.isSemicolonClassElement = isSemicolonClassElement;
        // Block
        function isBlock(node) {
            return node.kind === 216 /* Block */;
        }
        ts.isBlock = isBlock;
        function isVariableStatement(node) {
            return node.kind === 217 /* VariableStatement */;
        }
        ts.isVariableStatement = isVariableStatement;
        function isEmptyStatement(node) {
            return node.kind === 218 /* EmptyStatement */;
        }
        ts.isEmptyStatement = isEmptyStatement;
        function isExpressionStatement(node) {
            return node.kind === 219 /* ExpressionStatement */;
        }
        ts.isExpressionStatement = isExpressionStatement;
        function isIfStatement(node) {
            return node.kind === 220 /* IfStatement */;
        }
        ts.isIfStatement = isIfStatement;
        function isDoStatement(node) {
            return node.kind === 221 /* DoStatement */;
        }
        ts.isDoStatement = isDoStatement;
        function isWhileStatement(node) {
            return node.kind === 222 /* WhileStatement */;
        }
        ts.isWhileStatement = isWhileStatement;
        function isForStatement(node) {
            return node.kind === 223 /* ForStatement */;
        }
        ts.isForStatement = isForStatement;
        function isForInStatement(node) {
            return node.kind === 224 /* ForInStatement */;
        }
        ts.isForInStatement = isForInStatement;
        function isForOfStatement(node) {
            return node.kind === 225 /* ForOfStatement */;
        }
        ts.isForOfStatement = isForOfStatement;
        function isContinueStatement(node) {
            return node.kind === 226 /* ContinueStatement */;
        }
        ts.isContinueStatement = isContinueStatement;
        function isBreakStatement(node) {
            return node.kind === 227 /* BreakStatement */;
        }
        ts.isBreakStatement = isBreakStatement;
        function isBreakOrContinueStatement(node) {
            return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */;
        }
        ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
        function isReturnStatement(node) {
            return node.kind === 228 /* ReturnStatement */;
        }
        ts.isReturnStatement = isReturnStatement;
        function isWithStatement(node) {
            return node.kind === 229 /* WithStatement */;
        }
        ts.isWithStatement = isWithStatement;
        function isSwitchStatement(node) {
            return node.kind === 230 /* SwitchStatement */;
        }
        ts.isSwitchStatement = isSwitchStatement;
        function isLabeledStatement(node) {
            return node.kind === 231 /* LabeledStatement */;
        }
        ts.isLabeledStatement = isLabeledStatement;
        function isThrowStatement(node) {
            return node.kind === 232 /* ThrowStatement */;
        }
        ts.isThrowStatement = isThrowStatement;
        function isTryStatement(node) {
            return node.kind === 233 /* TryStatement */;
        }
        ts.isTryStatement = isTryStatement;
        function isDebuggerStatement(node) {
            return node.kind === 234 /* DebuggerStatement */;
        }
        ts.isDebuggerStatement = isDebuggerStatement;
        function isVariableDeclaration(node) {
            return node.kind === 235 /* VariableDeclaration */;
        }
        ts.isVariableDeclaration = isVariableDeclaration;
        function isVariableDeclarationList(node) {
            return node.kind === 236 /* VariableDeclarationList */;
        }
        ts.isVariableDeclarationList = isVariableDeclarationList;
        function isFunctionDeclaration(node) {
            return node.kind === 237 /* FunctionDeclaration */;
        }
        ts.isFunctionDeclaration = isFunctionDeclaration;
        function isClassDeclaration(node) {
            return node.kind === 238 /* ClassDeclaration */;
        }
        ts.isClassDeclaration = isClassDeclaration;
        function isInterfaceDeclaration(node) {
            return node.kind === 239 /* InterfaceDeclaration */;
        }
        ts.isInterfaceDeclaration = isInterfaceDeclaration;
        function isTypeAliasDeclaration(node) {
            return node.kind === 240 /* TypeAliasDeclaration */;
        }
        ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
        function isEnumDeclaration(node) {
            return node.kind === 241 /* EnumDeclaration */;
        }
        ts.isEnumDeclaration = isEnumDeclaration;
        function isModuleDeclaration(node) {
            return node.kind === 242 /* ModuleDeclaration */;
        }
        ts.isModuleDeclaration = isModuleDeclaration;
        function isModuleBlock(node) {
            return node.kind === 243 /* ModuleBlock */;
        }
        ts.isModuleBlock = isModuleBlock;
        function isCaseBlock(node) {
            return node.kind === 244 /* CaseBlock */;
        }
        ts.isCaseBlock = isCaseBlock;
        function isNamespaceExportDeclaration(node) {
            return node.kind === 245 /* NamespaceExportDeclaration */;
        }
        ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
        function isImportEqualsDeclaration(node) {
            return node.kind === 246 /* ImportEqualsDeclaration */;
        }
        ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
        function isImportDeclaration(node) {
            return node.kind === 247 /* ImportDeclaration */;
        }
        ts.isImportDeclaration = isImportDeclaration;
        function isImportClause(node) {
            return node.kind === 248 /* ImportClause */;
        }
        ts.isImportClause = isImportClause;
        function isNamespaceImport(node) {
            return node.kind === 249 /* NamespaceImport */;
        }
        ts.isNamespaceImport = isNamespaceImport;
        function isNamedImports(node) {
            return node.kind === 250 /* NamedImports */;
        }
        ts.isNamedImports = isNamedImports;
        function isImportSpecifier(node) {
            return node.kind === 251 /* ImportSpecifier */;
        }
        ts.isImportSpecifier = isImportSpecifier;
        function isExportAssignment(node) {
            return node.kind === 252 /* ExportAssignment */;
        }
        ts.isExportAssignment = isExportAssignment;
        function isExportDeclaration(node) {
            return node.kind === 253 /* ExportDeclaration */;
        }
        ts.isExportDeclaration = isExportDeclaration;
        function isNamedExports(node) {
            return node.kind === 254 /* NamedExports */;
        }
        ts.isNamedExports = isNamedExports;
        function isExportSpecifier(node) {
            return node.kind === 255 /* ExportSpecifier */;
        }
        ts.isExportSpecifier = isExportSpecifier;
        function isMissingDeclaration(node) {
            return node.kind === 256 /* MissingDeclaration */;
        }
        ts.isMissingDeclaration = isMissingDeclaration;
        // Module References
        function isExternalModuleReference(node) {
            return node.kind === 257 /* ExternalModuleReference */;
        }
        ts.isExternalModuleReference = isExternalModuleReference;
        // JSX
        function isJsxElement(node) {
            return node.kind === 258 /* JsxElement */;
        }
        ts.isJsxElement = isJsxElement;
        function isJsxSelfClosingElement(node) {
            return node.kind === 259 /* JsxSelfClosingElement */;
        }
        ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
        function isJsxOpeningElement(node) {
            return node.kind === 260 /* JsxOpeningElement */;
        }
        ts.isJsxOpeningElement = isJsxOpeningElement;
        function isJsxClosingElement(node) {
            return node.kind === 261 /* JsxClosingElement */;
        }
        ts.isJsxClosingElement = isJsxClosingElement;
        function isJsxFragment(node) {
            return node.kind === 262 /* JsxFragment */;
        }
        ts.isJsxFragment = isJsxFragment;
        function isJsxOpeningFragment(node) {
            return node.kind === 263 /* JsxOpeningFragment */;
        }
        ts.isJsxOpeningFragment = isJsxOpeningFragment;
        function isJsxClosingFragment(node) {
            return node.kind === 264 /* JsxClosingFragment */;
        }
        ts.isJsxClosingFragment = isJsxClosingFragment;
        function isJsxAttribute(node) {
            return node.kind === 265 /* JsxAttribute */;
        }
        ts.isJsxAttribute = isJsxAttribute;
        function isJsxAttributes(node) {
            return node.kind === 266 /* JsxAttributes */;
        }
        ts.isJsxAttributes = isJsxAttributes;
        function isJsxSpreadAttribute(node) {
            return node.kind === 267 /* JsxSpreadAttribute */;
        }
        ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
        function isJsxExpression(node) {
            return node.kind === 268 /* JsxExpression */;
        }
        ts.isJsxExpression = isJsxExpression;
        // Clauses
        function isCaseClause(node) {
            return node.kind === 269 /* CaseClause */;
        }
        ts.isCaseClause = isCaseClause;
        function isDefaultClause(node) {
            return node.kind === 270 /* DefaultClause */;
        }
        ts.isDefaultClause = isDefaultClause;
        function isHeritageClause(node) {
            return node.kind === 271 /* HeritageClause */;
        }
        ts.isHeritageClause = isHeritageClause;
        function isCatchClause(node) {
            return node.kind === 272 /* CatchClause */;
        }
        ts.isCatchClause = isCatchClause;
        // Property assignments
        function isPropertyAssignment(node) {
            return node.kind === 273 /* PropertyAssignment */;
        }
        ts.isPropertyAssignment = isPropertyAssignment;
        function isShorthandPropertyAssignment(node) {
            return node.kind === 274 /* ShorthandPropertyAssignment */;
        }
        ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
        function isSpreadAssignment(node) {
            return node.kind === 275 /* SpreadAssignment */;
        }
        ts.isSpreadAssignment = isSpreadAssignment;
        // Enum
        function isEnumMember(node) {
            return node.kind === 276 /* EnumMember */;
        }
        ts.isEnumMember = isEnumMember;
        // Top-level nodes
        function isSourceFile(node) {
            return node.kind === 277 /* SourceFile */;
        }
        ts.isSourceFile = isSourceFile;
        function isBundle(node) {
            return node.kind === 278 /* Bundle */;
        }
        ts.isBundle = isBundle;
        function isUnparsedSource(node) {
            return node.kind === 279 /* UnparsedSource */;
        }
        ts.isUnparsedSource = isUnparsedSource;
        // JSDoc
        function isJSDocTypeExpression(node) {
            return node.kind === 281 /* JSDocTypeExpression */;
        }
        ts.isJSDocTypeExpression = isJSDocTypeExpression;
        function isJSDocAllType(node) {
            return node.kind === 282 /* JSDocAllType */;
        }
        ts.isJSDocAllType = isJSDocAllType;
        function isJSDocUnknownType(node) {
            return node.kind === 283 /* JSDocUnknownType */;
        }
        ts.isJSDocUnknownType = isJSDocUnknownType;
        function isJSDocNullableType(node) {
            return node.kind === 284 /* JSDocNullableType */;
        }
        ts.isJSDocNullableType = isJSDocNullableType;
        function isJSDocNonNullableType(node) {
            return node.kind === 285 /* JSDocNonNullableType */;
        }
        ts.isJSDocNonNullableType = isJSDocNonNullableType;
        function isJSDocOptionalType(node) {
            return node.kind === 286 /* JSDocOptionalType */;
        }
        ts.isJSDocOptionalType = isJSDocOptionalType;
        function isJSDocFunctionType(node) {
            return node.kind === 287 /* JSDocFunctionType */;
        }
        ts.isJSDocFunctionType = isJSDocFunctionType;
        function isJSDocVariadicType(node) {
            return node.kind === 288 /* JSDocVariadicType */;
        }
        ts.isJSDocVariadicType = isJSDocVariadicType;
        function isJSDoc(node) {
            return node.kind === 289 /* JSDocComment */;
        }
        ts.isJSDoc = isJSDoc;
        function isJSDocAugmentsTag(node) {
            return node.kind === 293 /* JSDocAugmentsTag */;
        }
        ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
        function isJSDocClassTag(node) {
            return node.kind === 294 /* JSDocClassTag */;
        }
        ts.isJSDocClassTag = isJSDocClassTag;
        function isJSDocEnumTag(node) {
            return node.kind === 296 /* JSDocEnumTag */;
        }
        ts.isJSDocEnumTag = isJSDocEnumTag;
        function isJSDocThisTag(node) {
            return node.kind === 299 /* JSDocThisTag */;
        }
        ts.isJSDocThisTag = isJSDocThisTag;
        function isJSDocParameterTag(node) {
            return node.kind === 297 /* JSDocParameterTag */;
        }
        ts.isJSDocParameterTag = isJSDocParameterTag;
        function isJSDocReturnTag(node) {
            return node.kind === 298 /* JSDocReturnTag */;
        }
        ts.isJSDocReturnTag = isJSDocReturnTag;
        function isJSDocTypeTag(node) {
            return node.kind === 300 /* JSDocTypeTag */;
        }
        ts.isJSDocTypeTag = isJSDocTypeTag;
        function isJSDocTemplateTag(node) {
            return node.kind === 301 /* JSDocTemplateTag */;
        }
        ts.isJSDocTemplateTag = isJSDocTemplateTag;
        function isJSDocTypedefTag(node) {
            return node.kind === 302 /* JSDocTypedefTag */;
        }
        ts.isJSDocTypedefTag = isJSDocTypedefTag;
        function isJSDocPropertyTag(node) {
            return node.kind === 303 /* JSDocPropertyTag */;
        }
        ts.isJSDocPropertyTag = isJSDocPropertyTag;
        function isJSDocPropertyLikeTag(node) {
            return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */;
        }
        ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
        function isJSDocTypeLiteral(node) {
            return node.kind === 290 /* JSDocTypeLiteral */;
        }
        ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
        function isJSDocCallbackTag(node) {
            return node.kind === 295 /* JSDocCallbackTag */;
        }
        ts.isJSDocCallbackTag = isJSDocCallbackTag;
        function isJSDocSignature(node) {
            return node.kind === 291 /* JSDocSignature */;
        }
        ts.isJSDocSignature = isJSDocSignature;
    })(ts || (ts = {}));
    // Node tests
    //
    // All node tests in the following list should *not* reference parent pointers so that
    // they may be used with transformations.
    (function (ts) {
        /* @internal */
        function isSyntaxList(n) {
            return n.kind === 304 /* SyntaxList */;
        }
        ts.isSyntaxList = isSyntaxList;
        /* @internal */
        function isNode(node) {
            return isNodeKind(node.kind);
        }
        ts.isNode = isNode;
        /* @internal */
        function isNodeKind(kind) {
            return kind >= 146 /* FirstNode */;
        }
        ts.isNodeKind = isNodeKind;
        /**
         * True if node is of some token syntax kind.
         * For example, this is true for an IfKeyword but not for an IfStatement.
         * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
         */
        function isToken(n) {
            return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */;
        }
        ts.isToken = isToken;
        // Node Arrays
        /* @internal */
        function isNodeArray(array) {
            return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
        }
        ts.isNodeArray = isNodeArray;
        // Literals
        /* @internal */
        function isLiteralKind(kind) {
            return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */;
        }
        ts.isLiteralKind = isLiteralKind;
        function isLiteralExpression(node) {
            return isLiteralKind(node.kind);
        }
        ts.isLiteralExpression = isLiteralExpression;
        // Pseudo-literals
        /* @internal */
        function isTemplateLiteralKind(kind) {
            return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */;
        }
        ts.isTemplateLiteralKind = isTemplateLiteralKind;
        function isTemplateLiteralToken(node) {
            return isTemplateLiteralKind(node.kind);
        }
        ts.isTemplateLiteralToken = isTemplateLiteralToken;
        function isTemplateMiddleOrTemplateTail(node) {
            var kind = node.kind;
            return kind === 15 /* TemplateMiddle */
                || kind === 16 /* TemplateTail */;
        }
        ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
        function isStringTextContainingNode(node) {
            return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
        }
        ts.isStringTextContainingNode = isStringTextContainingNode;
        // Identifiers
        /* @internal */
        function isGeneratedIdentifier(node) {
            return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
        }
        ts.isGeneratedIdentifier = isGeneratedIdentifier;
        // Keywords
        /* @internal */
        function isModifierKind(token) {
            switch (token) {
                case 117 /* AbstractKeyword */:
                case 120 /* AsyncKeyword */:
                case 76 /* ConstKeyword */:
                case 124 /* DeclareKeyword */:
                case 79 /* DefaultKeyword */:
                case 84 /* ExportKeyword */:
                case 114 /* PublicKeyword */:
                case 112 /* PrivateKeyword */:
                case 113 /* ProtectedKeyword */:
                case 132 /* ReadonlyKeyword */:
                case 115 /* StaticKeyword */:
                    return true;
            }
            return false;
        }
        ts.isModifierKind = isModifierKind;
        /* @internal */
        function isParameterPropertyModifier(kind) {
            return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
        }
        ts.isParameterPropertyModifier = isParameterPropertyModifier;
        /* @internal */
        function isClassMemberModifier(idToken) {
            return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */;
        }
        ts.isClassMemberModifier = isClassMemberModifier;
        function isModifier(node) {
            return isModifierKind(node.kind);
        }
        ts.isModifier = isModifier;
        function isEntityName(node) {
            var kind = node.kind;
            return kind === 146 /* QualifiedName */
                || kind === 71 /* Identifier */;
        }
        ts.isEntityName = isEntityName;
        function isPropertyName(node) {
            var kind = node.kind;
            return kind === 71 /* Identifier */
                || kind === 9 /* StringLiteral */
                || kind === 8 /* NumericLiteral */
                || kind === 147 /* ComputedPropertyName */;
        }
        ts.isPropertyName = isPropertyName;
        function isBindingName(node) {
            var kind = node.kind;
            return kind === 71 /* Identifier */
                || kind === 182 /* ObjectBindingPattern */
                || kind === 183 /* ArrayBindingPattern */;
        }
        ts.isBindingName = isBindingName;
        // Functions
        function isFunctionLike(node) {
            return node && isFunctionLikeKind(node.kind);
        }
        ts.isFunctionLike = isFunctionLike;
        /* @internal */
        function isFunctionLikeDeclaration(node) {
            return node && isFunctionLikeDeclarationKind(node.kind);
        }
        ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
        function isFunctionLikeDeclarationKind(kind) {
            switch (kind) {
                case 237 /* FunctionDeclaration */:
                case 154 /* MethodDeclaration */:
                case 155 /* Constructor */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 194 /* FunctionExpression */:
                case 195 /* ArrowFunction */:
                    return true;
                default:
                    return false;
            }
        }
        /* @internal */
        function isFunctionLikeKind(kind) {
            switch (kind) {
                case 153 /* MethodSignature */:
                case 158 /* CallSignature */:
                case 291 /* JSDocSignature */:
                case 159 /* ConstructSignature */:
                case 160 /* IndexSignature */:
                case 163 /* FunctionType */:
                case 287 /* JSDocFunctionType */:
                case 164 /* ConstructorType */:
                    return true;
                default:
                    return isFunctionLikeDeclarationKind(kind);
            }
        }
        ts.isFunctionLikeKind = isFunctionLikeKind;
        /* @internal */
        function isFunctionOrModuleBlock(node) {
            return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
        }
        ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
        // Classes
        function isClassElement(node) {
            var kind = node.kind;
            return kind === 155 /* Constructor */
                || kind === 152 /* PropertyDeclaration */
                || kind === 154 /* MethodDeclaration */
                || kind === 156 /* GetAccessor */
                || kind === 157 /* SetAccessor */
                || kind === 160 /* IndexSignature */
                || kind === 215 /* SemicolonClassElement */;
        }
        ts.isClassElement = isClassElement;
        function isClassLike(node) {
            return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */);
        }
        ts.isClassLike = isClassLike;
        function isAccessor(node) {
            return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */);
        }
        ts.isAccessor = isAccessor;
        /* @internal */
        function isMethodOrAccessor(node) {
            switch (node.kind) {
                case 154 /* MethodDeclaration */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                    return true;
                default:
                    return false;
            }
        }
        ts.isMethodOrAccessor = isMethodOrAccessor;
        // Type members
        function isTypeElement(node) {
            var kind = node.kind;
            return kind === 159 /* ConstructSignature */
                || kind === 158 /* CallSignature */
                || kind === 151 /* PropertySignature */
                || kind === 153 /* MethodSignature */
                || kind === 160 /* IndexSignature */;
        }
        ts.isTypeElement = isTypeElement;
        function isClassOrTypeElement(node) {
            return isTypeElement(node) || isClassElement(node);
        }
        ts.isClassOrTypeElement = isClassOrTypeElement;
        function isObjectLiteralElementLike(node) {
            var kind = node.kind;
            return kind === 273 /* PropertyAssignment */
                || kind === 274 /* ShorthandPropertyAssignment */
                || kind === 275 /* SpreadAssignment */
                || kind === 154 /* MethodDeclaration */
                || kind === 156 /* GetAccessor */
                || kind === 157 /* SetAccessor */;
        }
        ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
        // Type
        function isTypeNodeKind(kind) {
            return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */)
                || kind === 119 /* AnyKeyword */
                || kind === 142 /* UnknownKeyword */
                || kind === 134 /* NumberKeyword */
                || kind === 135 /* ObjectKeyword */
                || kind === 122 /* BooleanKeyword */
                || kind === 137 /* StringKeyword */
                || kind === 138 /* SymbolKeyword */
                || kind === 99 /* ThisKeyword */
                || kind === 105 /* VoidKeyword */
                || kind === 140 /* UndefinedKeyword */
                || kind === 95 /* NullKeyword */
                || kind === 131 /* NeverKeyword */
                || kind === 209 /* ExpressionWithTypeArguments */
                || kind === 282 /* JSDocAllType */
                || kind === 283 /* JSDocUnknownType */
                || kind === 284 /* JSDocNullableType */
                || kind === 285 /* JSDocNonNullableType */
                || kind === 286 /* JSDocOptionalType */
                || kind === 287 /* JSDocFunctionType */
                || kind === 288 /* JSDocVariadicType */;
        }
        /**
         * Node test that determines whether a node is a valid type node.
         * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
         * of a TypeNode.
         */
        function isTypeNode(node) {
            return isTypeNodeKind(node.kind);
        }
        ts.isTypeNode = isTypeNode;
        function isFunctionOrConstructorTypeNode(node) {
            switch (node.kind) {
                case 163 /* FunctionType */:
                case 164 /* ConstructorType */:
                    return true;
            }
            return false;
        }
        ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
        // Binding patterns
        /* @internal */
        function isBindingPattern(node) {
            if (node) {
                var kind = node.kind;
                return kind === 183 /* ArrayBindingPattern */
                    || kind === 182 /* ObjectBindingPattern */;
            }
            return false;
        }
        ts.isBindingPattern = isBindingPattern;
        /* @internal */
        function isAssignmentPattern(node) {
            var kind = node.kind;
            return kind === 185 /* ArrayLiteralExpression */
                || kind === 186 /* ObjectLiteralExpression */;
        }
        ts.isAssignmentPattern = isAssignmentPattern;
        /* @internal */
        function isArrayBindingElement(node) {
            var kind = node.kind;
            return kind === 184 /* BindingElement */
                || kind === 208 /* OmittedExpression */;
        }
        ts.isArrayBindingElement = isArrayBindingElement;
        /**
         * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
         */
        /* @internal */
        function isDeclarationBindingElement(bindingElement) {
            switch (bindingElement.kind) {
                case 235 /* VariableDeclaration */:
                case 149 /* Parameter */:
                case 184 /* BindingElement */:
                    return true;
            }
            return false;
        }
        ts.isDeclarationBindingElement = isDeclarationBindingElement;
        /**
         * Determines whether a node is a BindingOrAssignmentPattern
         */
        /* @internal */
        function isBindingOrAssignmentPattern(node) {
            return isObjectBindingOrAssignmentPattern(node)
                || isArrayBindingOrAssignmentPattern(node);
        }
        ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
        /**
         * Determines whether a node is an ObjectBindingOrAssignmentPattern
         */
        /* @internal */
        function isObjectBindingOrAssignmentPattern(node) {
            switch (node.kind) {
                case 182 /* ObjectBindingPattern */:
                case 186 /* ObjectLiteralExpression */:
                    return true;
            }
            return false;
        }
        ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
        /**
         * Determines whether a node is an ArrayBindingOrAssignmentPattern
         */
        /* @internal */
        function isArrayBindingOrAssignmentPattern(node) {
            switch (node.kind) {
                case 183 /* ArrayBindingPattern */:
                case 185 /* ArrayLiteralExpression */:
                    return true;
            }
            return false;
        }
        ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
        /* @internal */
        function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
            var kind = node.kind;
            return kind === 187 /* PropertyAccessExpression */
                || kind === 146 /* QualifiedName */
                || kind === 181 /* ImportType */;
        }
        ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
        // Expression
        function isPropertyAccessOrQualifiedName(node) {
            var kind = node.kind;
            return kind === 187 /* PropertyAccessExpression */
                || kind === 146 /* QualifiedName */;
        }
        ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
        function isCallLikeExpression(node) {
            switch (node.kind) {
                case 260 /* JsxOpeningElement */:
                case 259 /* JsxSelfClosingElement */:
                case 189 /* CallExpression */:
                case 190 /* NewExpression */:
                case 191 /* TaggedTemplateExpression */:
                case 150 /* Decorator */:
                    return true;
                default:
                    return false;
            }
        }
        ts.isCallLikeExpression = isCallLikeExpression;
        function isCallOrNewExpression(node) {
            return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */;
        }
        ts.isCallOrNewExpression = isCallOrNewExpression;
        function isTemplateLiteral(node) {
            var kind = node.kind;
            return kind === 204 /* TemplateExpression */
                || kind === 13 /* NoSubstitutionTemplateLiteral */;
        }
        ts.isTemplateLiteral = isTemplateLiteral;
        /* @internal */
        function isLeftHandSideExpression(node) {
            return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
        }
        ts.isLeftHandSideExpression = isLeftHandSideExpression;
        function isLeftHandSideExpressionKind(kind) {
            switch (kind) {
                case 187 /* PropertyAccessExpression */:
                case 188 /* ElementAccessExpression */:
                case 190 /* NewExpression */:
                case 189 /* CallExpression */:
                case 258 /* JsxElement */:
                case 259 /* JsxSelfClosingElement */:
                case 262 /* JsxFragment */:
                case 191 /* TaggedTemplateExpression */:
                case 185 /* ArrayLiteralExpression */:
                case 193 /* ParenthesizedExpression */:
                case 186 /* ObjectLiteralExpression */:
                case 207 /* ClassExpression */:
                case 194 /* FunctionExpression */:
                case 71 /* Identifier */:
                case 12 /* RegularExpressionLiteral */:
                case 8 /* NumericLiteral */:
                case 9 /* StringLiteral */:
                case 13 /* NoSubstitutionTemplateLiteral */:
                case 204 /* TemplateExpression */:
                case 86 /* FalseKeyword */:
                case 95 /* NullKeyword */:
                case 99 /* ThisKeyword */:
                case 101 /* TrueKeyword */:
                case 97 /* SuperKeyword */:
                case 211 /* NonNullExpression */:
                case 212 /* MetaProperty */:
                case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
                    return true;
                default:
                    return false;
            }
        }
        /* @internal */
        function isUnaryExpression(node) {
            return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
        }
        ts.isUnaryExpression = isUnaryExpression;
        function isUnaryExpressionKind(kind) {
            switch (kind) {
                case 200 /* PrefixUnaryExpression */:
                case 201 /* PostfixUnaryExpression */:
                case 196 /* DeleteExpression */:
                case 197 /* TypeOfExpression */:
                case 198 /* VoidExpression */:
                case 199 /* AwaitExpression */:
                case 192 /* TypeAssertionExpression */:
                    return true;
                default:
                    return isLeftHandSideExpressionKind(kind);
            }
        }
        /* @internal */
        function isUnaryExpressionWithWrite(expr) {
            switch (expr.kind) {
                case 201 /* PostfixUnaryExpression */:
                    return true;
                case 200 /* PrefixUnaryExpression */:
                    return expr.operator === 43 /* PlusPlusToken */ ||
                        expr.operator === 44 /* MinusMinusToken */;
                default:
                    return false;
            }
        }
        ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
        /* @internal */
        /**
         * Determines whether a node is an expression based only on its kind.
         * Use `isExpressionNode` if not in transforms.
         */
        function isExpression(node) {
            return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
        }
        ts.isExpression = isExpression;
        function isExpressionKind(kind) {
            switch (kind) {
                case 203 /* ConditionalExpression */:
                case 205 /* YieldExpression */:
                case 195 /* ArrowFunction */:
                case 202 /* BinaryExpression */:
                case 206 /* SpreadElement */:
                case 210 /* AsExpression */:
                case 208 /* OmittedExpression */:
                case 307 /* CommaListExpression */:
                case 306 /* PartiallyEmittedExpression */:
                    return true;
                default:
                    return isUnaryExpressionKind(kind);
            }
        }
        function isAssertionExpression(node) {
            var kind = node.kind;
            return kind === 192 /* TypeAssertionExpression */
                || kind === 210 /* AsExpression */;
        }
        ts.isAssertionExpression = isAssertionExpression;
        /* @internal */
        function isPartiallyEmittedExpression(node) {
            return node.kind === 306 /* PartiallyEmittedExpression */;
        }
        ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
        /* @internal */
        function isNotEmittedStatement(node) {
            return node.kind === 305 /* NotEmittedStatement */;
        }
        ts.isNotEmittedStatement = isNotEmittedStatement;
        /* @internal */
        function isNotEmittedOrPartiallyEmittedNode(node) {
            return isNotEmittedStatement(node)
                || isPartiallyEmittedExpression(node);
        }
        ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
        function isIterationStatement(node, lookInLabeledStatements) {
            switch (node.kind) {
                case 223 /* ForStatement */:
                case 224 /* ForInStatement */:
                case 225 /* ForOfStatement */:
                case 221 /* DoStatement */:
                case 222 /* WhileStatement */:
                    return true;
                case 231 /* LabeledStatement */:
                    return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
            }
            return false;
        }
        ts.isIterationStatement = isIterationStatement;
        /* @internal */
        function isForInOrOfStatement(node) {
            return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */;
        }
        ts.isForInOrOfStatement = isForInOrOfStatement;
        // Element
        /* @internal */
        function isConciseBody(node) {
            return ts.isBlock(node)
                || isExpression(node);
        }
        ts.isConciseBody = isConciseBody;
        /* @internal */
        function isFunctionBody(node) {
            return ts.isBlock(node);
        }
        ts.isFunctionBody = isFunctionBody;
        /* @internal */
        function isForInitializer(node) {
            return ts.isVariableDeclarationList(node)
                || isExpression(node);
        }
        ts.isForInitializer = isForInitializer;
        /* @internal */
        function isModuleBody(node) {
            var kind = node.kind;
            return kind === 243 /* ModuleBlock */
                || kind === 242 /* ModuleDeclaration */
                || kind === 71 /* Identifier */;
        }
        ts.isModuleBody = isModuleBody;
        /* @internal */
        function isNamespaceBody(node) {
            var kind = node.kind;
            return kind === 243 /* ModuleBlock */
                || kind === 242 /* ModuleDeclaration */;
        }
        ts.isNamespaceBody = isNamespaceBody;
        /* @internal */
        function isJSDocNamespaceBody(node) {
            var kind = node.kind;
            return kind === 71 /* Identifier */
                || kind === 242 /* ModuleDeclaration */;
        }
        ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
        /* @internal */
        function isNamedImportBindings(node) {
            var kind = node.kind;
            return kind === 250 /* NamedImports */
                || kind === 249 /* NamespaceImport */;
        }
        ts.isNamedImportBindings = isNamedImportBindings;
        /* @internal */
        function isModuleOrEnumDeclaration(node) {
            return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */;
        }
        ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
        function isDeclarationKind(kind) {
            return kind === 195 /* ArrowFunction */
                || kind === 184 /* BindingElement */
                || kind === 238 /* ClassDeclaration */
                || kind === 207 /* ClassExpression */
                || kind === 155 /* Constructor */
                || kind === 241 /* EnumDeclaration */
                || kind === 276 /* EnumMember */
                || kind === 255 /* ExportSpecifier */
                || kind === 237 /* FunctionDeclaration */
                || kind === 194 /* FunctionExpression */
                || kind === 156 /* GetAccessor */
                || kind === 248 /* ImportClause */
                || kind === 246 /* ImportEqualsDeclaration */
                || kind === 251 /* ImportSpecifier */
                || kind === 239 /* InterfaceDeclaration */
                || kind === 265 /* JsxAttribute */
                || kind === 154 /* MethodDeclaration */
                || kind === 153 /* MethodSignature */
                || kind === 242 /* ModuleDeclaration */
                || kind === 245 /* NamespaceExportDeclaration */
                || kind === 249 /* NamespaceImport */
                || kind === 149 /* Parameter */
                || kind === 273 /* PropertyAssignment */
                || kind === 152 /* PropertyDeclaration */
                || kind === 151 /* PropertySignature */
                || kind === 157 /* SetAccessor */
                || kind === 274 /* ShorthandPropertyAssignment */
                || kind === 240 /* TypeAliasDeclaration */
                || kind === 148 /* TypeParameter */
                || kind === 235 /* VariableDeclaration */
                || kind === 302 /* JSDocTypedefTag */
                || kind === 295 /* JSDocCallbackTag */
                || kind === 303 /* JSDocPropertyTag */;
        }
        function isDeclarationStatementKind(kind) {
            return kind === 237 /* FunctionDeclaration */
                || kind === 256 /* MissingDeclaration */
                || kind === 238 /* ClassDeclaration */
                || kind === 239 /* InterfaceDeclaration */
                || kind === 240 /* TypeAliasDeclaration */
                || kind === 241 /* EnumDeclaration */
                || kind === 242 /* ModuleDeclaration */
                || kind === 247 /* ImportDeclaration */
                || kind === 246 /* ImportEqualsDeclaration */
                || kind === 253 /* ExportDeclaration */
                || kind === 252 /* ExportAssignment */
                || kind === 245 /* NamespaceExportDeclaration */;
        }
        function isStatementKindButNotDeclarationKind(kind) {
            return kind === 227 /* BreakStatement */
                || kind === 226 /* ContinueStatement */
                || kind === 234 /* DebuggerStatement */
                || kind === 221 /* DoStatement */
                || kind === 219 /* ExpressionStatement */
                || kind === 218 /* EmptyStatement */
                || kind === 224 /* ForInStatement */
                || kind === 225 /* ForOfStatement */
                || kind === 223 /* ForStatement */
                || kind === 220 /* IfStatement */
                || kind === 231 /* LabeledStatement */
                || kind === 228 /* ReturnStatement */
                || kind === 230 /* SwitchStatement */
                || kind === 232 /* ThrowStatement */
                || kind === 233 /* TryStatement */
                || kind === 217 /* VariableStatement */
                || kind === 222 /* WhileStatement */
                || kind === 229 /* WithStatement */
                || kind === 305 /* NotEmittedStatement */
                || kind === 309 /* EndOfDeclarationMarker */
                || kind === 308 /* MergeDeclarationMarker */;
        }
        /* @internal */
        function isDeclaration(node) {
            if (node.kind === 148 /* TypeParameter */) {
                return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node);
            }
            return isDeclarationKind(node.kind);
        }
        ts.isDeclaration = isDeclaration;
        /* @internal */
        function isDeclarationStatement(node) {
            return isDeclarationStatementKind(node.kind);
        }
        ts.isDeclarationStatement = isDeclarationStatement;
        /**
         * Determines whether the node is a statement that is not also a declaration
         */
        /* @internal */
        function isStatementButNotDeclaration(node) {
            return isStatementKindButNotDeclarationKind(node.kind);
        }
        ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
        /* @internal */
        function isStatement(node) {
            var kind = node.kind;
            return isStatementKindButNotDeclarationKind(kind)
                || isDeclarationStatementKind(kind)
                || isBlockStatement(node);
        }
        ts.isStatement = isStatement;
        function isBlockStatement(node) {
            if (node.kind !== 216 /* Block */)
                return false;
            if (node.parent !== undefined) {
                if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) {
                    return false;
                }
            }
            return !ts.isFunctionBlock(node);
        }
        // Module references
        /* @internal */
        function isModuleReference(node) {
            var kind = node.kind;
            return kind === 257 /* ExternalModuleReference */
                || kind === 146 /* QualifiedName */
                || kind === 71 /* Identifier */;
        }
        ts.isModuleReference = isModuleReference;
        // JSX
        /* @internal */
        function isJsxTagNameExpression(node) {
            var kind = node.kind;
            return kind === 99 /* ThisKeyword */
                || kind === 71 /* Identifier */
                || kind === 187 /* PropertyAccessExpression */;
        }
        ts.isJsxTagNameExpression = isJsxTagNameExpression;
        /* @internal */
        function isJsxChild(node) {
            var kind = node.kind;
            return kind === 258 /* JsxElement */
                || kind === 268 /* JsxExpression */
                || kind === 259 /* JsxSelfClosingElement */
                || kind === 10 /* JsxText */
                || kind === 262 /* JsxFragment */;
        }
        ts.isJsxChild = isJsxChild;
        /* @internal */
        function isJsxAttributeLike(node) {
            var kind = node.kind;
            return kind === 265 /* JsxAttribute */
                || kind === 267 /* JsxSpreadAttribute */;
        }
        ts.isJsxAttributeLike = isJsxAttributeLike;
        /* @internal */
        function isStringLiteralOrJsxExpression(node) {
            var kind = node.kind;
            return kind === 9 /* StringLiteral */
                || kind === 268 /* JsxExpression */;
        }
        ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
        function isJsxOpeningLikeElement(node) {
            var kind = node.kind;
            return kind === 260 /* JsxOpeningElement */
                || kind === 259 /* JsxSelfClosingElement */;
        }
        ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
        // Clauses
        function isCaseOrDefaultClause(node) {
            var kind = node.kind;
            return kind === 269 /* CaseClause */
                || kind === 270 /* DefaultClause */;
        }
        ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
        // JSDoc
        /** True if node is of some JSDoc syntax kind. */
        /* @internal */
        function isJSDocNode(node) {
            return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */;
        }
        ts.isJSDocNode = isJSDocNode;
        /** True if node is of a kind that may contain comment text. */
        function isJSDocCommentContainingNode(node) {
            return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
        }
        ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
        // TODO: determine what this does before making it public.
        /* @internal */
        function isJSDocTag(node) {
            return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */;
        }
        ts.isJSDocTag = isJSDocTag;
        function isSetAccessor(node) {
            return node.kind === 157 /* SetAccessor */;
        }
        ts.isSetAccessor = isSetAccessor;
        function isGetAccessor(node) {
            return node.kind === 156 /* GetAccessor */;
        }
        ts.isGetAccessor = isGetAccessor;
        /** True if has jsdoc nodes attached to it. */
        /* @internal */
        // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
        function hasJSDocNodes(node) {
            var jsDoc = node.jsDoc;
            return !!jsDoc && jsDoc.length > 0;
        }
        ts.hasJSDocNodes = hasJSDocNodes;
        /** True if has type node attached to it. */
        /* @internal */
        function hasType(node) {
            return !!node.type;
        }
        ts.hasType = hasType;
        /** True if has initializer node attached to it. */
        /* @internal */
        function hasInitializer(node) {
            return !!node.initializer;
        }
        ts.hasInitializer = hasInitializer;
        /** True if has initializer node attached to it. */
        /* @internal */
        function hasOnlyExpressionInitializer(node) {
            return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node);
        }
        ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
        function isObjectLiteralElement(node) {
            return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
        }
        ts.isObjectLiteralElement = isObjectLiteralElement;
        /* @internal */
        function isTypeReferenceType(node) {
            return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */;
        }
        ts.isTypeReferenceType = isTypeReferenceType;
        var MAX_SMI_X86 = 1073741823;
        /* @internal */
        function guessIndentation(lines) {
            var indentation = MAX_SMI_X86;
            for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
                var line = lines_1[_i];
                if (!line.length) {
                    continue;
                }
                var i = 0;
                for (; i < line.length && i < indentation; i++) {
                    if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
                        break;
                    }
                }
                if (i < indentation) {
                    indentation = i;
                }
                if (indentation === 0) {
                    return 0;
                }
            }
            return indentation === MAX_SMI_X86 ? undefined : indentation;
        }
        ts.guessIndentation = guessIndentation;
        function isStringLiteralLike(node) {
            return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */;
        }
        ts.isStringLiteralLike = isStringLiteralLike;
    })(ts || (ts = {}));
    /* @internal */
    (function (ts) {
        /** @internal */
        function isNamedImportsOrExports(node) {
            return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */;
        }
        ts.isNamedImportsOrExports = isNamedImportsOrExports;
        function Symbol(flags, name) {
            this.flags = flags;
            this.escapedName = name;
            this.declarations = undefined;
            this.valueDeclaration = undefined;
            this.id = undefined;
            this.mergeId = undefined;
            this.parent = undefined;
        }
        function Type(checker, flags) {
            this.flags = flags;
            if (ts.Debug.isDebugging) {
                this.checker = checker;
            }
        }
        function Signature() { } // tslint:disable-line no-empty
        function Node(kind, pos, end) {
            this.pos = pos;
            this.end = end;
            this.kind = kind;
            this.id = 0;
            this.flags = 0 /* None */;
            this.modifierFlagsCache = 0 /* None */;
            this.transformFlags = 0 /* None */;
            this.parent = undefined;
            this.original = undefined;
        }
        function SourceMapSource(fileName, text, skipTrivia) {
            this.fileName = fileName;
            this.text = text;
            this.skipTrivia = skipTrivia || (function (pos) { return pos; });
        }
        ts.objectAllocator = {
            getNodeConstructor: function () { return Node; },
            getTokenConstructor: function () { return Node; },
            getIdentifierConstructor: function () { return Node; },
            getSourceFileConstructor: function () { return Node; },
            getSymbolConstructor: function () { return Symbol; },
            getTypeConstructor: function () { return Type; },
            getSignatureConstructor: function () { return Signature; },
            getSourceMapSourceConstructor: function () { return SourceMapSource; },
        };
        /* @internal */
        function formatStringFromArgs(text, args, baseIndex) {
            if (baseIndex === void 0) {
                baseIndex = 0;
            }
            return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); });
        }
        ts.formatStringFromArgs = formatStringFromArgs;
        function getLocaleSpecificMessage(message) {
            return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
        }
        ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
        function createFileDiagnostic(file, start, length, message) {
            ts.Debug.assertGreaterThanOrEqual(start, 0);
            ts.Debug.assertGreaterThanOrEqual(length, 0);
            if (file) {
                ts.Debug.assertLessThanOrEqual(start, file.text.length);
                ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
            }
            var text = getLocaleSpecificMessage(message);
            if (arguments.length > 4) {
                text = formatStringFromArgs(text, arguments, 4);
            }
            return {
                file: file,
                start: start,
                length: length,
                messageText: text,
                category: message.category,
                code: message.code,
                reportsUnnecessary: message.reportsUnnecessary,
            };
        }
        ts.createFileDiagnostic = createFileDiagnostic;
        /* @internal */
        function formatMessage(_dummy, message) {
            var text = getLocaleSpecificMessage(message);
            if (arguments.length > 2) {
                text = formatStringFromArgs(text, arguments, 2);
            }
            return text;
        }
        ts.formatMessage = formatMessage;
        function createCompilerDiagnostic(message) {
            var text = getLocaleSpecificMessage(message);
            if (arguments.length > 1) {
                text = formatStringFromArgs(text, arguments, 1);
            }
            return {
                file: undefined,
                start: undefined,
                length: undefined,
                messageText: text,
                category: message.category,
                code: message.code,
                reportsUnnecessary: message.reportsUnnecessary,
            };
        }
        ts.createCompilerDiagnostic = createCompilerDiagnostic;
        /* @internal */
        function createCompilerDiagnosticFromMessageChain(chain) {
            return {
                file: undefined,
                start: undefined,
                length: undefined,
                code: chain.code,
                category: chain.category,
                messageText: chain.next ? chain : chain.messageText,
            };
        }
        ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
        function chainDiagnosticMessages(details, message) {
            var text = getLocaleSpecificMessage(message);
            if (arguments.length > 2) {
                text = formatStringFromArgs(text, arguments, 2);
            }
            return {
                messageText: text,
                category: message.category,
                code: message.code,
                next: details
            };
        }
        ts.chainDiagnosticMessages = chainDiagnosticMessages;
        function concatenateDiagnosticMessageChains(headChain, tailChain) {
            var lastChain = headChain;
            while (lastChain.next) {
                lastChain = lastChain.next;
            }
            lastChain.next = tailChain;
            return headChain;
        }
        ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
        function getDiagnosticFilePath(diagnostic) {
            return diagnostic.file ? diagnostic.file.path : undefined;
        }
        /* @internal */
        function compareDiagnostics(d1, d2) {
            return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
                compareRelatedInformation(d1, d2) ||
                0 /* EqualTo */;
        }
        ts.compareDiagnostics = compareDiagnostics;
        /* @internal */
        function compareDiagnosticsSkipRelatedInformation(d1, d2) {
            return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
                ts.compareValues(d1.start, d2.start) ||
                ts.compareValues(d1.length, d2.length) ||
                ts.compareValues(d1.code, d2.code) ||
                compareMessageText(d1.messageText, d2.messageText) ||
                0 /* EqualTo */;
        }
        ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
        function compareRelatedInformation(d1, d2) {
            if (!d1.relatedInformation && !d2.relatedInformation) {
                return 0 /* EqualTo */;
            }
            if (d1.relatedInformation && d2.relatedInformation) {
                return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
                    var d2i = d2.relatedInformation[index];
                    return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
                }) || 0 /* EqualTo */;
            }
            return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
        }
        function compareMessageText(t1, t2) {
            var text1 = t1;
            var text2 = t2;
            while (text1 && text2) {
                // We still have both chains.
                var string1 = ts.isString(text1) ? text1 : text1.messageText;
                var string2 = ts.isString(text2) ? text2 : text2.messageText;
                var res = ts.compareStringsCaseSensitive(string1, string2);
                if (res) {
                    return res;
                }
                text1 = ts.isString(text1) ? undefined : text1.next;
                text2 = ts.isString(text2) ? undefined : text2.next;
            }
            if (!text1 && !text2) {
                // if the chains are done, then these messages are the same.
                return 0 /* EqualTo */;
            }
            // We still have one chain remaining.  The shorter chain should come first.
            return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */;
        }
        function getEmitScriptTarget(compilerOptions) {
            return compilerOptions.target || 0 /* ES3 */;
        }
        ts.getEmitScriptTarget = getEmitScriptTarget;
        function getEmitModuleKind(compilerOptions) {
            return typeof compilerOptions.module === "number" ?
                compilerOptions.module :
                getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
        }
        ts.getEmitModuleKind = getEmitModuleKind;
        function getEmitModuleResolutionKind(compilerOptions) {
            var moduleResolution = compilerOptions.moduleResolution;
            if (moduleResolution === undefined) {
                moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
            }
            return moduleResolution;
        }
        ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
        function hasJsonModuleEmitEnabled(options) {
            switch (getEmitModuleKind(options)) {
                case ts.ModuleKind.CommonJS:
                case ts.ModuleKind.AMD:
                case ts.ModuleKind.ES2015:
                case ts.ModuleKind.ESNext:
                    return true;
                default:
                    return false;
            }
        }
        ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
        function unreachableCodeIsError(options) {
            return options.allowUnreachableCode === false;
        }
        ts.unreachableCodeIsError = unreachableCodeIsError;
        function unusedLabelIsError(options) {
            return options.allowUnusedLabels === false;
        }
        ts.unusedLabelIsError = unusedLabelIsError;
        function getAreDeclarationMapsEnabled(options) {
            return !!(getEmitDeclarations(options) && options.declarationMap);
        }
        ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
        function getAllowSyntheticDefaultImports(compilerOptions) {
            var moduleKind = getEmitModuleKind(compilerOptions);
            return compilerOptions.allowSyntheticDefaultImports !== undefined
                ? compilerOptions.allowSyntheticDefaultImports
                : compilerOptions.esModuleInterop ||
                    moduleKind === ts.ModuleKind.System;
        }
        ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
        function getEmitDeclarations(compilerOptions) {
            return !!(compilerOptions.declaration || compilerOptions.composite);
        }
        ts.getEmitDeclarations = getEmitDeclarations;
        function getStrictOptionValue(compilerOptions, flag) {
            return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
        }
        ts.getStrictOptionValue = getStrictOptionValue;
        function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
            return oldOptions !== newOptions &&
                ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
        }
        ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
        function getCompilerOptionValue(options, option) {
            return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
        }
        ts.getCompilerOptionValue = getCompilerOptionValue;
        function hasZeroOrOneAsteriskCharacter(str) {
            var seenAsterisk = false;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) === 42 /* asterisk */) {
                    if (!seenAsterisk) {
                        seenAsterisk = true;
                    }
                    else {
                        // have already seen asterisk
                        return false;
                    }
                }
            }
            return true;
        }
        ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
        /**
         * Internally, we represent paths as strings with '/' as the directory separator.
         * When we make system calls (eg: LanguageServiceHost.getDirectory()),
         * we expect the host to correctly handle paths in our specified format.
         */
        ts.directorySeparator = "/";
        var altDirectorySeparator = "\\";
        var urlSchemeSeparator = "://";
        var backslashRegExp = /\\/g;
        /**
         * Normalize path separators.
         */
        function normalizeSlashes(path) {
            return path.replace(backslashRegExp, ts.directorySeparator);
        }
        ts.normalizeSlashes = normalizeSlashes;
        function isVolumeCharacter(charCode) {
            return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
                (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
        }
        function getFileUrlVolumeSeparatorEnd(url, start) {
            var ch0 = url.charCodeAt(start);
            if (ch0 === 58 /* colon */)
                return start + 1;
            if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
                var ch2 = url.charCodeAt(start + 2);
                if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
                    return start + 3;
            }
            return -1;
        }
        /**
         * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
         * If the root is part of a URL, the twos-complement of the root length is returned.
         */
        function getEncodedRootLength(path) {
            if (!path)
                return 0;
            var ch0 = path.charCodeAt(0);
            // POSIX or UNC
            if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
                if (path.charCodeAt(1) !== ch0)
                    return 1; // POSIX: "/" (or non-normalized "\")
                var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
                if (p1 < 0)
                    return path.length; // UNC: "//server" or "\\server"
                return p1 + 1; // UNC: "//server/" or "\\server\"
            }
            // DOS
            if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
                var ch2 = path.charCodeAt(2);
                if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
                    return 3; // DOS: "c:/" or "c:\"
                if (path.length === 2)
                    return 2; // DOS: "c:" (but not "c:d")
            }
            // URL
            var schemeEnd = path.indexOf(urlSchemeSeparator);
            if (schemeEnd !== -1) {
                var authorityStart = schemeEnd + urlSchemeSeparator.length;
                var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
                if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
                    // For local "file" URLs, include the leading DOS volume (if present).
                    // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
                    // special case interpreted as "the machine from which the URL is being interpreted".
                    var scheme = path.slice(0, schemeEnd);
                    var authority = path.slice(authorityStart, authorityEnd);
                    if (scheme === "file" && (authority === "" || authority === "localhost") &&
                        isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
                        var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
                        if (volumeSeparatorEnd !== -1) {
                            if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
                                // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
                                return ~(volumeSeparatorEnd + 1);
                            }
                            if (volumeSeparatorEnd === path.length) {
                                // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
                                // but not "file:///c:d" or "file:///c%3ad"
                                return ~volumeSeparatorEnd;
                            }
                        }
                    }
                    return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
                }
                return ~path.length; // URL: "file://server", "http://server"
            }
            // relative
            return 0;
        }
        /**
         * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
         *
         * For example:
         * ```ts
         * getRootLength("a") === 0                   // ""
         * getRootLength("/") === 1                   // "/"
         * getRootLength("c:") === 2                  // "c:"
         * getRootLength("c:d") === 0                 // ""
         * getRootLength("c:/") === 3                 // "c:/"
         * getRootLength("c:\\") === 3                // "c:\\"
         * getRootLength("//server") === 7            // "//server"
         * getRootLength("//server/share") === 8      // "//server/"
         * getRootLength("\\\\server") === 7          // "\\\\server"
         * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
         * getRootLength("file:///path") === 8        // "file:///"
         * getRootLength("file:///c:") === 10         // "file:///c:"
         * getRootLength("file:///c:d") === 8         // "file:///"
         * getRootLength("file:///c:/path") === 11    // "file:///c:/"
         * getRootLength("file://server") === 13      // "file://server"
         * getRootLength("file://server/path") === 14 // "file://server/"
         * getRootLength("http://server") === 13      // "http://server"
         * getRootLength("http://server/path") === 14 // "http://server/"
         * ```
         */
        function getRootLength(path) {
            var rootLength = getEncodedRootLength(path);
            return rootLength < 0 ? ~rootLength : rootLength;
        }
        ts.getRootLength = getRootLength;
        // TODO(rbuckton): replace references with `resolvePath`
        function normalizePath(path) {
            return ts.resolvePath(path);
        }
        ts.normalizePath = normalizePath;
        function normalizePathAndParts(path) {
            path = normalizeSlashes(path);
            var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
            if (parts.length) {
                var joinedParts = root + parts.join(ts.directorySeparator);
                return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
            }
            else {
                return { path: root, parts: parts };
            }
        }
        ts.normalizePathAndParts = normalizePathAndParts;
        function getDirectoryPath(path) {
            path = normalizeSlashes(path);
            // If the path provided is itself the root, then return it.
            var rootLength = getRootLength(path);
            if (rootLength === path.length)
                return path;
            // return the leading portion of the path up to the last (non-terminal) directory separator
            // but not including any trailing directory separator.
            path = ts.removeTrailingDirectorySeparator(path);
            return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
        }
        ts.getDirectoryPath = getDirectoryPath;
        function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
            var canonicalFileName = getCanonicalFileName(fileName);
            var canonicalDirectoryName = getCanonicalFileName(directoryName);
            return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
        }
        ts.startsWithDirectory = startsWithDirectory;
        function isUrl(path) {
            return getEncodedRootLength(path) < 0;
        }
        ts.isUrl = isUrl;
        function pathIsRelative(path) {
            return /^\.\.?($|[\\/])/.test(path);
        }
        ts.pathIsRelative = pathIsRelative;
        /**
         * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
         * like `c:`, `c:\` or `c:/`).
         */
        function isRootedDiskPath(path) {
            return getEncodedRootLength(path) > 0;
        }
        ts.isRootedDiskPath = isRootedDiskPath;
        /**
         * Determines whether a path consists only of a path root.
         */
        function isDiskPathRoot(path) {
            var rootLength = getEncodedRootLength(path);
            return rootLength > 0 && rootLength === path.length;
        }
        ts.isDiskPathRoot = isDiskPathRoot;
        /* @internal */
        function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
            return !isRootedDiskPath(absoluteOrRelativePath)
                ? absoluteOrRelativePath
                : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
        }
        ts.convertToRelativePath = convertToRelativePath;
        function pathComponents(path, rootLength) {
            var root = path.substring(0, rootLength);
            var rest = path.substring(rootLength).split(ts.directorySeparator);
            if (rest.length && !ts.lastOrUndefined(rest))
                rest.pop();
            return [root].concat(rest);
        }
        /**
         * Parse a path into an array containing a root component (at index 0) and zero or more path
         * components (at indices > 0). The result is not normalized.
         * If the path is relative, the root component is `""`.
         * If the path is absolute, the root component includes the first path separator (`/`).
         */
        function getPathComponents(path, currentDirectory) {
            if (currentDirectory === void 0) {
                currentDirectory = "";
            }
            path = ts.combinePaths(currentDirectory, path);
            var rootLength = getRootLength(path);
            return pathComponents(path, rootLength);
        }
        ts.getPathComponents = getPathComponents;
        /**
         * Reduce an array of path components to a more simplified path by navigating any
         * `"."` or `".."` entries in the path.
         */
        function reducePathComponents(components) {
            if (!ts.some(components))
                return [];
            var reduced = [components[0]];
            for (var i = 1; i < components.length; i++) {
                var component = components[i];
                if (!component)
                    continue;
                if (component === ".")
                    continue;
                if (component === "..") {
                    if (reduced.length > 1) {
                        if (reduced[reduced.length - 1] !== "..") {
                            reduced.pop();
                            continue;
                        }
                    }
                    else if (reduced[0])
                        continue;
                }
                reduced.push(component);
            }
            return reduced;
        }
        ts.reducePathComponents = reducePathComponents;
        /**
         * Parse a path into an array containing a root component (at index 0) and zero or more path
         * components (at indices > 0). The result is normalized.
         * If the path is relative, the root component is `""`.
         * If the path is absolute, the root component includes the first path separator (`/`).
         */
        function getNormalizedPathComponents(path, currentDirectory) {
            return reducePathComponents(getPathComponents(path, currentDirectory));
        }
        ts.getNormalizedPathComponents = getNormalizedPathComponents;
        function getNormalizedAbsolutePath(fileName, currentDirectory) {
            return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
        }
        ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
        /**
         * Formats a parsed path consisting of a root component (at index 0) and zero or more path
         * segments (at indices > 0).
         */
        function getPathFromPathComponents(pathComponents) {
            if (pathComponents.length === 0)
                return "";
            var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]);
            return root + pathComponents.slice(1).join(ts.directorySeparator);
        }
        ts.getPathFromPathComponents = getPathFromPathComponents;
    })(ts || (ts = {}));
    /* @internal */
    (function (ts) {
        function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
            var fromComponents = ts.reducePathComponents(ts.getPathComponents(from));
            var toComponents = ts.reducePathComponents(ts.getPathComponents(to));
            var start;
            for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
                var fromComponent = getCanonicalFileName(fromComponents[start]);
                var toComponent = getCanonicalFileName(toComponents[start]);
                var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
                if (!comparer(fromComponent, toComponent))
                    break;
            }
            if (start === 0) {
                return toComponents;
            }
            var components = toComponents.slice(start);
            var relative = [];
            for (; start < fromComponents.length; start++) {
                relative.push("..");
            }
            return [""].concat(relative, components);
        }
        ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
        function getRelativePathFromFile(from, to, getCanonicalFileName) {
            return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName));
        }
        ts.getRelativePathFromFile = getRelativePathFromFile;
        function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
            Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
            var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
            var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
            var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
            return ts.getPathFromPathComponents(pathComponents);
        }
        ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
        function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
            var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
            var firstComponent = pathComponents[0];
            if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) {
                var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
                pathComponents[0] = prefix + firstComponent;
            }
            return ts.getPathFromPathComponents(pathComponents);
        }
        ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
        /**
         * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
         * with `./` or `../`) so as not to be confused with an unprefixed module name.
         */
        function ensurePathIsNonModuleName(path) {
            return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path;
        }
        ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
        function getBaseFileName(path, extensions, ignoreCase) {
            path = ts.normalizeSlashes(path);
            // if the path provided is itself the root, then it has not file name.
            var rootLength = ts.getRootLength(path);
            if (rootLength === path.length)
                return "";
            // return the trailing portion of the path starting after the last (non-terminal) directory
            // separator but not including any trailing directory separator.
            path = removeTrailingDirectorySeparator(path);
            var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
            var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
            return extension ? name.slice(0, name.length - extension.length) : name;
        }
        ts.getBaseFileName = getBaseFileName;
        /**
         * Combines paths. If a path is absolute, it replaces any previous path.
         */
        function combinePaths(path) {
            var paths = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                paths[_i - 1] = arguments[_i];
            }
            if (path)
                path = ts.normalizeSlashes(path);
            for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
                var relativePath = paths_1[_a];
                if (!relativePath)
                    continue;
                relativePath = ts.normalizeSlashes(relativePath);
                if (!path || ts.getRootLength(relativePath) !== 0) {
                    path = relativePath;
                }
                else {
                    path = ensureTrailingDirectorySeparator(path) + relativePath;
                }
            }
            return path;
        }
        ts.combinePaths = combinePaths;
        /**
         * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
         * `.` and `..` path components are resolved.
         */
        function resolvePath(path) {
            var paths = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                paths[_i - 1] = arguments[_i];
            }
            var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path);
            var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined)));
            return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
        }
        ts.resolvePath = resolvePath;
        /**
         * Determines whether a path has a trailing separator (`/` or `\\`).
         */
        function hasTrailingDirectorySeparator(path) {
            if (path.length === 0)
                return false;
            var ch = path.charCodeAt(path.length - 1);
            return ch === 47 /* slash */ || ch === 92 /* backslash */;
        }
        ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
        function removeTrailingDirectorySeparator(path) {
            if (hasTrailingDirectorySeparator(path)) {
                return path.substr(0, path.length - 1);
            }
            return path;
        }
        ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
        function ensureTrailingDirectorySeparator(path) {
            if (!hasTrailingDirectorySeparator(path)) {
                return path + ts.directorySeparator;
            }
            return path;
        }
        ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
        function comparePathsWorker(a, b, componentComparer) {
            if (a === b)
                return 0 /* EqualTo */;
            if (a === undefined)
                return -1 /* LessThan */;
            if (b === undefined)
                return 1 /* GreaterThan */;
            var aComponents = ts.reducePathComponents(ts.getPathComponents(a));
            var bComponents = ts.reducePathComponents(ts.getPathComponents(b));
            var sharedLength = Math.min(aComponents.length, bComponents.length);
            for (var i = 0; i < sharedLength; i++) {
                var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer;
                var result = stringComparer(aComponents[i], bComponents[i]);
                if (result !== 0 /* EqualTo */) {
                    return result;
                }
            }
            return ts.compareValues(aComponents.length, bComponents.length);
        }
        /**
         * Performs a case-sensitive comparison of two paths.
         */
        function comparePathsCaseSensitive(a, b) {
            return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
        }
        ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
        /**
         * Performs a case-insensitive comparison of two paths.
         */
        function comparePathsCaseInsensitive(a, b) {
            return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
        }
        ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
        function comparePaths(a, b, currentDirectory, ignoreCase) {
            if (typeof currentDirectory === "string") {
                a = combinePaths(currentDirectory, a);
                b = combinePaths(currentDirectory, b);
            }
            else if (typeof currentDirectory === "boolean") {
                ignoreCase = currentDirectory;
            }
            return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
        }
        ts.comparePaths = comparePaths;
        function containsPath(parent, child, currentDirectory, ignoreCase) {
            if (typeof currentDirectory === "string") {
                parent = combinePaths(currentDirectory, parent);
                child = combinePaths(currentDirectory, child);
            }
            else if (typeof currentDirectory === "boolean") {
                ignoreCase = currentDirectory;
            }
            if (parent === undefined || child === undefined)
                return false;
            if (parent === child)
                return true;
            var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent));
            var childComponents = ts.reducePathComponents(ts.getPathComponents(child));
            if (childComponents.length < parentComponents.length) {
                return false;
            }
            var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
            for (var i = 0; i < parentComponents.length; i++) {
                var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
                if (!equalityComparer(parentComponents[i], childComponents[i])) {
                    return false;
                }
            }
            return true;
        }
        ts.containsPath = containsPath;
        function isDirectorySeparator(charCode) {
            return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
        }
        function stripLeadingDirectorySeparator(s) {
            return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
        }
        function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
            var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
            return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
        }
        ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
        // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
        // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
        // proof.
        var reservedCharacterPattern = /[^\w\s\/]/g;
        function regExpEscape(text) {
            return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
        }
        ts.regExpEscape = regExpEscape;
        function escapeRegExpCharacter(match) {
            return "\\" + match;
        }
        var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
        function hasExtension(fileName) {
            return ts.stringContains(getBaseFileName(fileName), ".");
        }
        ts.hasExtension = hasExtension;
        ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
        var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
        var filesMatcher = {
            /**
             * Matches any single directory segment unless it is the last segment and a .min.js file
             * Breakdown:
             *  [^./]                   # matches everything up to the first . character (excluding directory separators)
             *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
             */
            singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
            /**
             * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
             * files or directories, does not match subdirectories that start with a . character
             */
            doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
            replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
        };
        var directoriesMatcher = {
            singleAsteriskRegexFragment: "[^/]*",
            /**
             * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
             * files or directories, does not match subdirectories that start with a . character
             */
            doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
            replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
        };
        var excludeMatcher = {
            singleAsteriskRegexFragment: "[^/]*",
            doubleAsteriskRegexFragment: "(/.+?)?",
            replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
        };
        var wildcardMatchers = {
            files: filesMatcher,
            directories: directoriesMatcher,
            exclude: excludeMatcher
        };
        function getRegularExpressionForWildcard(specs, basePath, usage) {
            var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
            if (!patterns || !patterns.length) {
                return undefined;
            }
            var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
            // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
            var terminator = usage === "exclude" ? "($|/)" : "$";
            return "^(" + pattern + ")" + terminator;
        }
        ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
        function getRegularExpressionsForWildcards(specs, basePath, usage) {
            if (specs === undefined || specs.length === 0) {
                return undefined;
            }
            return ts.flatMap(specs, function (spec) {
                return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
            });
        }
        /**
         * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
         * and does not contain any glob characters itself.
         */
        function isImplicitGlob(lastPathComponent) {
            return !/[.*?]/.test(lastPathComponent);
        }
        ts.isImplicitGlob = isImplicitGlob;
        function getSubPatternFromSpec(spec, basePath, usage, _a) {
            var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
            var subpattern = "";
            var hasWrittenComponent = false;
            var components = ts.getNormalizedPathComponents(spec, basePath);
            var lastComponent = ts.last(components);
            if (usage !== "exclude" && lastComponent === "**") {
                return undefined;
            }
            // getNormalizedPathComponents includes the separator for the root component.
            // We need to remove to create our regex correctly.
            components[0] = removeTrailingDirectorySeparator(components[0]);
            if (isImplicitGlob(lastComponent)) {
                components.push("**", "*");
            }
            var optionalCount = 0;
            for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
                var component = components_1[_i];
                if (component === "**") {
                    subpattern += doubleAsteriskRegexFragment;
                }
                else {
                    if (usage === "directories") {
                        subpattern += "(";
                        optionalCount++;
                    }
                    if (hasWrittenComponent) {
                        subpattern += ts.directorySeparator;
                    }
                    if (usage !== "exclude") {
                        var componentPattern = "";
                        // The * and ? wildcards should not match directories or files that start with . if they
                        // appear first in a component. Dotted directories and files can be included explicitly
                        // like so: **/.*/.*
                        if (component.charCodeAt(0) === 42 /* asterisk */) {
                            componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
                            component = component.substr(1);
                        }
                        else if (component.charCodeAt(0) === 63 /* question */) {
                            componentPattern += "[^./]";
                            component = component.substr(1);
                        }
                        componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
                        // Patterns should not include subfolders like node_modules unless they are
                        // explicitly included as part of the path.
                        //
                        // As an optimization, if the component pattern is the same as the component,
                        // then there definitely were no wildcard characters and we do not need to
                        // add the exclusion pattern.
                        if (componentPattern !== component) {
                            subpattern += implicitExcludePathRegexPattern;
                        }
                        subpattern += componentPattern;
                    }
                    else {
                        subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
                    }
                }
                hasWrittenComponent = true;
            }
            while (optionalCount > 0) {
                subpattern += ")?";
                optionalCount--;
            }
            return subpattern;
        }
        function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
            return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
        }
        /** @param path directory of the tsconfig.json */
        function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
            path = ts.normalizePath(path);
            currentDirectory = ts.normalizePath(currentDirectory);
            var absolutePath = combinePaths(currentDirectory, path);
            return {
                includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
                includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
                includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
                excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
                basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
            };
        }
        ts.getFileMatcherPatterns = getFileMatcherPatterns;
        function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
            return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
        }
        ts.getRegexFromPattern = getRegexFromPattern;
        /** @param path directory of the tsconfig.json */
        function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
            path = ts.normalizePath(path);
            currentDirectory = ts.normalizePath(currentDirectory);
            var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
            var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
            var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
            var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
            // Associate an array of results with each include regex. This keeps results in order of the "include" order.
            // If there are no "includes", then just put everything in results[0].
            var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
            for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
                var basePath = _a[_i];
                visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
            }
            return ts.flatten(results);
            function visitDirectory(path, absolutePath, depth) {
                var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
                var _loop_1 = function (current) {
                    var name = combinePaths(path, current);
                    var absoluteName = combinePaths(absolutePath, current);
                    if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
                        return "continue";
                    if (excludeRegex && excludeRegex.test(absoluteName))
                        return "continue";
                    if (!includeFileRegexes) {
                        results[0].push(name);
                    }
                    else {
                        var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
                        if (includeIndex !== -1) {
                            results[includeIndex].push(name);
                        }
                    }
                };
                for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
                    var current = _b[_i];
                    _loop_1(current);
                }
                if (depth !== undefined) {
                    depth--;
                    if (depth === 0) {
                        return;
                    }
                }
                for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
                    var current = _d[_c];
                    var name = combinePaths(path, current);
                    var absoluteName = combinePaths(absolutePath, current);
                    if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
                        (!excludeRegex || !excludeRegex.test(absoluteName))) {
                        visitDirectory(name, absoluteName, depth);
                    }
                }
            }
        }
        ts.matchFiles = matchFiles;
        /**
         * Computes the unique non-wildcard base paths amongst the provided include patterns.
         */
        function getBasePaths(path, includes, useCaseSensitiveFileNames) {
            // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
            var basePaths = [path];
            if (includes) {
                // Storage for literal base paths amongst the include patterns.
                var includeBasePaths = [];
                for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
                    var include = includes_1[_i];
                    // We also need to check the relative paths by converting them to absolute and normalizing
                    // in case they escape the base path (e.g "..\somedirectory")
                    var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include));
                    // Append the literal and canonical candidate base paths.
                    includeBasePaths.push(getIncludeBasePath(absolute));
                }
                // Sort the offsets array using either the literal or canonical path representations.
                includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
                var _loop_2 = function (includeBasePath) {
                    if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
                        basePaths.push(includeBasePath);
                    }
                };
                // Iterate over each include base path and include unique base paths that are not a
                // subpath of an existing base path
                for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
                    var includeBasePath = includeBasePaths_1[_a];
                    _loop_2(includeBasePath);
                }
            }
            return basePaths;
        }
        function getIncludeBasePath(absolute) {
            var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
            if (wildcardOffset < 0) {
                // No "*" or "?" in the path
                return !hasExtension(absolute)
                    ? absolute
                    : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
            }
            return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
        }
        function ensureScriptKind(fileName, scriptKind) {
            // Using scriptKind as a condition handles both:
            // - 'scriptKind' is unspecified and thus it is `undefined`
            // - 'scriptKind' is set and it is `Unknown` (0)
            // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
            // to get the ScriptKind from the file name. If it cannot be resolved
            // from the file name then the default 'TS' script kind is returned.
            return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
        }
        ts.ensureScriptKind = ensureScriptKind;
        function getScriptKindFromFileName(fileName) {
            var ext = fileName.substr(fileName.lastIndexOf("."));
            switch (ext.toLowerCase()) {
                case ".js" /* Js */:
                    return 1 /* JS */;
                case ".jsx" /* Jsx */:
                    return 2 /* JSX */;
                case ".ts" /* Ts */:
                    return 3 /* TS */;
                case ".tsx" /* Tsx */:
                    return 4 /* TSX */;
                case ".json" /* Json */:
                    return 6 /* JSON */;
                default:
                    return 0 /* Unknown */;
            }
        }
        ts.getScriptKindFromFileName = getScriptKindFromFileName;
        /**
         *  List of supported extensions in order of file resolution precedence.
         */
        ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
        /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
        ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
        ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
        ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
        var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions);
        function getSupportedExtensions(options, extraFileExtensions) {
            var needJsExtensions = options && options.allowJs;
            if (!extraFileExtensions || extraFileExtensions.length === 0) {
                return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
            }
            var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
            return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
        }
        ts.getSupportedExtensions = getSupportedExtensions;
        function isJSLike(scriptKind) {
            return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
        }
        function hasJSFileExtension(fileName) {
            return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
        }
        ts.hasJSFileExtension = hasJSFileExtension;
        function hasJSOrJsonFileExtension(fileName) {
            return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); });
        }
        ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension;
        function hasTSFileExtension(fileName) {
            return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
        }
        ts.hasTSFileExtension = hasTSFileExtension;
        function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
            if (!fileName) {
                return false;
            }
            for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) {
                var extension = _a[_i];
                if (ts.fileExtensionIs(fileName, extension)) {
                    return true;
                }
            }
            return false;
        }
        ts.isSupportedSourceFileName = isSupportedSourceFileName;
        /**
         * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
         * aligned to the offset of the highest priority extension in the
         * allSupportedExtensions array.
         */
        var ExtensionPriority;
        (function (ExtensionPriority) {
            ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
            ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
            ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
            ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
        })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
        function getExtensionPriority(path, supportedExtensions) {
            for (var i = supportedExtensions.length - 1; i >= 0; i--) {
                if (ts.fileExtensionIs(path, supportedExtensions[i])) {
                    return adjustExtensionPriority(i, supportedExtensions);
                }
            }
            // If its not in the list of supported extensions, this is likely a
            // TypeScript file with a non-ts extension
            return 0 /* Highest */;
        }
        ts.getExtensionPriority = getExtensionPriority;
        /**
         * Adjusts an extension priority to be the highest priority within the same range.
         */
        function adjustExtensionPriority(extensionPriority, supportedExtensions) {
            if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
                return 0 /* TypeScriptFiles */;
            }
            else if (extensionPriority < supportedExtensions.length) {
                return 2 /* DeclarationAndJavaScriptFiles */;
            }
            else {
                return supportedExtensions.length;
            }
        }
        ts.adjustExtensionPriority = adjustExtensionPriority;
        /**
         * Gets the next lowest extension priority for a given priority.
         */
        function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
            if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
                return 2 /* DeclarationAndJavaScriptFiles */;
            }
            else {
                return supportedExtensions.length;
            }
        }
        ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
        var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
        function removeFileExtension(path) {
            for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
                var ext = extensionsToRemove_1[_i];
                var extensionless = tryRemoveExtension(path, ext);
                if (extensionless !== undefined) {
                    return extensionless;
                }
            }
            return path;
        }
        ts.removeFileExtension = removeFileExtension;
        function tryRemoveExtension(path, extension) {
            return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
        }
        ts.tryRemoveExtension = tryRemoveExtension;
        function removeExtension(path, extension) {
            return path.substring(0, path.length - extension.length);
        }
        ts.removeExtension = removeExtension;
        function changeExtension(path, newExtension) {
            return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
        }
        ts.changeExtension = changeExtension;
        function changeAnyExtension(path, ext, extensions, ignoreCase) {
            var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
            return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
        }
        ts.changeAnyExtension = changeAnyExtension;
        var Debug;
        (function (Debug) {
            function showSymbol(symbol) {
                var symbolFlags = ts.SymbolFlags;
                return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }";
            }
            Debug.showSymbol = showSymbol;
            function showFlags(flags, flagsEnum) {
                var out = [];
                for (var pow = 0; pow <= 30; pow++) {
                    var n = 1 << pow;
                    if (flags & n) {
                        out.push(flagsEnum[n]);
                    }
                }
                return out.join("|");
            }
            function showSyntaxKind(node) {
                var syntaxKind = ts.SyntaxKind;
                return syntaxKind ? syntaxKind[node.kind] : node.kind.toString();
            }
            Debug.showSyntaxKind = showSyntaxKind;
        })(Debug = ts.Debug || (ts.Debug = {}));
        function tryParsePattern(pattern) {
            // This should be verified outside of here and a proper error thrown.
            Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
            var indexOfStar = pattern.indexOf("*");
            return indexOfStar === -1 ? undefined : {
                prefix: pattern.substr(0, indexOfStar),
                suffix: pattern.substr(indexOfStar + 1)
            };
        }
        ts.tryParsePattern = tryParsePattern;
        function positionIsSynthesized(pos) {
            // This is a fast way of testing the following conditions:
            //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
            return !(pos >= 0);
        }
        ts.positionIsSynthesized = positionIsSynthesized;
        /** True if an extension is one of the supported TypeScript extensions. */
        function extensionIsTS(ext) {
            return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
        }
        ts.extensionIsTS = extensionIsTS;
        function resolutionExtensionIsTSOrJson(ext) {
            return extensionIsTS(ext) || ext === ".json" /* Json */;
        }
        ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
        /**
         * Gets the extension from a path.
         * Path must have a valid extension.
         */
        function extensionFromPath(path) {
            var ext = tryGetExtensionFromPath(path);
            return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension.");
        }
        ts.extensionFromPath = extensionFromPath;
        function isAnySupportedFileExtension(path) {
            return tryGetExtensionFromPath(path) !== undefined;
        }
        ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
        function tryGetExtensionFromPath(path) {
            return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
        }
        ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
        function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
            if (typeof extensions === "string")
                extensions = [extensions];
            for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
                var extension = extensions_2[_i];
                if (!ts.startsWith(extension, "."))
                    extension = "." + extension;
                if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
                    var pathExtension = path.slice(path.length - extension.length);
                    if (stringEqualityComparer(pathExtension, extension)) {
                        return pathExtension;
                    }
                }
            }
            return "";
        }
        function getAnyExtensionFromPath(path, extensions, ignoreCase) {
            // Retrieves any string from the final "." onwards from a base file name.
            // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
            if (extensions) {
                return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
            }
            var baseFileName = getBaseFileName(path);
            var extensionIndex = baseFileName.lastIndexOf(".");
            if (extensionIndex >= 0) {
                return baseFileName.substring(extensionIndex);
            }
            return "";
        }
        ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
        function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
            return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
        }
        ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
        ts.emptyFileSystemEntries = {
            files: ts.emptyArray,
            directories: ts.emptyArray
        };
        /**
         * patternStrings contains both pattern strings (containing "*") and regular strings.
         * Return an exact match if possible, or a pattern match, or undefined.
         * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
         */
        function matchPatternOrExact(patternStrings, candidate) {
            var patterns = [];
            for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
                var patternString = patternStrings_1[_i];
                var pattern = tryParsePattern(patternString);
                if (pattern) {
                    patterns.push(pattern);
                }
                else if (patternString === candidate) {
                    // pattern was matched as is - no need to search further
                    return patternString;
                }
            }
            return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
        }
        ts.matchPatternOrExact = matchPatternOrExact;
        function sliceAfter(arr, value) {
            var index = arr.indexOf(value);
            Debug.assert(index !== -1);
            return arr.slice(index);
        }
        ts.sliceAfter = sliceAfter;
        function minAndMax(arr, getValue) {
            Debug.assert(arr.length !== 0);
            var min = getValue(arr[0]);
            var max = min;
            for (var i = 1; i < arr.length; i++) {
                var value = getValue(arr[i]);
                if (value < min) {
                    min = value;
                }
                else if (value > max) {
                    max = value;
                }
            }
            return { min: min, max: max };
        }
        ts.minAndMax = minAndMax;
        var NodeSet = /** @class */ (function () {
            function NodeSet() {
                this.map = ts.createMap();
            }
            NodeSet.prototype.add = function (node) {
                this.map.set(String(ts.getNodeId(node)), node);
            };
            NodeSet.prototype.tryAdd = function (node) {
                if (this.has(node))
                    return false;
                this.add(node);
                return true;
            };
            NodeSet.prototype.has = function (node) {
                return this.map.has(String(ts.getNodeId(node)));
            };
            NodeSet.prototype.forEach = function (cb) {
                this.map.forEach(cb);
            };
            NodeSet.prototype.some = function (pred) {
                return ts.forEachEntry(this.map, pred) || false;
            };
            return NodeSet;
        }());
        ts.NodeSet = NodeSet;
        var NodeMap = /** @class */ (function () {
            function NodeMap() {
                this.map = ts.createMap();
            }
            NodeMap.prototype.get = function (node) {
                var res = this.map.get(String(ts.getNodeId(node)));
                return res && res.value;
            };
            NodeMap.prototype.getOrUpdate = function (node, setValue) {
                var res = this.get(node);
                if (res)
                    return res;
                var value = setValue();
                this.set(node, value);
                return value;
            };
            NodeMap.prototype.set = function (node, value) {
                this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
            };
            NodeMap.prototype.has = function (node) {
                return this.map.has(String(ts.getNodeId(node)));
            };
            NodeMap.prototype.forEach = function (cb) {
                this.map.forEach(function (_a) {
                    var node = _a.node, value = _a.value;
                    return cb(value, node);
                });
            };
            return NodeMap;
        }());
        ts.NodeMap = NodeMap;
        function rangeOfNode(node) {
            return { pos: ts.getTokenPosOfNode(node), end: node.end };
        }
        ts.rangeOfNode = rangeOfNode;
        function rangeOfTypeParameters(typeParameters) {
            // Include the `<>`
            return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
        }
        ts.rangeOfTypeParameters = rangeOfTypeParameters;
        function skipTypeChecking(sourceFile, options) {
            // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
            // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
            // '/// <reference no-default-lib="true"/>' directive.
            return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib;
        }
        ts.skipTypeChecking = skipTypeChecking;
        function isJsonEqual(a, b) {
            return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
        }
        ts.isJsonEqual = isJsonEqual;
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        var SignatureFlags;
        (function (SignatureFlags) {
            SignatureFlags[SignatureFlags["None"] = 0] = "None";
            SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
            SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
            SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
            SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
            SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
        })(SignatureFlags || (SignatureFlags = {}));
        // tslint:disable variable-name
        var NodeConstructor;
        var TokenConstructor;
        var IdentifierConstructor;
        var SourceFileConstructor;
        // tslint:enable variable-name
        function createNode(kind, pos, end) {
            if (kind === 277 /* SourceFile */) {
                return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
            }
            else if (kind === 71 /* Identifier */) {
                return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
            }
            else if (!ts.isNodeKind(kind)) {
                return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
            }
            else {
                return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
            }
        }
        ts.createNode = createNode;
        function visitNode(cbNode, node) {
            return node && cbNode(node);
        }
        function visitNodes(cbNode, cbNodes, nodes) {
            if (nodes) {
                if (cbNodes) {
                    return cbNodes(nodes);
                }
                for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
                    var node = nodes_1[_i];
                    var result = cbNode(node);
                    if (result) {
                        return result;
                    }
                }
            }
        }
        /*@internal*/
        function isJSDocLikeText(text, start) {
            return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
                text.charCodeAt(start + 2) === 42 /* asterisk */ &&
                text.charCodeAt(start + 3) !== 47 /* slash */;
        }
        ts.isJSDocLikeText = isJSDocLikeText;
        /**
         * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
         * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
         * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
         * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
         *
         * @param node a given node to visit its children
         * @param cbNode a callback to be invoked for all child nodes
         * @param cbNodes a callback to be invoked for embedded array
         *
         * @remarks `forEachChild` must visit the children of a node in the order
         * that they appear in the source code. The language service depends on this property to locate nodes by position.
         */
        function forEachChild(node, cbNode, cbNodes) {
            if (!node || node.kind <= 145 /* LastToken */) {
                return;
            }
            switch (node.kind) {
                case 146 /* QualifiedName */:
                    return visitNode(cbNode, node.left) ||
                        visitNode(cbNode, node.right);
                case 148 /* TypeParameter */:
                    return visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.constraint) ||
                        visitNode(cbNode, node.default) ||
                        visitNode(cbNode, node.expression);
                case 274 /* ShorthandPropertyAssignment */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.exclamationToken) ||
                        visitNode(cbNode, node.equalsToken) ||
                        visitNode(cbNode, node.objectAssignmentInitializer);
                case 275 /* SpreadAssignment */:
                    return visitNode(cbNode, node.expression);
                case 149 /* Parameter */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.dotDotDotToken) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.type) ||
                        visitNode(cbNode, node.initializer);
                case 152 /* PropertyDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.exclamationToken) ||
                        visitNode(cbNode, node.type) ||
                        visitNode(cbNode, node.initializer);
                case 151 /* PropertySignature */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.type) ||
                        visitNode(cbNode, node.initializer);
                case 273 /* PropertyAssignment */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.initializer);
                case 235 /* VariableDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.exclamationToken) ||
                        visitNode(cbNode, node.type) ||
                        visitNode(cbNode, node.initializer);
                case 184 /* BindingElement */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.dotDotDotToken) ||
                        visitNode(cbNode, node.propertyName) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.initializer);
                case 163 /* FunctionType */:
                case 164 /* ConstructorType */:
                case 158 /* CallSignature */:
                case 159 /* ConstructSignature */:
                case 160 /* IndexSignature */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNodes(cbNode, cbNodes, node.typeParameters) ||
                        visitNodes(cbNode, cbNodes, node.parameters) ||
                        visitNode(cbNode, node.type);
                case 154 /* MethodDeclaration */:
                case 153 /* MethodSignature */:
                case 155 /* Constructor */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 194 /* FunctionExpression */:
                case 237 /* FunctionDeclaration */:
                case 195 /* ArrowFunction */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.asteriskToken) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.exclamationToken) ||
                        visitNodes(cbNode, cbNodes, node.typeParameters) ||
                        visitNodes(cbNode, cbNodes, node.parameters) ||
                        visitNode(cbNode, node.type) ||
                        visitNode(cbNode, node.equalsGreaterThanToken) ||
                        visitNode(cbNode, node.body);
                case 162 /* TypeReference */:
                    return visitNode(cbNode, node.typeName) ||
                        visitNodes(cbNode, cbNodes, node.typeArguments);
                case 161 /* TypePredicate */:
                    return visitNode(cbNode, node.parameterName) ||
                        visitNode(cbNode, node.type);
                case 165 /* TypeQuery */:
                    return visitNode(cbNode, node.exprName);
                case 166 /* TypeLiteral */:
                    return visitNodes(cbNode, cbNodes, node.members);
                case 167 /* ArrayType */:
                    return visitNode(cbNode, node.elementType);
                case 168 /* TupleType */:
                    return visitNodes(cbNode, cbNodes, node.elementTypes);
                case 171 /* UnionType */:
                case 172 /* IntersectionType */:
                    return visitNodes(cbNode, cbNodes, node.types);
                case 173 /* ConditionalType */:
                    return visitNode(cbNode, node.checkType) ||
                        visitNode(cbNode, node.extendsType) ||
                        visitNode(cbNode, node.trueType) ||
                        visitNode(cbNode, node.falseType);
                case 174 /* InferType */:
                    return visitNode(cbNode, node.typeParameter);
                case 181 /* ImportType */:
                    return visitNode(cbNode, node.argument) ||
                        visitNode(cbNode, node.qualifier) ||
                        visitNodes(cbNode, cbNodes, node.typeArguments);
                case 175 /* ParenthesizedType */:
                case 177 /* TypeOperator */:
                    return visitNode(cbNode, node.type);
                case 178 /* IndexedAccessType */:
                    return visitNode(cbNode, node.objectType) ||
                        visitNode(cbNode, node.indexType);
                case 179 /* MappedType */:
                    return visitNode(cbNode, node.readonlyToken) ||
                        visitNode(cbNode, node.typeParameter) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.type);
                case 180 /* LiteralType */:
                    return visitNode(cbNode, node.literal);
                case 182 /* ObjectBindingPattern */:
                case 183 /* ArrayBindingPattern */:
                    return visitNodes(cbNode, cbNodes, node.elements);
                case 185 /* ArrayLiteralExpression */:
                    return visitNodes(cbNode, cbNodes, node.elements);
                case 186 /* ObjectLiteralExpression */:
                    return visitNodes(cbNode, cbNodes, node.properties);
                case 187 /* PropertyAccessExpression */:
                    return visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.name);
                case 188 /* ElementAccessExpression */:
                    return visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.argumentExpression);
                case 189 /* CallExpression */:
                case 190 /* NewExpression */:
                    return visitNode(cbNode, node.expression) ||
                        visitNodes(cbNode, cbNodes, node.typeArguments) ||
                        visitNodes(cbNode, cbNodes, node.arguments);
                case 191 /* TaggedTemplateExpression */:
                    return visitNode(cbNode, node.tag) ||
                        visitNodes(cbNode, cbNodes, node.typeArguments) ||
                        visitNode(cbNode, node.template);
                case 192 /* TypeAssertionExpression */:
                    return visitNode(cbNode, node.type) ||
                        visitNode(cbNode, node.expression);
                case 193 /* ParenthesizedExpression */:
                    return visitNode(cbNode, node.expression);
                case 196 /* DeleteExpression */:
                    return visitNode(cbNode, node.expression);
                case 197 /* TypeOfExpression */:
                    return visitNode(cbNode, node.expression);
                case 198 /* VoidExpression */:
                    return visitNode(cbNode, node.expression);
                case 200 /* PrefixUnaryExpression */:
                    return visitNode(cbNode, node.operand);
                case 205 /* YieldExpression */:
                    return visitNode(cbNode, node.asteriskToken) ||
                        visitNode(cbNode, node.expression);
                case 199 /* AwaitExpression */:
                    return visitNode(cbNode, node.expression);
                case 201 /* PostfixUnaryExpression */:
                    return visitNode(cbNode, node.operand);
                case 202 /* BinaryExpression */:
                    return visitNode(cbNode, node.left) ||
                        visitNode(cbNode, node.operatorToken) ||
                        visitNode(cbNode, node.right);
                case 210 /* AsExpression */:
                    return visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.type);
                case 211 /* NonNullExpression */:
                    return visitNode(cbNode, node.expression);
                case 212 /* MetaProperty */:
                    return visitNode(cbNode, node.name);
                case 203 /* ConditionalExpression */:
                    return visitNode(cbNode, node.condition) ||
                        visitNode(cbNode, node.questionToken) ||
                        visitNode(cbNode, node.whenTrue) ||
                        visitNode(cbNode, node.colonToken) ||
                        visitNode(cbNode, node.whenFalse);
                case 206 /* SpreadElement */:
                    return visitNode(cbNode, node.expression);
                case 216 /* Block */:
                case 243 /* ModuleBlock */:
                    return visitNodes(cbNode, cbNodes, node.statements);
                case 277 /* SourceFile */:
                    return visitNodes(cbNode, cbNodes, node.statements) ||
                        visitNode(cbNode, node.endOfFileToken);
                case 217 /* VariableStatement */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.declarationList);
                case 236 /* VariableDeclarationList */:
                    return visitNodes(cbNode, cbNodes, node.declarations);
                case 219 /* ExpressionStatement */:
                    return visitNode(cbNode, node.expression);
                case 220 /* IfStatement */:
                    return visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.thenStatement) ||
                        visitNode(cbNode, node.elseStatement);
                case 221 /* DoStatement */:
                    return visitNode(cbNode, node.statement) ||
                        visitNode(cbNode, node.expression);
                case 222 /* WhileStatement */:
                    return visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.statement);
                case 223 /* ForStatement */:
                    return visitNode(cbNode, node.initializer) ||
                        visitNode(cbNode, node.condition) ||
                        visitNode(cbNode, node.incrementor) ||
                        visitNode(cbNode, node.statement);
                case 224 /* ForInStatement */:
                    return visitNode(cbNode, node.initializer) ||
                        visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.statement);
                case 225 /* ForOfStatement */:
                    return visitNode(cbNode, node.awaitModifier) ||
                        visitNode(cbNode, node.initializer) ||
                        visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.statement);
                case 226 /* ContinueStatement */:
                case 227 /* BreakStatement */:
                    return visitNode(cbNode, node.label);
                case 228 /* ReturnStatement */:
                    return visitNode(cbNode, node.expression);
                case 229 /* WithStatement */:
                    return visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.statement);
                case 230 /* SwitchStatement */:
                    return visitNode(cbNode, node.expression) ||
                        visitNode(cbNode, node.caseBlock);
                case 244 /* CaseBlock */:
                    return visitNodes(cbNode, cbNodes, node.clauses);
                case 269 /* CaseClause */:
                    return visitNode(cbNode, node.expression) ||
                        visitNodes(cbNode, cbNodes, node.statements);
                case 270 /* DefaultClause */:
                    return visitNodes(cbNode, cbNodes, node.statements);
                case 231 /* LabeledStatement */:
                    return visitNode(cbNode, node.label) ||
                        visitNode(cbNode, node.statement);
                case 232 /* ThrowStatement */:
                    return visitNode(cbNode, node.expression);
                case 233 /* TryStatement */:
                    return visitNode(cbNode, node.tryBlock) ||
                        visitNode(cbNode, node.catchClause) ||
                        visitNode(cbNode, node.finallyBlock);
                case 272 /* CatchClause */:
                    return visitNode(cbNode, node.variableDeclaration) ||
                        visitNode(cbNode, node.block);
                case 150 /* Decorator */:
                    return visitNode(cbNode, node.expression);
                case 238 /* ClassDeclaration */:
                case 207 /* ClassExpression */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNodes(cbNode, cbNodes, node.typeParameters) ||
                        visitNodes(cbNode, cbNodes, node.heritageClauses) ||
                        visitNodes(cbNode, cbNodes, node.members);
                case 239 /* InterfaceDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNodes(cbNode, cbNodes, node.typeParameters) ||
                        visitNodes(cbNode, cbNodes, node.heritageClauses) ||
                        visitNodes(cbNode, cbNodes, node.members);
                case 240 /* TypeAliasDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNodes(cbNode, cbNodes, node.typeParameters) ||
                        visitNode(cbNode, node.type);
                case 241 /* EnumDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNodes(cbNode, cbNodes, node.members);
                case 276 /* EnumMember */:
                    return visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.initializer);
                case 242 /* ModuleDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.body);
                case 246 /* ImportEqualsDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.moduleReference);
                case 247 /* ImportDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.importClause) ||
                        visitNode(cbNode, node.moduleSpecifier);
                case 248 /* ImportClause */:
                    return visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.namedBindings);
                case 245 /* NamespaceExportDeclaration */:
                    return visitNode(cbNode, node.name);
                case 249 /* NamespaceImport */:
                    return visitNode(cbNode, node.name);
                case 250 /* NamedImports */:
                case 254 /* NamedExports */:
                    return visitNodes(cbNode, cbNodes, node.elements);
                case 253 /* ExportDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.exportClause) ||
                        visitNode(cbNode, node.moduleSpecifier);
                case 251 /* ImportSpecifier */:
                case 255 /* ExportSpecifier */:
                    return visitNode(cbNode, node.propertyName) ||
                        visitNode(cbNode, node.name);
                case 252 /* ExportAssignment */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        visitNode(cbNode, node.expression);
                case 204 /* TemplateExpression */:
                    return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
                case 214 /* TemplateSpan */:
                    return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
                case 147 /* ComputedPropertyName */:
                    return visitNode(cbNode, node.expression);
                case 271 /* HeritageClause */:
                    return visitNodes(cbNode, cbNodes, node.types);
                case 209 /* ExpressionWithTypeArguments */:
                    return visitNode(cbNode, node.expression) ||
                        visitNodes(cbNode, cbNodes, node.typeArguments);
                case 257 /* ExternalModuleReference */:
                    return visitNode(cbNode, node.expression);
                case 256 /* MissingDeclaration */:
                    return visitNodes(cbNode, cbNodes, node.decorators);
                case 307 /* CommaListExpression */:
                    return visitNodes(cbNode, cbNodes, node.elements);
                case 258 /* JsxElement */:
                    return visitNode(cbNode, node.openingElement) ||
                        visitNodes(cbNode, cbNodes, node.children) ||
                        visitNode(cbNode, node.closingElement);
                case 262 /* JsxFragment */:
                    return visitNode(cbNode, node.openingFragment) ||
                        visitNodes(cbNode, cbNodes, node.children) ||
                        visitNode(cbNode, node.closingFragment);
                case 259 /* JsxSelfClosingElement */:
                case 260 /* JsxOpeningElement */:
                    return visitNode(cbNode, node.tagName) ||
                        visitNodes(cbNode, cbNodes, node.typeArguments) ||
                        visitNode(cbNode, node.attributes);
                case 266 /* JsxAttributes */:
                    return visitNodes(cbNode, cbNodes, node.properties);
                case 265 /* JsxAttribute */:
                    return visitNode(cbNode, node.name) ||
                        visitNode(cbNode, node.initializer);
                case 267 /* JsxSpreadAttribute */:
                    return visitNode(cbNode, node.expression);
                case 268 /* JsxExpression */:
                    return visitNode(cbNode, node.dotDotDotToken) ||
                        visitNode(cbNode, node.expression);
                case 261 /* JsxClosingElement */:
                    return visitNode(cbNode, node.tagName);
                case 169 /* OptionalType */:
                case 170 /* RestType */:
                case 281 /* JSDocTypeExpression */:
                case 285 /* JSDocNonNullableType */:
                case 284 /* JSDocNullableType */:
                case 286 /* JSDocOptionalType */:
                case 288 /* JSDocVariadicType */:
                    return visitNode(cbNode, node.type);
                case 287 /* JSDocFunctionType */:
                    return visitNodes(cbNode, cbNodes, node.parameters) ||
                        visitNode(cbNode, node.type);
                case 289 /* JSDocComment */:
                    return visitNodes(cbNode, cbNodes, node.tags);
                case 297 /* JSDocParameterTag */:
                case 303 /* JSDocPropertyTag */:
                    if (node.isNameFirst) {
                        return visitNode(cbNode, node.name) ||
                            visitNode(cbNode, node.typeExpression);
                    }
                    else {
                        return visitNode(cbNode, node.typeExpression) ||
                            visitNode(cbNode, node.name);
                    }
                case 298 /* JSDocReturnTag */:
                    return visitNode(cbNode, node.typeExpression);
                case 300 /* JSDocTypeTag */:
                    return visitNode(cbNode, node.typeExpression);
                case 293 /* JSDocAugmentsTag */:
                    return visitNode(cbNode, node.class);
                case 301 /* JSDocTemplateTag */:
                    return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters);
                case 302 /* JSDocTypedefTag */:
                    if (node.typeExpression &&
                        node.typeExpression.kind === 281 /* JSDocTypeExpression */) {
                        return visitNode(cbNode, node.typeExpression) ||
                            visitNode(cbNode, node.fullName);
                    }
                    else {
                        return visitNode(cbNode, node.fullName) ||
                            visitNode(cbNode, node.typeExpression);
                    }
                case 295 /* JSDocCallbackTag */:
                    return visitNode(cbNode, node.fullName) ||
                        visitNode(cbNode, node.typeExpression);
                case 299 /* JSDocThisTag */:
                    return visitNode(cbNode, node.typeExpression);
                case 296 /* JSDocEnumTag */:
                    return visitNode(cbNode, node.typeExpression);
                case 291 /* JSDocSignature */:
                    return visitNodes(cbNode, cbNodes, node.decorators) ||
                        visitNodes(cbNode, cbNodes, node.modifiers) ||
                        ts.forEach(node.typeParameters, cbNode) ||
                        ts.forEach(node.parameters, cbNode) ||
                        visitNode(cbNode, node.type);
                case 290 /* JSDocTypeLiteral */:
                    if (node.jsDocPropertyTags) {
                        for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
                            var tag = _a[_i];
                            visitNode(cbNode, tag);
                        }
                    }
                    return;
                case 306 /* PartiallyEmittedExpression */:
                    return visitNode(cbNode, node.expression);
            }
        }
        ts.forEachChild = forEachChild;
        function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
            if (setParentNodes === void 0) {
                setParentNodes = false;
            }
            ts.performance.mark("beforeParse");
            var result;
            if (languageVersion === 100 /* JSON */) {
                result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
            }
            else {
                result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
            }
            ts.performance.mark("afterParse");
            ts.performance.measure("Parse", "beforeParse", "afterParse");
            return result;
        }
        ts.createSourceFile = createSourceFile;
        function parseIsolatedEntityName(text, languageVersion) {
            return Parser.parseIsolatedEntityName(text, languageVersion);
        }
        ts.parseIsolatedEntityName = parseIsolatedEntityName;
        /**
         * Parse json text into SyntaxTree and return node and parse errors if any
         * @param fileName
         * @param sourceText
         */
        function parseJsonText(fileName, sourceText) {
            return Parser.parseJsonText(fileName, sourceText);
        }
        ts.parseJsonText = parseJsonText;
        // See also `isExternalOrCommonJsModule` in utilities.ts
        function isExternalModule(file) {
            return file.externalModuleIndicator !== undefined;
        }
        ts.isExternalModule = isExternalModule;
        // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
        // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
        // The SourceFile will be created with the compiler attempting to reuse as many nodes from
        // this file as possible.
        //
        // Note: this function mutates nodes from this SourceFile. That means any existing nodes
        // from this SourceFile that are being held onto may change as a result (including
        // becoming detached from any SourceFile).  It is recommended that this SourceFile not
        // be used once 'update' is called on it.
        function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
            if (aggressiveChecks === void 0) {
                aggressiveChecks = false;
            }
            var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
            // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import.
            // We will manually port the flag to the new source file.
            newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */);
            return newSourceFile;
        }
        ts.updateSourceFile = updateSourceFile;
        /* @internal */
        function parseIsolatedJSDocComment(content, start, length) {
            var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
            if (result && result.jsDoc) {
                // because the jsDocComment was parsed out of the source file, it might
                // not be covered by the fixupParentReferences.
                Parser.fixupParentReferences(result.jsDoc);
            }
            return result;
        }
        ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
        /* @internal */
        // Exposed only for testing.
        function parseJSDocTypeExpressionForTests(content, start, length) {
            return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
        }
        ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
        // Implement the parser as a singleton module.  We do this for perf reasons because creating
        // parser instances can actually be expensive enough to impact us on projects with many source
        // files.
        var Parser;
        (function (Parser) {
            // Share a single scanner across all calls to parse a source file.  This helps speed things
            // up by avoiding the cost of creating/compiling scanners over and over again.
            var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
            var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
            // capture constructors in 'initializeState' to avoid null checks
            // tslint:disable variable-name
            var NodeConstructor;
            var TokenConstructor;
            var IdentifierConstructor;
            var SourceFileConstructor;
            // tslint:enable variable-name
            var sourceFile;
            var parseDiagnostics;
            var syntaxCursor;
            var currentToken;
            var sourceText;
            var nodeCount;
            var identifiers;
            var identifierCount;
            var parsingContext;
            // Flags that dictate what parsing context we're in.  For example:
            // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
            // that some tokens that would be considered identifiers may be considered keywords.
            //
            // When adding more parser context flags, consider which is the more common case that the
            // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
            // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
            // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
            // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
            // all nodes would need extra state on them to store this info.
            //
            // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
            // grammar specification.
            //
            // An important thing about these context concepts.  By default they are effectively inherited
            // while parsing through every grammar production.  i.e. if you don't change them, then when
            // you parse a sub-production, it will have the same context values as the parent production.
            // This is great most of the time.  After all, consider all the 'expression' grammar productions
            // and how nearly all of them pass along the 'in' and 'yield' context values:
            //
            // EqualityExpression[In, Yield] :
            //      RelationalExpression[?In, ?Yield]
            //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
            //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
            //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
            //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
            //
            // Where you have to be careful is then understanding what the points are in the grammar
            // where the values are *not* passed along.  For example:
            //
            // SingleNameBinding[Yield,GeneratorParameter]
            //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
            //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
            //
            // Here this is saying that if the GeneratorParameter context flag is set, that we should
            // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
            // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
            // production.  Conversely, if the GeneratorParameter context flag is not set, then we
            // should leave the 'yield' context flag alone.
            //
            // Getting this all correct is tricky and requires careful reading of the grammar to
            // understand when these values should be changed versus when they should be inherited.
            //
            // Note: it should not be necessary to save/restore these flags during speculative/lookahead
            // parsing.  These context flags are naturally stored and restored through normal recursive
            // descent parsing and unwinding.
            var contextFlags;
            // Whether or not we've had a parse error since creating the last AST node.  If we have
            // encountered an error, it will be stored on the next AST node we create.  Parse errors
            // can be broken down into three categories:
            //
            // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
            //    character that was completely not understood.
            //
            // 2) A token was expected, but was not present.  This type of error is commonly produced
            //    by the 'parseExpected' function.
            //
            // 3) A token was present that no parsing function was able to consume.  This type of error
            //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
            //    decides to skip the token.
            //
            // In all of these cases, we want to mark the next node as having had an error before it.
            // With this mark, we can know in incremental settings if this node can be reused, or if
            // we have to reparse it.  If we don't keep this information around, we may just reuse the
            // node.  in that event we would then not produce the same errors as we did before, causing
            // significant confusion problems.
            //
            // Note: it is necessary that this value be saved/restored during speculative/lookahead
            // parsing.  During lookahead parsing, we will often create a node.  That node will have
            // this value attached, and then this value will be set back to 'false'.  If we decide to
            // rewind, we must get back to the same value we had prior to the lookahead.
            //
            // Note: any errors at the end of the file that do not precede a regular node, should get
            // attached to the EOF token.
            var parseErrorBeforeNextFinishedNode = false;
            function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
                if (setParentNodes === void 0) {
                    setParentNodes = false;
                }
                scriptKind = ts.ensureScriptKind(fileName, scriptKind);
                if (scriptKind === 6 /* JSON */) {
                    var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
                    ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
                    result_1.referencedFiles = ts.emptyArray;
                    result_1.typeReferenceDirectives = ts.emptyArray;
                    result_1.libReferenceDirectives = ts.emptyArray;
                    result_1.amdDependencies = ts.emptyArray;
                    result_1.hasNoDefaultLib = false;
                    result_1.pragmas = ts.emptyMap;
                    return result_1;
                }
                initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
                var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
                clearState();
                return result;
            }
            Parser.parseSourceFile = parseSourceFile;
            function parseIsolatedEntityName(content, languageVersion) {
                // Choice of `isDeclarationFile` should be arbitrary
                initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
                // Prime the scanner.
                nextToken();
                var entityName = parseEntityName(/*allowReservedWords*/ true);
                var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
                clearState();
                return isInvalid ? entityName : undefined;
            }
            Parser.parseIsolatedEntityName = parseIsolatedEntityName;
            function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
                if (languageVersion === void 0) {
                    languageVersion = 2 /* ES2015 */;
                }
                initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
                // Set source file so that errors will be reported with this file name
                sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
                sourceFile.flags = contextFlags;
                // Prime the scanner.
                nextToken();
                var pos = getNodePos();
                if (token() === 1 /* EndOfFileToken */) {
                    sourceFile.statements = createNodeArray([], pos, pos);
                    sourceFile.endOfFileToken = parseTokenNode();
                }
                else {
                    var statement = createNode(219 /* ExpressionStatement */);
                    switch (token()) {
                        case 21 /* OpenBracketToken */:
                            statement.expression = parseArrayLiteralExpression();
                            break;
                        case 101 /* TrueKeyword */:
                        case 86 /* FalseKeyword */:
                        case 95 /* NullKeyword */:
                            statement.expression = parseTokenNode();
                            break;
                        case 38 /* MinusToken */:
                            if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) {
                                statement.expression = parsePrefixUnaryExpression();
                            }
                            else {
                                statement.expression = parseObjectLiteralExpression();
                            }
                            break;
                        case 8 /* NumericLiteral */:
                        case 9 /* StringLiteral */:
                            if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) {
                                statement.expression = parseLiteralNode();
                                break;
                            }
                        // falls through
                        default:
                            statement.expression = parseObjectLiteralExpression();
                            break;
                    }
                    finishNode(statement);
                    sourceFile.statements = createNodeArray([statement], pos);
                    sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
                }
                if (setParentNodes) {
                    fixupParentReferences(sourceFile);
                }
                sourceFile.parseDiagnostics = parseDiagnostics;
                var result = sourceFile;
                clearState();
                return result;
            }
            Parser.parseJsonText = parseJsonText;
            function getLanguageVariant(scriptKind) {
                // .tsx and .jsx files are treated as jsx language variant.
                return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
            }
            function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
                NodeConstructor = ts.objectAllocator.getNodeConstructor();
                TokenConstructor = ts.objectAllocator.getTokenConstructor();
                IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
                SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
                sourceText = _sourceText;
                syntaxCursor = _syntaxCursor;
                parseDiagnostics = [];
                parsingContext = 0;
                identifiers = ts.createMap();
                identifierCount = 0;
                nodeCount = 0;
                switch (scriptKind) {
                    case 1 /* JS */:
                    case 2 /* JSX */:
                        contextFlags = 65536 /* JavaScriptFile */;
                        break;
                    case 6 /* JSON */:
                        contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */;
                        break;
                    default:
                        contextFlags = 0 /* None */;
                        break;
                }
                parseErrorBeforeNextFinishedNode = false;
                // Initialize and prime the scanner before parsing the source elements.
                scanner.setText(sourceText);
                scanner.setOnError(scanError);
                scanner.setScriptTarget(languageVersion);
                scanner.setLanguageVariant(getLanguageVariant(scriptKind));
            }
            function clearState() {
                // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
                scanner.setText("");
                scanner.setOnError(undefined);
                // Clear any data.  We don't want to accidentally hold onto it for too long.
                parseDiagnostics = undefined;
                sourceFile = undefined;
                identifiers = undefined;
                syntaxCursor = undefined;
                sourceText = undefined;
            }
            function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
                var isDeclarationFile = isDeclarationFileName(fileName);
                if (isDeclarationFile) {
                    contextFlags |= 4194304 /* Ambient */;
                }
                sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
                sourceFile.flags = contextFlags;
                // Prime the scanner.
                nextToken();
                // A member of ReadonlyArray<T> isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future
                processCommentPragmas(sourceFile, sourceText);
                processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
                sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
                ts.Debug.assert(token() === 1 /* EndOfFileToken */);
                sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
                setExternalModuleIndicator(sourceFile);
                sourceFile.nodeCount = nodeCount;
                sourceFile.identifierCount = identifierCount;
                sourceFile.identifiers = identifiers;
                sourceFile.parseDiagnostics = parseDiagnostics;
                if (setParentNodes) {
                    fixupParentReferences(sourceFile);
                }
                return sourceFile;
                function reportPragmaDiagnostic(pos, end, diagnostic) {
                    parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
                }
            }
            function addJSDocComment(node) {
                ts.Debug.assert(!node.jsDoc); // Should only be called once per node
                var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
                if (jsDoc.length)
                    node.jsDoc = jsDoc;
                return node;
            }
            function fixupParentReferences(rootNode) {
                // normally parent references are set during binding. However, for clients that only need
                // a syntax tree, and no semantic features, then the binding process is an unnecessary
                // overhead.  This functions allows us to set all the parents, without all the expense of
                // binding.
                var parent = rootNode;
                forEachChild(rootNode, visitNode);
                return;
                function visitNode(n) {
                    // walk down setting parents that differ from the parent we think it should be.  This
                    // allows us to quickly bail out of setting parents for subtrees during incremental
                    // parsing
                    if (n.parent !== parent) {
                        n.parent = parent;
                        var saveParent = parent;
                        parent = n;
                        forEachChild(n, visitNode);
                        if (ts.hasJSDocNodes(n)) {
                            for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) {
                                var jsDoc = _a[_i];
                                jsDoc.parent = n;
                                parent = jsDoc;
                                forEachChild(jsDoc, visitNode);
                            }
                        }
                        parent = saveParent;
                    }
                }
            }
            Parser.fixupParentReferences = fixupParentReferences;
            function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
                // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
                // this is quite rare comparing to other nodes and createNode should be as fast as possible
                var sourceFile = new SourceFileConstructor(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
                nodeCount++;
                sourceFile.text = sourceText;
                sourceFile.bindDiagnostics = [];
                sourceFile.bindSuggestionDiagnostics = undefined;
                sourceFile.languageVersion = languageVersion;
                sourceFile.fileName = ts.normalizePath(fileName);
                sourceFile.languageVariant = getLanguageVariant(scriptKind);
                sourceFile.isDeclarationFile = isDeclarationFile;
                sourceFile.scriptKind = scriptKind;
                return sourceFile;
            }
            function setContextFlag(val, flag) {
                if (val) {
                    contextFlags |= flag;
                }
                else {
                    contextFlags &= ~flag;
                }
            }
            function setDisallowInContext(val) {
                setContextFlag(val, 2048 /* DisallowInContext */);
            }
            function setYieldContext(val) {
                setContextFlag(val, 4096 /* YieldContext */);
            }
            function setDecoratorContext(val) {
                setContextFlag(val, 8192 /* DecoratorContext */);
            }
            function setAwaitContext(val) {
                setContextFlag(val, 16384 /* AwaitContext */);
            }
            function doOutsideOfContext(context, func) {
                // contextFlagsToClear will contain only the context flags that are
                // currently set that we need to temporarily clear
                // We don't just blindly reset to the previous flags to ensure
                // that we do not mutate cached flags for the incremental
                // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
                // HasAggregatedChildData).
                var contextFlagsToClear = context & contextFlags;
                if (contextFlagsToClear) {
                    // clear the requested context flags
                    setContextFlag(/*val*/ false, contextFlagsToClear);
                    var result = func();
                    // restore the context flags we just cleared
                    setContextFlag(/*val*/ true, contextFlagsToClear);
                    return result;
                }
                // no need to do anything special as we are not in any of the requested contexts
                return func();
            }
            function doInsideOfContext(context, func) {
                // contextFlagsToSet will contain only the context flags that
                // are not currently set that we need to temporarily enable.
                // We don't just blindly reset to the previous flags to ensure
                // that we do not mutate cached flags for the incremental
                // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
                // HasAggregatedChildData).
                var contextFlagsToSet = context & ~contextFlags;
                if (contextFlagsToSet) {
                    // set the requested context flags
                    setContextFlag(/*val*/ true, contextFlagsToSet);
                    var result = func();
                    // reset the context flags we just set
                    setContextFlag(/*val*/ false, contextFlagsToSet);
                    return result;
                }
                // no need to do anything special as we are already in all of the requested contexts
                return func();
            }
            function allowInAnd(func) {
                return doOutsideOfContext(2048 /* DisallowInContext */, func);
            }
            function disallowInAnd(func) {
                return doInsideOfContext(2048 /* DisallowInContext */, func);
            }
            function doInYieldContext(func) {
                return doInsideOfContext(4096 /* YieldContext */, func);
            }
            function doInDecoratorContext(func) {
                return doInsideOfContext(8192 /* DecoratorContext */, func);
            }
            function doInAwaitContext(func) {
                return doInsideOfContext(16384 /* AwaitContext */, func);
            }
            function doOutsideOfAwaitContext(func) {
                return doOutsideOfContext(16384 /* AwaitContext */, func);
            }
            function doInYieldAndAwaitContext(func) {
                return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func);
            }
            function inContext(flags) {
                return (contextFlags & flags) !== 0;
            }
            function inYieldContext() {
                return inContext(4096 /* YieldContext */);
            }
            function inDisallowInContext() {
                return inContext(2048 /* DisallowInContext */);
            }
            function inDecoratorContext() {
                return inContext(8192 /* DecoratorContext */);
            }
            function inAwaitContext() {
                return inContext(16384 /* AwaitContext */);
            }
            function parseErrorAtCurrentToken(message, arg0) {
                parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
            }
            function parseErrorAtPosition(start, length, message, arg0) {
                // Don't report another error if it would just be at the same position as the last error.
                var lastError = ts.lastOrUndefined(parseDiagnostics);
                if (!lastError || start !== lastError.start) {
                    parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
                }
                // Mark that we've encountered an error.  We'll set an appropriate bit on the next
                // node we finish so that it can't be reused incrementally.
                parseErrorBeforeNextFinishedNode = true;
            }
            function parseErrorAt(start, end, message, arg0) {
                parseErrorAtPosition(start, end - start, message, arg0);
            }
            function parseErrorAtRange(range, message, arg0) {
                parseErrorAt(range.pos, range.end, message, arg0);
            }
            function scanError(message, length) {
                parseErrorAtPosition(scanner.getTextPos(), length, message);
            }
            function getNodePos() {
                return scanner.getStartPos();
            }
            // Use this function to access the current token instead of reading the currentToken
            // variable. Since function results aren't narrowed in control flow analysis, this ensures
            // that the type checker doesn't make wrong assumptions about the type of the current
            // token (e.g. a call to nextToken() changes the current token but the checker doesn't
            // reason about this side effect).  Mainstream VMs inline simple functions like this, so
            // there is no performance penalty.
            function token() {
                return currentToken;
            }
            function nextToken() {
                return currentToken = scanner.scan();
            }
            function reScanGreaterToken() {
                return currentToken = scanner.reScanGreaterToken();
            }
            function reScanSlashToken() {
                return currentToken = scanner.reScanSlashToken();
            }
            function reScanTemplateToken() {
                return currentToken = scanner.reScanTemplateToken();
            }
            function scanJsxIdentifier() {
                return currentToken = scanner.scanJsxIdentifier();
            }
            function scanJsxText() {
                return currentToken = scanner.scanJsxToken();
            }
            function scanJsxAttributeValue() {
                return currentToken = scanner.scanJsxAttributeValue();
            }
            function speculationHelper(callback, isLookAhead) {
                // Keep track of the state we'll need to rollback to if lookahead fails (or if the
                // caller asked us to always reset our state).
                var saveToken = currentToken;
                var saveParseDiagnosticsLength = parseDiagnostics.length;
                var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
                // Note: it is not actually necessary to save/restore the context flags here.  That's
                // because the saving/restoring of these flags happens naturally through the recursive
                // descent nature of our parser.  However, we still store this here just so we can
                // assert that invariant holds.
                var saveContextFlags = contextFlags;
                // If we're only looking ahead, then tell the scanner to only lookahead as well.
                // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
                // same.
                var result = isLookAhead
                    ? scanner.lookAhead(callback)
                    : scanner.tryScan(callback);
                ts.Debug.assert(saveContextFlags === contextFlags);
                // If our callback returned something 'falsy' or we're just looking ahead,
                // then unconditionally restore us to where we were.
                if (!result || isLookAhead) {
                    currentToken = saveToken;
                    parseDiagnostics.length = saveParseDiagnosticsLength;
                    parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
                }
                return result;
            }
            /** Invokes the provided callback then unconditionally restores the parser to the state it
             * was in immediately prior to invoking the callback.  The result of invoking the callback
             * is returned from this function.
             */
            function lookAhead(callback) {
                return speculationHelper(callback, /*isLookAhead*/ true);
            }
            /** Invokes the provided callback.  If the callback returns something falsy, then it restores
             * the parser to the state it was in immediately prior to invoking the callback.  If the
             * callback returns something truthy, then the parser state is not rolled back.  The result
             * of invoking the callback is returned from this function.
             */
            function tryParse(callback) {
                return speculationHelper(callback, /*isLookAhead*/ false);
            }
            // Ignore strict mode flag because we will report an error in type checker instead.
            function isIdentifier() {
                if (token() === 71 /* Identifier */) {
                    return true;
                }
                // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
                // considered a keyword and is not an identifier.
                if (token() === 116 /* YieldKeyword */ && inYieldContext()) {
                    return false;
                }
                // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
                // considered a keyword and is not an identifier.
                if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) {
                    return false;
                }
                return token() > 107 /* LastReservedWord */;
            }
            function parseExpected(kind, diagnosticMessage, shouldAdvance) {
                if (shouldAdvance === void 0) {
                    shouldAdvance = true;
                }
                if (token() === kind) {
                    if (shouldAdvance) {
                        nextToken();
                    }
                    return true;
                }
                // Report specific message if provided with one.  Otherwise, report generic fallback message.
                if (diagnosticMessage) {
                    parseErrorAtCurrentToken(diagnosticMessage);
                }
                else {
                    parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
                }
                return false;
            }
            function parseOptional(t) {
                if (token() === t) {
                    nextToken();
                    return true;
                }
                return false;
            }
            function parseOptionalToken(t) {
                if (token() === t) {
                    return parseTokenNode();
                }
                return undefined;
            }
            function parseExpectedToken(t, diagnosticMessage, arg0) {
                return parseOptionalToken(t) ||
                    createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
            }
            function parseTokenNode() {
                var node = createNode(token());
                nextToken();
                return finishNode(node);
            }
            function canParseSemicolon() {
                // If there's a real semicolon, then we can always parse it out.
                if (token() === 25 /* SemicolonToken */) {
                    return true;
                }
                // We can parse out an optional semicolon in ASI cases in the following cases.
                return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
            }
            function parseSemicolon() {
                if (canParseSemicolon()) {
                    if (token() === 25 /* SemicolonToken */) {
                        // consume the semicolon if it was explicitly provided.
                        nextToken();
                    }
                    return true;
                }
                else {
                    return parseExpected(25 /* SemicolonToken */);
                }
            }
            function createNode(kind, pos) {
                nodeCount++;
                var p = pos >= 0 ? pos : scanner.getStartPos();
                return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
                    kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
                        new TokenConstructor(kind, p, p);
            }
            function createNodeWithJSDoc(kind, pos) {
                var node = createNode(kind, pos);
                if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) {
                    addJSDocComment(node);
                }
                return node;
            }
            function createNodeArray(elements, pos, end) {
                // Since the element list of a node array is typically created by starting with an empty array and
                // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
                // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
                var length = elements.length;
                var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
                array.pos = pos;
                array.end = end === undefined ? scanner.getStartPos() : end;
                return array;
            }
            function finishNode(node, end) {
                node.end = end === undefined ? scanner.getStartPos() : end;
                if (contextFlags) {
                    node.flags |= contextFlags;
                }
                // Keep track on the node if we encountered an error while parsing it.  If we did, then
                // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
                // flag so that we don't mark any subsequent nodes.
                if (parseErrorBeforeNextFinishedNode) {
                    parseErrorBeforeNextFinishedNode = false;
                    node.flags |= 32768 /* ThisNodeHasError */;
                }
                return node;
            }
            function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
                if (reportAtCurrentPosition) {
                    parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
                }
                else if (diagnosticMessage) {
                    parseErrorAtCurrentToken(diagnosticMessage, arg0);
                }
                var result = createNode(kind);
                if (kind === 71 /* Identifier */) {
                    result.escapedText = "";
                }
                else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
                    result.text = "";
                }
                return finishNode(result);
            }
            function internIdentifier(text) {
                var identifier = identifiers.get(text);
                if (identifier === undefined) {
                    identifiers.set(text, identifier = text);
                }
                return identifier;
            }
            // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
            // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
            // each identifier in order to reduce memory consumption.
            function createIdentifier(isIdentifier, diagnosticMessage) {
                identifierCount++;
                if (isIdentifier) {
                    var node = createNode(71 /* Identifier */);
                    // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
                    if (token() !== 71 /* Identifier */) {
                        node.originalKeywordKind = token();
                    }
                    node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
                    nextToken();
                    return finishNode(node);
                }
                // Only for end of file because the error gets reported incorrectly on embedded script tags.
                var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
                return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected);
            }
            function parseIdentifier(diagnosticMessage) {
                return createIdentifier(isIdentifier(), diagnosticMessage);
            }
            function parseIdentifierName(diagnosticMessage) {
                return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
            }
            function isLiteralPropertyName() {
                return ts.tokenIsIdentifierOrKeyword(token()) ||
                    token() === 9 /* StringLiteral */ ||
                    token() === 8 /* NumericLiteral */;
            }
            function parsePropertyNameWorker(allowComputedPropertyNames) {
                if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
                    var node = parseLiteralNode();
                    node.text = internIdentifier(node.text);
                    return node;
                }
                if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) {
                    return parseComputedPropertyName();
                }
                return parseIdentifierName();
            }
            function parsePropertyName() {
                return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
            }
            function parseComputedPropertyName() {
                // PropertyName [Yield]:
                //      LiteralPropertyName
                //      ComputedPropertyName[?Yield]
                var node = createNode(147 /* ComputedPropertyName */);
                parseExpected(21 /* OpenBracketToken */);
                // We parse any expression (including a comma expression). But the grammar
                // says that only an assignment expression is allowed, so the grammar checker
                // will error if it sees a comma expression.
                node.expression = allowInAnd(parseExpression);
                parseExpected(22 /* CloseBracketToken */);
                return finishNode(node);
            }
            function parseContextualModifier(t) {
                return token() === t && tryParse(nextTokenCanFollowModifier);
            }
            function nextTokenIsOnSameLineAndCanFollowModifier() {
                nextToken();
                if (scanner.hasPrecedingLineBreak()) {
                    return false;
                }
                return canFollowModifier();
            }
            function nextTokenCanFollowModifier() {
                switch (token()) {
                    case 76 /* ConstKeyword */:
                        // 'const' is only a modifier if followed by 'enum'.
                        return nextToken() === 83 /* EnumKeyword */;
                    case 84 /* ExportKeyword */:
                        nextToken();
                        if (token() === 79 /* DefaultKeyword */) {
                            return lookAhead(nextTokenCanFollowDefaultKeyword);
                        }
                        return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier();
                    case 79 /* DefaultKeyword */:
                        return nextTokenCanFollowDefaultKeyword();
                    case 115 /* StaticKeyword */:
                    case 125 /* GetKeyword */:
                    case 136 /* SetKeyword */:
                        nextToken();
                        return canFollowModifier();
                    default:
                        return nextTokenIsOnSameLineAndCanFollowModifier();
                }
            }
            function parseAnyContextualModifier() {
                return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
            }
            function canFollowModifier() {
                return token() === 21 /* OpenBracketToken */
                    || token() === 17 /* OpenBraceToken */
                    || token() === 39 /* AsteriskToken */
                    || token() === 24 /* DotDotDotToken */
                    || isLiteralPropertyName();
            }
            function nextTokenCanFollowDefaultKeyword() {
                nextToken();
                return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ ||
                    token() === 109 /* InterfaceKeyword */ ||
                    (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
                    (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
            }
            // True if positioned at the start of a list element
            function isListElement(parsingContext, inErrorRecovery) {
                var node = currentNode(parsingContext);
                if (node) {
                    return true;
                }
                switch (parsingContext) {
                    case 0 /* SourceElements */:
                    case 1 /* BlockStatements */:
                    case 3 /* SwitchClauseStatements */:
                        // If we're in error recovery, then we don't want to treat ';' as an empty statement.
                        // The problem is that ';' can show up in far too many contexts, and if we see one
                        // and assume it's a statement, then we may bail out inappropriately from whatever
                        // we're parsing.  For example, if we have a semicolon in the middle of a class, then
                        // we really don't want to assume the class is over and we're on a statement in the
                        // outer module.  We just want to consume and move on.
                        return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
                    case 2 /* SwitchClauses */:
                        return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */;
                    case 4 /* TypeMembers */:
                        return lookAhead(isTypeMemberStart);
                    case 5 /* ClassMembers */:
                        // We allow semicolons as class elements (as specified by ES6) as long as we're
                        // not in error recovery.  If we're in error recovery, we don't want an errant
                        // semicolon to be treated as a class member (since they're almost always used
                        // for statements.
                        return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery);
                    case 6 /* EnumMembers */:
                        // Include open bracket computed properties. This technically also lets in indexers,
                        // which would be a candidate for improved error reporting.
                        return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName();
                    case 12 /* ObjectLiteralMembers */:
                        return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName();
                    case 18 /* RestProperties */:
                        return isLiteralPropertyName();
                    case 9 /* ObjectBindingElements */:
                        return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName();
                    case 7 /* HeritageClauseElement */:
                        // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
                        // That way we won't consume the body of a class in its heritage clause.
                        if (token() === 17 /* OpenBraceToken */) {
                            return lookAhead(isValidHeritageClauseObjectLiteral);
                        }
                        if (!inErrorRecovery) {
                            return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
                        }
                        else {
                            // If we're in error recovery we tighten up what we're willing to match.
                            // That way we don't treat something like "this" as a valid heritage clause
                            // element during recovery.
                            return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
                        }
                    case 8 /* VariableDeclarations */:
                        return isIdentifierOrPattern();
                    case 10 /* ArrayBindingElements */:
                        return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern();
                    case 19 /* TypeParameters */:
                        return isIdentifier();
                    case 15 /* ArrayLiteralMembers */:
                        if (token() === 26 /* CommaToken */) {
                            return true;
                        }
                    // falls through
                    case 11 /* ArgumentExpressions */:
                        return token() === 24 /* DotDotDotToken */ || isStartOfExpression();
                    case 16 /* Parameters */:
                        return isStartOfParameter(/*isJSDocParameter*/ false);
                    case 17 /* JSDocParameters */:
                        return isStartOfParameter(/*isJSDocParameter*/ true);
                    case 20 /* TypeArguments */:
                    case 21 /* TupleElementTypes */:
                        return token() === 26 /* CommaToken */ || isStartOfType();
                    case 22 /* HeritageClauses */:
                        return isHeritageClause();
                    case 23 /* ImportOrExportSpecifiers */:
                        return ts.tokenIsIdentifierOrKeyword(token());
                    case 13 /* JsxAttributes */:
                        return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */;
                    case 14 /* JsxChildren */:
                        return true;
                }
                return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
            }
            function isValidHeritageClauseObjectLiteral() {
                ts.Debug.assert(token() === 17 /* OpenBraceToken */);
                if (nextToken() === 18 /* CloseBraceToken */) {
                    // if we see "extends {}" then only treat the {} as what we're extending (and not
                    // the class body) if we have:
                    //
                    //      extends {} {
                    //      extends {},
                    //      extends {} extends
                    //      extends {} implements
                    var next = nextToken();
                    return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */;
                }
                return true;
            }
            function nextTokenIsIdentifier() {
                nextToken();
                return isIdentifier();
            }
            function nextTokenIsIdentifierOrKeyword() {
                nextToken();
                return ts.tokenIsIdentifierOrKeyword(token());
            }
            function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
                nextToken();
                return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
            }
            function isHeritageClauseExtendsOrImplementsKeyword() {
                if (token() === 108 /* ImplementsKeyword */ ||
                    token() === 85 /* ExtendsKeyword */) {
                    return lookAhead(nextTokenIsStartOfExpression);
                }
                return false;
            }
            function nextTokenIsStartOfExpression() {
                nextToken();
                return isStartOfExpression();
            }
            function nextTokenIsStartOfType() {
                nextToken();
                return isStartOfType();
            }
            // True if positioned at a list terminator
            function isListTerminator(kind) {
                if (token() === 1 /* EndOfFileToken */) {
                    // Being at the end of the file ends all lists.
                    return true;
                }
                switch (kind) {
                    case 1 /* BlockStatements */:
                    case 2 /* SwitchClauses */:
                    case 4 /* TypeMembers */:
                    case 5 /* ClassMembers */:
                    case 6 /* EnumMembers */:
                    case 12 /* ObjectLiteralMembers */:
                    case 9 /* ObjectBindingElements */:
                    case 23 /* ImportOrExportSpecifiers */:
                        return token() === 18 /* CloseBraceToken */;
                    case 3 /* SwitchClauseStatements */:
                        return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */;
                    case 7 /* HeritageClauseElement */:
                        return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */;
                    case 8 /* VariableDeclarations */:
                        return isVariableDeclaratorListTerminator();
                    case 19 /* TypeParameters */:
                        // Tokens other than '>' are here for better error recovery
                        return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */;
                    case 11 /* ArgumentExpressions */:
                        // Tokens other than ')' are here for better error recovery
                        return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */;
                    case 15 /* ArrayLiteralMembers */:
                    case 21 /* TupleElementTypes */:
                    case 10 /* ArrayBindingElements */:
                        return token() === 22 /* CloseBracketToken */;
                    case 17 /* JSDocParameters */:
                    case 16 /* Parameters */:
                    case 18 /* RestProperties */:
                        // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
                        return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
                    case 20 /* TypeArguments */:
                        // All other tokens should cause the type-argument to terminate except comma token
                        return token() !== 26 /* CommaToken */;
                    case 22 /* HeritageClauses */:
                        return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */;
                    case 13 /* JsxAttributes */:
                        return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */;
                    case 14 /* JsxChildren */:
                        return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
                    default:
                        return false;
                }
            }
            function isVariableDeclaratorListTerminator() {
                // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
                // with parsing the list of variable declarators.
                if (canParseSemicolon()) {
                    return true;
                }
                // in the case where we're parsing the variable declarator of a 'for-in' statement, we
                // are done if we see an 'in' keyword in front of us. Same with for-of
                if (isInOrOfKeyword(token())) {
                    return true;
                }
                // ERROR RECOVERY TWEAK:
                // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
                // arrow function here and it's going to be very unlikely that we'll resynchronize and get
                // another variable declaration.
                if (token() === 36 /* EqualsGreaterThanToken */) {
                    return true;
                }
                // Keep trying to parse out variable declarators.
                return false;
            }
            // True if positioned at element or terminator of the current list or any enclosing list
            function isInSomeParsingContext() {
                for (var kind = 0; kind < 24 /* Count */; kind++) {
                    if (parsingContext & (1 << kind)) {
                        if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
                            return true;
                        }
                    }
                }
                return false;
            }
            // Parses a list of elements
            function parseList(kind, parseElement) {
                var saveParsingContext = parsingContext;
                parsingContext |= 1 << kind;
                var list = [];
                var listPos = getNodePos();
                while (!isListTerminator(kind)) {
                    if (isListElement(kind, /*inErrorRecovery*/ false)) {
                        var element = parseListElement(kind, parseElement);
                        list.push(element);
                        continue;
                    }
                    if (abortParsingListOrMoveToNextToken(kind)) {
                        break;
                    }
                }
                parsingContext = saveParsingContext;
                return createNodeArray(list, listPos);
            }
            function parseListElement(parsingContext, parseElement) {
                var node = currentNode(parsingContext);
                if (node) {
                    return consumeNode(node);
                }
                return parseElement();
            }
            function currentNode(parsingContext) {
                // If there is an outstanding parse error that we've encountered, but not attached to
                // some node, then we cannot get a node from the old source tree.  This is because we
                // want to mark the next node we encounter as being unusable.
                //
                // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
                // on it (or its leftmost child) as having the error.  For now though, being conservative
                // is nice and likely won't ever affect perf.
                if (parseErrorBeforeNextFinishedNode) {
                    return undefined;
                }
                if (!syntaxCursor) {
                    // if we don't have a cursor, we could never return a node from the old tree.
                    return undefined;
                }
                var node = syntaxCursor.currentNode(scanner.getStartPos());
                // Can't reuse a missing node.
                if (ts.nodeIsMissing(node)) {
                    return undefined;
                }
                // Can't reuse a node that intersected the change range.
                if (node.intersectsChange) {
                    return undefined;
                }
                // Can't reuse a node that contains a parse error.  This is necessary so that we
                // produce the same set of errors again.
                if (ts.containsParseError(node)) {
                    return undefined;
                }
                // We can only reuse a node if it was parsed under the same strict mode that we're
                // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
                // the user added 'using strict' at the top of the file, then we can't use that node
                // again as the presence of strict mode may cause us to parse the tokens in the file
                // differently.
                //
                // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
                // are unaffected by strict mode.  It's just the parser will decide what to do with it
                // differently depending on what mode it is in.
                //
                // This also applies to all our other context flags as well.
                var nodeContextFlags = node.flags & 12679168 /* ContextFlags */;
                if (nodeContextFlags !== contextFlags) {
                    return undefined;
                }
                // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
                // in the current list parsing context that we're currently at.
                if (!canReuseNode(node, parsingContext)) {
                    return undefined;
                }
                if (node.jsDocCache) {
                    // jsDocCache may include tags from parent nodes, which might have been modified.
                    node.jsDocCache = undefined;
                }
                return node;
            }
            function consumeNode(node) {
                // Move the scanner so it is after the node we just consumed.
                scanner.setTextPos(node.end);
                nextToken();
                return node;
            }
            function canReuseNode(node, parsingContext) {
                switch (parsingContext) {
                    case 5 /* ClassMembers */:
                        return isReusableClassMember(node);
                    case 2 /* SwitchClauses */:
                        return isReusableSwitchClause(node);
                    case 0 /* SourceElements */:
                    case 1 /* BlockStatements */:
                    case 3 /* SwitchClauseStatements */:
                        return isReusableStatement(node);
                    case 6 /* EnumMembers */:
                        return isReusableEnumMember(node);
                    case 4 /* TypeMembers */:
                        return isReusableTypeMember(node);
                    case 8 /* VariableDeclarations */:
                        return isReusableVariableDeclaration(node);
                    case 17 /* JSDocParameters */:
                    case 16 /* Parameters */:
                        return isReusableParameter(node);
                    case 18 /* RestProperties */:
                        return false;
                    // Any other lists we do not care about reusing nodes in.  But feel free to add if
                    // you can do so safely.  Danger areas involve nodes that may involve speculative
                    // parsing.  If speculative parsing is involved with the node, then the range the
                    // parser reached while looking ahead might be in the edited range (see the example
                    // in canReuseVariableDeclaratorNode for a good case of this).
                    case 22 /* HeritageClauses */:
                    // This would probably be safe to reuse.  There is no speculative parsing with
                    // heritage clauses.
                    case 19 /* TypeParameters */:
                    // This would probably be safe to reuse.  There is no speculative parsing with
                    // type parameters.  Note that that's because type *parameters* only occur in
                    // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
                    // *expression* contexts.
                    case 21 /* TupleElementTypes */:
                    // This would probably be safe to reuse.  There is no speculative parsing with
                    // tuple types.
                    // Technically, type argument list types are probably safe to reuse.  While
                    // speculative parsing is involved with them (since type argument lists are only
                    // produced from speculative parsing a < as a type argument list), we only have
                    // the types because speculative parsing succeeded.  Thus, the lookahead never
                    // went past the end of the list and rewound.
                    case 20 /* TypeArguments */:
                    // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
                    // need a large amount of lookahead, and we should not reuse them as they may
                    // have actually intersected the edit.
                    case 11 /* ArgumentExpressions */:
                    // This is not safe to reuse for the same reason as the 'AssignmentExpression'
                    // cases.  i.e. a property assignment may end with an expression, and thus might
                    // have lookahead far beyond it's old node.
                    case 12 /* ObjectLiteralMembers */:
                    // This is probably not safe to reuse.  There can be speculative parsing with
                    // type names in a heritage clause.  There can be generic names in the type
                    // name list, and there can be left hand side expressions (which can have type
                    // arguments.)
                    case 7 /* HeritageClauseElement */:
                    // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
                    // on any given element. Same for children.
                    case 13 /* JsxAttributes */:
                    case 14 /* JsxChildren */:
                }
                return false;
            }
            function isReusableClassMember(node) {
                if (node) {
                    switch (node.kind) {
                        case 155 /* Constructor */:
                        case 160 /* IndexSignature */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                        case 152 /* PropertyDeclaration */:
                        case 215 /* SemicolonClassElement */:
                            return true;
                        case 154 /* MethodDeclaration */:
                            // Method declarations are not necessarily reusable.  An object-literal
                            // may have a method calls "constructor(...)" and we must reparse that
                            // into an actual .ConstructorDeclaration.
                            var methodDeclaration = node;
                            var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ &&
                                methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */;
                            return !nameIsConstructor;
                    }
                }
                return false;
            }
            function isReusableSwitchClause(node) {
                if (node) {
                    switch (node.kind) {
                        case 269 /* CaseClause */:
                        case 270 /* DefaultClause */:
                            return true;
                    }
                }
                return false;
            }
            function isReusableStatement(node) {
                if (node) {
                    switch (node.kind) {
                        case 237 /* FunctionDeclaration */:
                        case 217 /* VariableStatement */:
                        case 216 /* Block */:
                        case 220 /* IfStatement */:
                        case 219 /* ExpressionStatement */:
                        case 232 /* ThrowStatement */:
                        case 228 /* ReturnStatement */:
                        case 230 /* SwitchStatement */:
                        case 227 /* BreakStatement */:
                        case 226 /* ContinueStatement */:
                        case 224 /* ForInStatement */:
                        case 225 /* ForOfStatement */:
                        case 223 /* ForStatement */:
                        case 222 /* WhileStatement */:
                        case 229 /* WithStatement */:
                        case 218 /* EmptyStatement */:
                        case 233 /* TryStatement */:
                        case 231 /* LabeledStatement */:
                        case 221 /* DoStatement */:
                        case 234 /* DebuggerStatement */:
                        case 247 /* ImportDeclaration */:
                        case 246 /* ImportEqualsDeclaration */:
                        case 253 /* ExportDeclaration */:
                        case 252 /* ExportAssignment */:
                        case 242 /* ModuleDeclaration */:
                        case 238 /* ClassDeclaration */:
                        case 239 /* InterfaceDeclaration */:
                        case 241 /* EnumDeclaration */:
                        case 240 /* TypeAliasDeclaration */:
                            return true;
                    }
                }
                return false;
            }
            function isReusableEnumMember(node) {
                return node.kind === 276 /* EnumMember */;
            }
            function isReusableTypeMember(node) {
                if (node) {
                    switch (node.kind) {
                        case 159 /* ConstructSignature */:
                        case 153 /* MethodSignature */:
                        case 160 /* IndexSignature */:
                        case 151 /* PropertySignature */:
                        case 158 /* CallSignature */:
                            return true;
                    }
                }
                return false;
            }
            function isReusableVariableDeclaration(node) {
                if (node.kind !== 235 /* VariableDeclaration */) {
                    return false;
                }
                // Very subtle incremental parsing bug.  Consider the following code:
                //
                //      let v = new List < A, B
                //
                // This is actually legal code.  It's a list of variable declarators "v = new List<A"
                // on one side and "B" on the other. If you then change that to:
                //
                //      let v = new List < A, B >()
                //
                // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
                // start reparsing at "B" and we completely fail to handle this properly.
                //
                // In order to prevent this, we do not allow a variable declarator to be reused if it
                // has an initializer.
                var variableDeclarator = node;
                return variableDeclarator.initializer === undefined;
            }
            function isReusableParameter(node) {
                if (node.kind !== 149 /* Parameter */) {
                    return false;
                }
                // See the comment in isReusableVariableDeclaration for why we do this.
                var parameter = node;
                return parameter.initializer === undefined;
            }
            // Returns true if we should abort parsing.
            function abortParsingListOrMoveToNextToken(kind) {
                parseErrorAtCurrentToken(parsingContextErrors(kind));
                if (isInSomeParsingContext()) {
                    return true;
                }
                nextToken();
                return false;
            }
            function parsingContextErrors(context) {
                switch (context) {
                    case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
                    case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
                    case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
                    case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
                    case 18 /* RestProperties */: // fallthrough
                    case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
                    case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
                    case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
                    case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
                    case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
                    case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
                    case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
                    case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
                    case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
                    case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
                    case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
                    case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
                    case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
                    case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
                    case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
                    case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
                    case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
                    case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
                    case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
                    default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
                }
            }
            // Parses a comma-delimited list of elements
            function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
                var saveParsingContext = parsingContext;
                parsingContext |= 1 << kind;
                var list = [];
                var listPos = getNodePos();
                var commaStart = -1; // Meaning the previous token was not a comma
                while (true) {
                    if (isListElement(kind, /*inErrorRecovery*/ false)) {
                        var startPos = scanner.getStartPos();
                        list.push(parseListElement(kind, parseElement));
                        commaStart = scanner.getTokenPos();
                        if (parseOptional(26 /* CommaToken */)) {
                            // No need to check for a zero length node since we know we parsed a comma
                            continue;
                        }
                        commaStart = -1; // Back to the state where the last token was not a comma
                        if (isListTerminator(kind)) {
                            break;
                        }
                        // We didn't get a comma, and the list wasn't terminated, explicitly parse
                        // out a comma so we give a good error message.
                        parseExpected(26 /* CommaToken */);
                        // If the token was a semicolon, and the caller allows that, then skip it and
                        // continue.  This ensures we get back on track and don't result in tons of
                        // parse errors.  For example, this can happen when people do things like use
                        // a semicolon to delimit object literal members.   Note: we'll have already
                        // reported an error when we called parseExpected above.
                        if (considerSemicolonAsDelimiter && token() === 25 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
                            nextToken();
                        }
                        if (startPos === scanner.getStartPos()) {
                            // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
                            // Consume a token to advance the parser in some way and avoid an infinite loop
                            // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
                            // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
                            nextToken();
                        }
                        continue;
                    }
                    if (isListTerminator(kind)) {
                        break;
                    }
                    if (abortParsingListOrMoveToNextToken(kind)) {
                        break;
                    }
                }
                parsingContext = saveParsingContext;
                var result = createNodeArray(list, listPos);
                // Recording the trailing comma is deliberately done after the previous
                // loop, and not just if we see a list terminator. This is because the list
                // may have ended incorrectly, but it is still important to know if there
                // was a trailing comma.
                // Check if the last token was a comma.
                if (commaStart >= 0) {
                    // Always preserve a trailing comma by marking it on the NodeArray
                    result.hasTrailingComma = true;
                }
                return result;
            }
            function createMissingList() {
                var list = createNodeArray([], getNodePos());
                list.isMissingList = true;
                return list;
            }
            function isMissingList(arr) {
                return !!arr.isMissingList;
            }
            function parseBracketedList(kind, parseElement, open, close) {
                if (parseExpected(open)) {
                    var result = parseDelimitedList(kind, parseElement);
                    parseExpected(close);
                    return result;
                }
                return createMissingList();
            }
            function parseEntityName(allowReservedWords, diagnosticMessage) {
                var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
                var dotPos = scanner.getStartPos();
                while (parseOptional(23 /* DotToken */)) {
                    if (token() === 27 /* LessThanToken */) {
                        // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
                        entity.jsdocDotPos = dotPos;
                        break;
                    }
                    dotPos = scanner.getStartPos();
                    entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords));
                }
                return entity;
            }
            function createQualifiedName(entity, name) {
                var node = createNode(146 /* QualifiedName */, entity.pos);
                node.left = entity;
                node.right = name;
                return finishNode(node);
            }
            function parseRightSideOfDot(allowIdentifierNames) {
                // Technically a keyword is valid here as all identifiers and keywords are identifier names.
                // However, often we'll encounter this in error situations when the identifier or keyword
                // is actually starting another valid construct.
                //
                // So, we check for the following specific case:
                //
                //      name.
                //      identifierOrKeyword identifierNameOrKeyword
                //
                // Note: the newlines are important here.  For example, if that above code
                // were rewritten into:
                //
                //      name.identifierOrKeyword
                //      identifierNameOrKeyword
                //
                // Then we would consider it valid.  That's because ASI would take effect and
                // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
                // In the first case though, ASI will not take effect because there is not a
                // line terminator after the identifier or keyword.
                if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
                    var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
                    if (matchesPattern) {
                        // Report that we need an identifier.  However, report it right after the dot,
                        // and not on the next token.  This is because the next token might actually
                        // be an identifier and the error would be quite confusing.
                        return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
                    }
                }
                return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
            }
            function parseTemplateExpression() {
                var template = createNode(204 /* TemplateExpression */);
                template.head = parseTemplateHead();
                ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind");
                var list = [];
                var listPos = getNodePos();
                do {
                    list.push(parseTemplateSpan());
                } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */);
                template.templateSpans = createNodeArray(list, listPos);
                return finishNode(template);
            }
            function parseTemplateSpan() {
                var span = createNode(214 /* TemplateSpan */);
                span.expression = allowInAnd(parseExpression);
                var literal;
                if (token() === 18 /* CloseBraceToken */) {
                    reScanTemplateToken();
                    literal = parseTemplateMiddleOrTemplateTail();
                }
                else {
                    literal = parseExpectedToken(16 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */));
                }
                span.literal = literal;
                return finishNode(span);
            }
            function parseLiteralNode() {
                return parseLiteralLikeNode(token());
            }
            function parseTemplateHead() {
                var fragment = parseLiteralLikeNode(token());
                ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind");
                return fragment;
            }
            function parseTemplateMiddleOrTemplateTail() {
                var fragment = parseLiteralLikeNode(token());
                ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind");
                return fragment;
            }
            function parseLiteralLikeNode(kind) {
                var node = createNode(kind);
                var text = scanner.getTokenValue();
                node.text = text;
                if (scanner.hasExtendedUnicodeEscape()) {
                    node.hasExtendedUnicodeEscape = true;
                }
                if (scanner.isUnterminated()) {
                    node.isUnterminated = true;
                }
                // Octal literals are not allowed in strict mode or ES5
                // Note that theoretically the following condition would hold true literals like 009,
                // which is not octal.But because of how the scanner separates the tokens, we would
                // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
                // We also do not need to check for negatives because any prefix operator would be part of a
                // parent unary expression.
                if (node.kind === 8 /* NumericLiteral */) {
                    node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
                }
                nextToken();
                finishNode(node);
                return node;
            }
            // TYPES
            function parseTypeReference() {
                var node = createNode(162 /* TypeReference */);
                node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
                if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) {
                    node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */);
                }
                return finishNode(node);
            }
            // If true, we should abort parsing an error function.
            function typeHasArrowFunctionBlockingParseError(node) {
                switch (node.kind) {
                    case 162 /* TypeReference */:
                        return ts.nodeIsMissing(node.typeName);
                    case 163 /* FunctionType */:
                    case 164 /* ConstructorType */: {
                        var _a = node, parameters = _a.parameters, type = _a.type;
                        return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
                    }
                    case 175 /* ParenthesizedType */:
                        return typeHasArrowFunctionBlockingParseError(node.type);
                    default:
                        return false;
                }
            }
            function parseThisTypePredicate(lhs) {
                nextToken();
                var node = createNode(161 /* TypePredicate */, lhs.pos);
                node.parameterName = lhs;
                node.type = parseType();
                return finishNode(node);
            }
            function parseThisTypeNode() {
                var node = createNode(176 /* ThisType */);
                nextToken();
                return finishNode(node);
            }
            function parseJSDocAllType(postFixEquals) {
                var result = createNode(282 /* JSDocAllType */);
                if (postFixEquals) {
                    return createPostfixType(286 /* JSDocOptionalType */, result);
                }
                else {
                    nextToken();
                }
                return finishNode(result);
            }
            function parseJSDocNonNullableType() {
                var result = createNode(285 /* JSDocNonNullableType */);
                nextToken();
                result.type = parseNonArrayType();
                return finishNode(result);
            }
            function parseJSDocUnknownOrNullableType() {
                var pos = scanner.getStartPos();
                // skip the ?
                nextToken();
                // Need to lookahead to decide if this is a nullable or unknown type.
                // Here are cases where we'll pick the unknown type:
                //
                //      Foo(?,
                //      { a: ? }
                //      Foo(?)
                //      Foo<?>
                //      Foo(?=
                //      (?|
                if (token() === 26 /* CommaToken */ ||
                    token() === 18 /* CloseBraceToken */ ||
                    token() === 20 /* CloseParenToken */ ||
                    token() === 29 /* GreaterThanToken */ ||
                    token() === 58 /* EqualsToken */ ||
                    token() === 49 /* BarToken */) {
                    var result = createNode(283 /* JSDocUnknownType */, pos);
                    return finishNode(result);
                }
                else {
                    var result = createNode(284 /* JSDocNullableType */, pos);
                    result.type = parseType();
                    return finishNode(result);
                }
            }
            function parseJSDocFunctionType() {
                if (lookAhead(nextTokenIsOpenParen)) {
                    var result = createNodeWithJSDoc(287 /* JSDocFunctionType */);
                    nextToken();
                    fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
                    return finishNode(result);
                }
                var node = createNode(162 /* TypeReference */);
                node.typeName = parseIdentifierName();
                return finishNode(node);
            }
            function parseJSDocParameter() {
                var parameter = createNode(149 /* Parameter */);
                if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) {
                    parameter.name = parseIdentifierName();
                    parseExpected(56 /* ColonToken */);
                }
                parameter.type = parseJSDocType();
                return finishNode(parameter);
            }
            function parseJSDocType() {
                scanner.setInJSDocType(true);
                var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */);
                var type = parseTypeOrTypePredicate();
                scanner.setInJSDocType(false);
                if (dotdotdot) {
                    var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos);
                    variadic.type = type;
                    type = finishNode(variadic);
                }
                if (token() === 58 /* EqualsToken */) {
                    return createPostfixType(286 /* JSDocOptionalType */, type);
                }
                return type;
            }
            function parseTypeQuery() {
                var node = createNode(165 /* TypeQuery */);
                parseExpected(103 /* TypeOfKeyword */);
                node.exprName = parseEntityName(/*allowReservedWords*/ true);
                return finishNode(node);
            }
            function parseTypeParameter() {
                var node = createNode(148 /* TypeParameter */);
                node.name = parseIdentifier();
                if (parseOptional(85 /* ExtendsKeyword */)) {
                    // It's not uncommon for people to write improper constraints to a generic.  If the
                    // user writes a constraint that is an expression and not an actual type, then parse
                    // it out as an expression (so we can recover well), but report that a type is needed
                    // instead.
                    if (isStartOfType() || !isStartOfExpression()) {
                        node.constraint = parseType();
                    }
                    else {
                        // It was not a type, and it looked like an expression.  Parse out an expression
                        // here so we recover well.  Note: it is important that we call parseUnaryExpression
                        // and not parseExpression here.  If the user has:
                        //
                        //      <T extends "">
                        //
                        // We do *not* want to consume the `>` as we're consuming the expression for "".
                        node.expression = parseUnaryExpressionOrHigher();
                    }
                }
                if (parseOptional(58 /* EqualsToken */)) {
                    node.default = parseType();
                }
                return finishNode(node);
            }
            function parseTypeParameters() {
                if (token() === 27 /* LessThanToken */) {
                    return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */);
                }
            }
            function parseParameterType() {
                if (parseOptional(56 /* ColonToken */)) {
                    return parseType();
                }
                return undefined;
            }
            function isStartOfParameter(isJSDocParameter) {
                return token() === 24 /* DotDotDotToken */ ||
                    isIdentifierOrPattern() ||
                    ts.isModifierKind(token()) ||
                    token() === 57 /* AtToken */ ||
                    isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
            }
            function parseParameter() {
                var node = createNodeWithJSDoc(149 /* Parameter */);
                if (token() === 99 /* ThisKeyword */) {
                    node.name = createIdentifier(/*isIdentifier*/ true);
                    node.type = parseParameterType();
                    return finishNode(node);
                }
                node.decorators = parseDecorators();
                node.modifiers = parseModifiers();
                node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
                // FormalParameter [Yield,Await]:
                //      BindingElement[?Yield,?Await]
                node.name = parseIdentifierOrPattern();
                if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) {
                    // in cases like
                    // 'use strict'
                    // function foo(static)
                    // isParameter('static') === true, because of isModifier('static')
                    // however 'static' is not a legal identifier in a strict mode.
                    // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
                    // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
                    // to avoid this we'll advance cursor to the next token.
                    nextToken();
                }
                node.questionToken = parseOptionalToken(55 /* QuestionToken */);
                node.type = parseParameterType();
                node.initializer = parseInitializer();
                return finishNode(node);
            }
            /**
             * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
             * @returns If return type parsing succeeds
             */
            function fillSignature(returnToken, flags, signature) {
                if (!(flags & 32 /* JSDoc */)) {
                    signature.typeParameters = parseTypeParameters();
                }
                var parametersParsedSuccessfully = parseParameterList(signature, flags);
                if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
                    signature.type = parseTypeOrTypePredicate();
                    if (typeHasArrowFunctionBlockingParseError(signature.type))
                        return false;
                }
                return parametersParsedSuccessfully;
            }
            function shouldParseReturnType(returnToken, isType) {
                if (returnToken === 36 /* EqualsGreaterThanToken */) {
                    parseExpected(returnToken);
                    return true;
                }
                else if (parseOptional(56 /* ColonToken */)) {
                    return true;
                }
                else if (isType && token() === 36 /* EqualsGreaterThanToken */) {
                    // This is easy to get backward, especially in type contexts, so parse the type anyway
                    parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */));
                    nextToken();
                    return true;
                }
                return false;
            }
            // Returns true on success.
            function parseParameterList(signature, flags) {
                // FormalParameters [Yield,Await]: (modified)
                //      [empty]
                //      FormalParameterList[?Yield,Await]
                //
                // FormalParameter[Yield,Await]: (modified)
                //      BindingElement[?Yield,Await]
                //
                // BindingElement [Yield,Await]: (modified)
                //      SingleNameBinding[?Yield,?Await]
                //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
                //
                // SingleNameBinding [Yield,Await]:
                //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
                if (!parseExpected(19 /* OpenParenToken */)) {
                    signature.parameters = createMissingList();
                    return false;
                }
                var savedYieldContext = inYieldContext();
                var savedAwaitContext = inAwaitContext();
                setYieldContext(!!(flags & 1 /* Yield */));
                setAwaitContext(!!(flags & 2 /* Await */));
                signature.parameters = flags & 32 /* JSDoc */ ?
                    parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
                    parseDelimitedList(16 /* Parameters */, parseParameter);
                setYieldContext(savedYieldContext);
                setAwaitContext(savedAwaitContext);
                return parseExpected(20 /* CloseParenToken */);
            }
            function parseTypeMemberSemicolon() {
                // We allow type members to be separated by commas or (possibly ASI) semicolons.
                // First check if it was a comma.  If so, we're done with the member.
                if (parseOptional(26 /* CommaToken */)) {
                    return;
                }
                // Didn't have a comma.  We must have a (possible ASI) semicolon.
                parseSemicolon();
            }
            function parseSignatureMember(kind) {
                var node = createNodeWithJSDoc(kind);
                if (kind === 159 /* ConstructSignature */) {
                    parseExpected(94 /* NewKeyword */);
                }
                fillSignature(56 /* ColonToken */, 4 /* Type */, node);
                parseTypeMemberSemicolon();
                return finishNode(node);
            }
            function isIndexSignature() {
                return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
            }
            function isUnambiguouslyIndexSignature() {
                // The only allowed sequence is:
                //
                //   [id:
                //
                // However, for error recovery, we also check the following cases:
                //
                //   [...
                //   [id,
                //   [id?,
                //   [id?:
                //   [id?]
                //   [public id
                //   [private id
                //   [protected id
                //   []
                //
                nextToken();
                if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) {
                    return true;
                }
                if (ts.isModifierKind(token())) {
                    nextToken();
                    if (isIdentifier()) {
                        return true;
                    }
                }
                else if (!isIdentifier()) {
                    return false;
                }
                else {
                    // Skip the identifier
                    nextToken();
                }
                // A colon signifies a well formed indexer
                // A comma should be a badly formed indexer because comma expressions are not allowed
                // in computed properties.
                if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) {
                    return true;
                }
                // Question mark could be an indexer with an optional property,
                // or it could be a conditional expression in a computed property.
                if (token() !== 55 /* QuestionToken */) {
                    return false;
                }
                // If any of the following tokens are after the question mark, it cannot
                // be a conditional expression, so treat it as an indexer.
                nextToken();
                return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */;
            }
            function parseIndexSignatureDeclaration(node) {
                node.kind = 160 /* IndexSignature */;
                node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */);
                node.type = parseTypeAnnotation();
                parseTypeMemberSemicolon();
                return finishNode(node);
            }
            function parsePropertyOrMethodSignature(node) {
                node.name = parsePropertyName();
                node.questionToken = parseOptionalToken(55 /* QuestionToken */);
                if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
                    node.kind = 153 /* MethodSignature */;
                    // Method signatures don't exist in expression contexts.  So they have neither
                    // [Yield] nor [Await]
                    fillSignature(56 /* ColonToken */, 4 /* Type */, node);
                }
                else {
                    node.kind = 151 /* PropertySignature */;
                    node.type = parseTypeAnnotation();
                    if (token() === 58 /* EqualsToken */) {
                        // Although type literal properties cannot not have initializers, we attempt
                        // to parse an initializer so we can report in the checker that an interface
                        // property or type literal property cannot have an initializer.
                        node.initializer = parseInitializer();
                    }
                }
                parseTypeMemberSemicolon();
                return finishNode(node);
            }
            function isTypeMemberStart() {
                // Return true if we have the start of a signature member
                if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
                    return true;
                }
                var idToken = false;
                // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
                while (ts.isModifierKind(token())) {
                    idToken = true;
                    nextToken();
                }
                // Index signatures and computed property names are type members
                if (token() === 21 /* OpenBracketToken */) {
                    return true;
                }
                // Try to get the first property-like token following all modifiers
                if (isLiteralPropertyName()) {
                    idToken = true;
                    nextToken();
                }
                // If we were able to get any potential identifier, check that it is
                // the start of a member declaration
                if (idToken) {
                    return token() === 19 /* OpenParenToken */ ||
                        token() === 27 /* LessThanToken */ ||
                        token() === 55 /* QuestionToken */ ||
                        token() === 56 /* ColonToken */ ||
                        token() === 26 /* CommaToken */ ||
                        canParseSemicolon();
                }
                return false;
            }
            function parseTypeMember() {
                if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
                    return parseSignatureMember(158 /* CallSignature */);
                }
                if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
                    return parseSignatureMember(159 /* ConstructSignature */);
                }
                var node = createNodeWithJSDoc(0 /* Unknown */);
                node.modifiers = parseModifiers();
                if (isIndexSignature()) {
                    return parseIndexSignatureDeclaration(node);
                }
                return parsePropertyOrMethodSignature(node);
            }
            function nextTokenIsOpenParenOrLessThan() {
                nextToken();
                return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */;
            }
            function nextTokenIsDot() {
                return nextToken() === 23 /* DotToken */;
            }
            function nextTokenIsOpenParenOrLessThanOrDot() {
                switch (nextToken()) {
                    case 19 /* OpenParenToken */:
                    case 27 /* LessThanToken */:
                    case 23 /* DotToken */:
                        return true;
                }
                return false;
            }
            function parseTypeLiteral() {
                var node = createNode(166 /* TypeLiteral */);
                node.members = parseObjectTypeMembers();
                return finishNode(node);
            }
            function parseObjectTypeMembers() {
                var members;
                if (parseExpected(17 /* OpenBraceToken */)) {
                    members = parseList(4 /* TypeMembers */, parseTypeMember);
                    parseExpected(18 /* CloseBraceToken */);
                }
                else {
                    members = createMissingList();
                }
                return members;
            }
            function isStartOfMappedType() {
                nextToken();
                if (token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) {
                    return nextToken() === 132 /* ReadonlyKeyword */;
                }
                if (token() === 132 /* ReadonlyKeyword */) {
                    nextToken();
                }
                return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */;
            }
            function parseMappedTypeParameter() {
                var node = createNode(148 /* TypeParameter */);
                node.name = parseIdentifier();
                parseExpected(92 /* InKeyword */);
                node.constraint = parseType();
                return finishNode(node);
            }
            function parseMappedType() {
                var node = createNode(179 /* MappedType */);
                parseExpected(17 /* OpenBraceToken */);
                if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) {
                    node.readonlyToken = parseTokenNode();
                    if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) {
                        parseExpectedToken(132 /* ReadonlyKeyword */);
                    }
                }
                parseExpected(21 /* OpenBracketToken */);
                node.typeParameter = parseMappedTypeParameter();
                parseExpected(22 /* CloseBracketToken */);
                if (token() === 55 /* QuestionToken */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) {
                    node.questionToken = parseTokenNode();
                    if (node.questionToken.kind !== 55 /* QuestionToken */) {
                        parseExpectedToken(55 /* QuestionToken */);
                    }
                }
                node.type = parseTypeAnnotation();
                parseSemicolon();
                parseExpected(18 /* CloseBraceToken */);
                return finishNode(node);
            }
            function parseTupleElementType() {
                var pos = getNodePos();
                if (parseOptional(24 /* DotDotDotToken */)) {
                    var node = createNode(170 /* RestType */, pos);
                    node.type = parseType();
                    return finishNode(node);
                }
                var type = parseType();
                if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) {
                    type.kind = 169 /* OptionalType */;
                }
                return type;
            }
            function parseTupleType() {
                var node = createNode(168 /* TupleType */);
                node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */);
                return finishNode(node);
            }
            function parseParenthesizedType() {
                var node = createNode(175 /* ParenthesizedType */);
                parseExpected(19 /* OpenParenToken */);
                node.type = parseType();
                parseExpected(20 /* CloseParenToken */);
                return finishNode(node);
            }
            function parseFunctionOrConstructorType() {
                var pos = getNodePos();
                var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */;
                var node = createNodeWithJSDoc(kind, pos);
                fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node);
                return finishNode(node);
            }
            function parseKeywordAndNoDot() {
                var node = parseTokenNode();
                return token() === 23 /* DotToken */ ? undefined : node;
            }
            function parseLiteralTypeNode(negative) {
                var node = createNode(180 /* LiteralType */);
                var unaryMinusExpression;
                if (negative) {
                    unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */);
                    unaryMinusExpression.operator = 38 /* MinusToken */;
                    nextToken();
                }
                var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */
                    ? parseTokenNode()
                    : parseLiteralLikeNode(token());
                if (negative) {
                    unaryMinusExpression.operand = expression;
                    finishNode(unaryMinusExpression);
                    expression = unaryMinusExpression;
                }
                node.literal = expression;
                return finishNode(node);
            }
            function isStartOfTypeOfImportType() {
                nextToken();
                return token() === 91 /* ImportKeyword */;
            }
            function parseImportType() {
                sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */;
                var node = createNode(181 /* ImportType */);
                if (parseOptional(103 /* TypeOfKeyword */)) {
                    node.isTypeOf = true;
                }
                parseExpected(91 /* ImportKeyword */);
                parseExpected(19 /* OpenParenToken */);
                node.argument = parseType();
                parseExpected(20 /* CloseParenToken */);
                if (parseOptional(23 /* DotToken */)) {
                    node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
                }
                node.typeArguments = tryParseTypeArguments();
                return finishNode(node);
            }
            function nextTokenIsNumericLiteral() {
                return nextToken() === 8 /* NumericLiteral */;
            }
            function parseNonArrayType() {
                switch (token()) {
                    case 119 /* AnyKeyword */:
                    case 142 /* UnknownKeyword */:
                    case 137 /* StringKeyword */:
                    case 134 /* NumberKeyword */:
                    case 138 /* SymbolKeyword */:
                    case 122 /* BooleanKeyword */:
                    case 140 /* UndefinedKeyword */:
                    case 131 /* NeverKeyword */:
                    case 135 /* ObjectKeyword */:
                        // If these are followed by a dot, then parse these out as a dotted type reference instead.
                        return tryParse(parseKeywordAndNoDot) || parseTypeReference();
                    case 39 /* AsteriskToken */:
                        return parseJSDocAllType(/*postfixEquals*/ false);
                    case 61 /* AsteriskEqualsToken */:
                        return parseJSDocAllType(/*postfixEquals*/ true);
                    case 55 /* QuestionToken */:
                        return parseJSDocUnknownOrNullableType();
                    case 89 /* FunctionKeyword */:
                        return parseJSDocFunctionType();
                    case 51 /* ExclamationToken */:
                        return parseJSDocNonNullableType();
                    case 13 /* NoSubstitutionTemplateLiteral */:
                    case 9 /* StringLiteral */:
                    case 8 /* NumericLiteral */:
                    case 101 /* TrueKeyword */:
                    case 86 /* FalseKeyword */:
                        return parseLiteralTypeNode();
                    case 38 /* MinusToken */:
                        return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
                    case 105 /* VoidKeyword */:
                    case 95 /* NullKeyword */:
                        return parseTokenNode();
                    case 99 /* ThisKeyword */: {
                        var thisKeyword = parseThisTypeNode();
                        if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
                            return parseThisTypePredicate(thisKeyword);
                        }
                        else {
                            return thisKeyword;
                        }
                    }
                    case 103 /* TypeOfKeyword */:
                        return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
                    case 17 /* OpenBraceToken */:
                        return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
                    case 21 /* OpenBracketToken */:
                        return parseTupleType();
                    case 19 /* OpenParenToken */:
                        return parseParenthesizedType();
                    case 91 /* ImportKeyword */:
                        return parseImportType();
                    default:
                        return parseTypeReference();
                }
            }
            function isStartOfType(inStartOfParameter) {
                switch (token()) {
                    case 119 /* AnyKeyword */:
                    case 142 /* UnknownKeyword */:
                    case 137 /* StringKeyword */:
                    case 134 /* NumberKeyword */:
                    case 122 /* BooleanKeyword */:
                    case 138 /* SymbolKeyword */:
                    case 141 /* UniqueKeyword */:
                    case 105 /* VoidKeyword */:
                    case 140 /* UndefinedKeyword */:
                    case 95 /* NullKeyword */:
                    case 99 /* ThisKeyword */:
                    case 103 /* TypeOfKeyword */:
                    case 131 /* NeverKeyword */:
                    case 17 /* OpenBraceToken */:
                    case 21 /* OpenBracketToken */:
                    case 27 /* LessThanToken */:
                    case 49 /* BarToken */:
                    case 48 /* AmpersandToken */:
                    case 94 /* NewKeyword */:
                    case 9 /* StringLiteral */:
                    case 8 /* NumericLiteral */:
                    case 101 /* TrueKeyword */:
                    case 86 /* FalseKeyword */:
                    case 135 /* ObjectKeyword */:
                    case 39 /* AsteriskToken */:
                    case 55 /* QuestionToken */:
                    case 51 /* ExclamationToken */:
                    case 24 /* DotDotDotToken */:
                    case 126 /* InferKeyword */:
                    case 91 /* ImportKeyword */:
                        return true;
                    case 89 /* FunctionKeyword */:
                        return !inStartOfParameter;
                    case 38 /* MinusToken */:
                        return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral);
                    case 19 /* OpenParenToken */:
                        // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
                        // or something that starts a type. We don't want to consider things like '(1)' a type.
                        return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
                    default:
                        return isIdentifier();
                }
            }
            function isStartOfParenthesizedOrFunctionType() {
                nextToken();
                return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
            }
            function parsePostfixTypeOrHigher() {
                var type = parseNonArrayType();
                while (!scanner.hasPrecedingLineBreak()) {
                    switch (token()) {
                        case 51 /* ExclamationToken */:
                            type = createPostfixType(285 /* JSDocNonNullableType */, type);
                            break;
                        case 55 /* QuestionToken */:
                            // If not in JSDoc and next token is start of a type we have a conditional type
                            if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
                                return type;
                            }
                            type = createPostfixType(284 /* JSDocNullableType */, type);
                            break;
                        case 21 /* OpenBracketToken */:
                            parseExpected(21 /* OpenBracketToken */);
                            if (isStartOfType()) {
                                var node = createNode(178 /* IndexedAccessType */, type.pos);
                                node.objectType = type;
                                node.indexType = parseType();
                                parseExpected(22 /* CloseBracketToken */);
                                type = finishNode(node);
                            }
                            else {
                                var node = createNode(167 /* ArrayType */, type.pos);
                                node.elementType = type;
                                parseExpected(22 /* CloseBracketToken */);
                                type = finishNode(node);
                            }
                            break;
                        default:
                            return type;
                    }
                }
                return type;
            }
            function createPostfixType(kind, type) {
                nextToken();
                var postfix = createNode(kind, type.pos);
                postfix.type = type;
                return finishNode(postfix);
            }
            function parseTypeOperator(operator) {
                var node = createNode(177 /* TypeOperator */);
                parseExpected(operator);
                node.operator = operator;
                node.type = parseTypeOperatorOrHigher();
                return finishNode(node);
            }
            function parseInferType() {
                var node = createNode(174 /* InferType */);
                parseExpected(126 /* InferKeyword */);
                var typeParameter = createNode(148 /* TypeParameter */);
                typeParameter.name = parseIdentifier();
                node.typeParameter = finishNode(typeParameter);
                return finishNode(node);
            }
            function parseTypeOperatorOrHigher() {
                var operator = token();
                switch (operator) {
                    case 128 /* KeyOfKeyword */:
                    case 141 /* UniqueKeyword */:
                        return parseTypeOperator(operator);
                    case 126 /* InferKeyword */:
                        return parseInferType();
                }
                return parsePostfixTypeOrHigher();
            }
            function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
                parseOptional(operator);
                var type = parseConstituentType();
                if (token() === operator) {
                    var types = [type];
                    while (parseOptional(operator)) {
                        types.push(parseConstituentType());
                    }
                    var node = createNode(kind, type.pos);
                    node.types = createNodeArray(types, type.pos);
                    type = finishNode(node);
                }
                return type;
            }
            function parseIntersectionTypeOrHigher() {
                return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */);
            }
            function parseUnionTypeOrHigher() {
                return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */);
            }
            function isStartOfFunctionType() {
                if (token() === 27 /* LessThanToken */) {
                    return true;
                }
                return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
            }
            function skipParameterStart() {
                if (ts.isModifierKind(token())) {
                    // Skip modifiers
                    parseModifiers();
                }
                if (isIdentifier() || token() === 99 /* ThisKeyword */) {
                    nextToken();
                    return true;
                }
                if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) {
                    // Return true if we can parse an array or object binding pattern with no errors
                    var previousErrorCount = parseDiagnostics.length;
                    parseIdentifierOrPattern();
                    return previousErrorCount === parseDiagnostics.length;
                }
                return false;
            }
            function isUnambiguouslyStartOfFunctionType() {
                nextToken();
                if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) {
                    // ( )
                    // ( ...
                    return true;
                }
                if (skipParameterStart()) {
                    // We successfully skipped modifiers (if any) and an identifier or binding pattern,
                    // now see if we have something that indicates a parameter declaration
                    if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ ||
                        token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) {
                        // ( xxx :
                        // ( xxx ,
                        // ( xxx ?
                        // ( xxx =
                        return true;
                    }
                    if (token() === 20 /* CloseParenToken */) {
                        nextToken();
                        if (token() === 36 /* EqualsGreaterThanToken */) {
                            // ( xxx ) =>
                            return true;
                        }
                    }
                }
                return false;
            }
            function parseTypeOrTypePredicate() {
                var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
                var type = parseType();
                if (typePredicateVariable) {
                    var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos);
                    node.parameterName = typePredicateVariable;
                    node.type = type;
                    return finishNode(node);
                }
                else {
                    return type;
                }
            }
            function parseTypePredicatePrefix() {
                var id = parseIdentifier();
                if (token() === 127 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
                    nextToken();
                    return id;
                }
            }
            function parseType() {
                // The rules about 'yield' only apply to actual code/expression contexts.  They don't
                // apply to 'type' contexts.  So we disable these parameters here before moving on.
                return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker);
            }
            function parseTypeWorker(noConditionalTypes) {
                if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) {
                    return parseFunctionOrConstructorType();
                }
                var type = parseUnionTypeOrHigher();
                if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) {
                    var node = createNode(173 /* ConditionalType */, type.pos);
                    node.checkType = type;
                    // The type following 'extends' is not permitted to be another conditional type
                    node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
                    parseExpected(55 /* QuestionToken */);
                    node.trueType = parseTypeWorker();
                    parseExpected(56 /* ColonToken */);
                    node.falseType = parseTypeWorker();
                    return finishNode(node);
                }
                return type;
            }
            function parseTypeAnnotation() {
                return parseOptional(56 /* ColonToken */) ? parseType() : undefined;
            }
            // EXPRESSIONS
            function isStartOfLeftHandSideExpression() {
                switch (token()) {
                    case 99 /* ThisKeyword */:
                    case 97 /* SuperKeyword */:
                    case 95 /* NullKeyword */:
                    case 101 /* TrueKeyword */:
                    case 86 /* FalseKeyword */:
                    case 8 /* NumericLiteral */:
                    case 9 /* StringLiteral */:
                    case 13 /* NoSubstitutionTemplateLiteral */:
                    case 14 /* TemplateHead */:
                    case 19 /* OpenParenToken */:
                    case 21 /* OpenBracketToken */:
                    case 17 /* OpenBraceToken */:
                    case 89 /* FunctionKeyword */:
                    case 75 /* ClassKeyword */:
                    case 94 /* NewKeyword */:
                    case 41 /* SlashToken */:
                    case 63 /* SlashEqualsToken */:
                    case 71 /* Identifier */:
                        return true;
                    case 91 /* ImportKeyword */:
                        return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
                    default:
                        return isIdentifier();
                }
            }
            function isStartOfExpression() {
                if (isStartOfLeftHandSideExpression()) {
                    return true;
                }
                switch (token()) {
                    case 37 /* PlusToken */:
                    case 38 /* MinusToken */:
                    case 52 /* TildeToken */:
                    case 51 /* ExclamationToken */:
                    case 80 /* DeleteKeyword */:
                    case 103 /* TypeOfKeyword */:
                    case 105 /* VoidKeyword */:
                    case 43 /* PlusPlusToken */:
                    case 44 /* MinusMinusToken */:
                    case 27 /* LessThanToken */:
                    case 121 /* AwaitKeyword */:
                    case 116 /* YieldKeyword */:
                        // Yield/await always starts an expression.  Either it is an identifier (in which case
                        // it is definitely an expression).  Or it's a keyword (either because we're in
                        // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
                        return true;
                    default:
                        // Error tolerance.  If we see the start of some binary operator, we consider
                        // that the start of an expression.  That way we'll parse out a missing identifier,
                        // give a good message about an identifier being missing, and then consume the
                        // rest of the binary expression.
                        if (isBinaryOperator()) {
                            return true;
                        }
                        return isIdentifier();
                }
            }
            function isStartOfExpressionStatement() {
                // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
                return token() !== 17 /* OpenBraceToken */ &&
                    token() !== 89 /* FunctionKeyword */ &&
                    token() !== 75 /* ClassKeyword */ &&
                    token() !== 57 /* AtToken */ &&
                    isStartOfExpression();
            }
            function parseExpression() {
                // Expression[in]:
                //      AssignmentExpression[in]
                //      Expression[in] , AssignmentExpression[in]
                // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
                var saveDecoratorContext = inDecoratorContext();
                if (saveDecoratorContext) {
                    setDecoratorContext(/*val*/ false);
                }
                var expr = parseAssignmentExpressionOrHigher();
                var operatorToken;
                while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) {
                    expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
                }
                if (saveDecoratorContext) {
                    setDecoratorContext(/*val*/ true);
                }
                return expr;
            }
            function parseInitializer() {
                return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
            }
            function parseAssignmentExpressionOrHigher() {
                //  AssignmentExpression[in,yield]:
                //      1) ConditionalExpression[?in,?yield]
                //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
                //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
                //      4) ArrowFunctionExpression[?in,?yield]
                //      5) AsyncArrowFunctionExpression[in,yield,await]
                //      6) [+Yield] YieldExpression[?In]
                //
                // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
                // (i.e. they're both BinaryExpressions with an assignment operator in it).
                // First, do the simple check if we have a YieldExpression (production '6').
                if (isYieldExpression()) {
                    return parseYieldExpression();
                }
                // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
                // parameter list or is an async arrow function.
                // AsyncArrowFunctionExpression:
                //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
                //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
                // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
                // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
                //
                // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
                // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
                // with AssignmentExpression if we see one.
                var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
                if (arrowExpression) {
                    return arrowExpression;
                }
                // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
                // start with a LogicalOrExpression, while the assignment productions can only start with
                // LeftHandSideExpressions.
                //
                // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
                // LeftHandSide or higher, then we can try to parse out the assignment expression part.
                // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
                // binary expression here, so we pass in the 'lowest' precedence here so that it matches
                // and consumes anything.
                var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
                // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
                // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
                // identifier and the current token is an arrow.
                if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) {
                    return parseSimpleArrowFunctionExpression(expr);
                }
                // Now see if we might be in cases '2' or '3'.
                // If the expression was a LHS expression, and we have an assignment operator, then
                // we're in '2' or '3'. Consume the assignment and return.
                //
                // Note: we call reScanGreaterToken so that we get an appropriately merged token
                // for cases like `> > =` becoming `>>=`
                if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
                    return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
                }
                // It wasn't an assignment or a lambda.  This is a conditional expression:
                return parseConditionalExpressionRest(expr);
            }
            function isYieldExpression() {
                if (token() === 116 /* YieldKeyword */) {
                    // If we have a 'yield' keyword, and this is a context where yield expressions are
                    // allowed, then definitely parse out a yield expression.
                    if (inYieldContext()) {
                        return true;
                    }
                    // We're in a context where 'yield expr' is not allowed.  However, if we can
                    // definitely tell that the user was trying to parse a 'yield expr' and not
                    // just a normal expr that start with a 'yield' identifier, then parse out
                    // a 'yield expr'.  We can then report an error later that they are only
                    // allowed in generator expressions.
                    //
                    // for example, if we see 'yield(foo)', then we'll have to treat that as an
                    // invocation expression of something called 'yield'.  However, if we have
                    // 'yield foo' then that is not legal as a normal expression, so we can
                    // definitely recognize this as a yield expression.
                    //
                    // for now we just check if the next token is an identifier.  More heuristics
                    // can be added here later as necessary.  We just need to make sure that we
                    // don't accidentally consume something legal.
                    return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
                }
                return false;
            }
            function nextTokenIsIdentifierOnSameLine() {
                nextToken();
                return !scanner.hasPrecedingLineBreak() && isIdentifier();
            }
            function parseYieldExpression() {
                var node = createNode(205 /* YieldExpression */);
                // YieldExpression[In] :
                //      yield
                //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
                //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
                nextToken();
                if (!scanner.hasPrecedingLineBreak() &&
                    (token() === 39 /* AsteriskToken */ || isStartOfExpression())) {
                    node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
                    node.expression = parseAssignmentExpressionOrHigher();
                    return finishNode(node);
                }
                else {
                    // if the next token is not on the same line as yield.  or we don't have an '*' or
                    // the start of an expression, then this is just a simple "yield" expression.
                    return finishNode(node);
                }
            }
            function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
                ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
                var node;
                if (asyncModifier) {
                    node = createNode(195 /* ArrowFunction */, asyncModifier.pos);
                    node.modifiers = asyncModifier;
                }
                else {
                    node = createNode(195 /* ArrowFunction */, identifier.pos);
                }
                var parameter = createNode(149 /* Parameter */, identifier.pos);
                parameter.name = identifier;
                finishNode(parameter);
                node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
                node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */);
                node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
                return addJSDocComment(finishNode(node));
            }
            function tryParseParenthesizedArrowFunctionExpression() {
                var triState = isParenthesizedArrowFunctionExpression();
                if (triState === 0 /* False */) {
                    // It's definitely not a parenthesized arrow function expression.
                    return undefined;
                }
                // If we definitely have an arrow function, then we can just parse one, not requiring a
                // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
                // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
                // expression instead.
                var arrowFunction = triState === 1 /* True */
                    ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
                    : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
                if (!arrowFunction) {
                    // Didn't appear to actually be a parenthesized arrow function.  Just bail out.
                    return undefined;
                }
                var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */);
                // If we have an arrow, then try to parse the body. Even if not, try to parse if we
                // have an opening brace, just in case we're in an error state.
                var lastToken = token();
                arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */);
                arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */)
                    ? parseArrowFunctionExpressionBody(isAsync)
                    : parseIdentifier();
                return finishNode(arrowFunction);
            }
            //  True        -> We definitely expect a parenthesized arrow function here.
            //  False       -> There *cannot* be a parenthesized arrow function here.
            //  Unknown     -> There *might* be a parenthesized arrow function here.
            //                 Speculatively look ahead to be sure, and rollback if not.
            function isParenthesizedArrowFunctionExpression() {
                if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) {
                    return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
                }
                if (token() === 36 /* EqualsGreaterThanToken */) {
                    // ERROR RECOVERY TWEAK:
                    // If we see a standalone => try to parse it as an arrow function expression as that's
                    // likely what the user intended to write.
                    return 1 /* True */;
                }
                // Definitely not a parenthesized arrow function.
                return 0 /* False */;
            }
            function isParenthesizedArrowFunctionExpressionWorker() {
                if (token() === 120 /* AsyncKeyword */) {
                    nextToken();
                    if (scanner.hasPrecedingLineBreak()) {
                        return 0 /* False */;
                    }
                    if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) {
                        return 0 /* False */;
                    }
                }
                var first = token();
                var second = nextToken();
                if (first === 19 /* OpenParenToken */) {
                    if (second === 20 /* CloseParenToken */) {
                        // Simple cases: "() =>", "(): ", and "() {".
                        // This is an arrow function with no parameters.
                        // The last one is not actually an arrow function,
                        // but this is probably what the user intended.
                        var third = nextToken();
                        switch (third) {
                            case 36 /* EqualsGreaterThanToken */:
                            case 56 /* ColonToken */:
                            case 17 /* OpenBraceToken */:
                                return 1 /* True */;
                            default:
                                return 0 /* False */;
                        }
                    }
                    // If encounter "([" or "({", this could be the start of a binding pattern.
                    // Examples:
                    //      ([ x ]) => { }
                    //      ({ x }) => { }
                    //      ([ x ])
                    //      ({ x })
                    if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) {
                        return 2 /* Unknown */;
                    }
                    // Simple case: "(..."
                    // This is an arrow function with a rest parameter.
                    if (second === 24 /* DotDotDotToken */) {
                        return 1 /* True */;
                    }
                    // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
                    // isn't actually allowed, but we want to treat it as a lambda so we can provide
                    // a good error message.
                    if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
                        return 1 /* True */;
                    }
                    // If we had "(" followed by something that's not an identifier,
                    // then this definitely doesn't look like a lambda.  "this" is not
                    // valid, but we want to parse it and then give a semantic error.
                    if (!isIdentifier() && second !== 99 /* ThisKeyword */) {
                        return 0 /* False */;
                    }
                    switch (nextToken()) {
                        case 56 /* ColonToken */:
                            // If we have something like "(a:", then we must have a
                            // type-annotated parameter in an arrow function expression.
                            return 1 /* True */;
                        case 55 /* QuestionToken */:
                            nextToken();
                            // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
                            if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) {
                                return 1 /* True */;
                            }
                            // Otherwise it is definitely not a lambda.
                            return 0 /* False */;
                        case 26 /* CommaToken */:
                        case 58 /* EqualsToken */:
                        case 20 /* CloseParenToken */:
                            // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
                            return 2 /* Unknown */;
                    }
                    // It is definitely not an arrow function
                    return 0 /* False */;
                }
                else {
                    ts.Debug.assert(first === 27 /* LessThanToken */);
                    // If we have "<" not followed by an identifier,
                    // then this definitely is not an arrow function.
                    if (!isIdentifier()) {
                        return 0 /* False */;
                    }
                    // JSX overrides
                    if (sourceFile.languageVariant === 1 /* JSX */) {
                        var isArrowFunctionInJsx = lookAhead(function () {
                            var third = nextToken();
                            if (third === 85 /* ExtendsKeyword */) {
                                var fourth = nextToken();
                                switch (fourth) {
                                    case 58 /* EqualsToken */:
                                    case 29 /* GreaterThanToken */:
                                        return false;
                                    default:
                                        return true;
                                }
                            }
                            else if (third === 26 /* CommaToken */) {
                                return true;
                            }
                            return false;
                        });
                        if (isArrowFunctionInJsx) {
                            return 1 /* True */;
                        }
                        return 0 /* False */;
                    }
                    // This *could* be a parenthesized arrow function.
                    return 2 /* Unknown */;
                }
            }
            function parsePossibleParenthesizedArrowFunctionExpressionHead() {
                return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
            }
            function tryParseAsyncSimpleArrowFunctionExpression() {
                // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
                if (token() === 120 /* AsyncKeyword */) {
                    if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
                        var asyncModifier = parseModifiersForArrowFunction();
                        var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
                        return parseSimpleArrowFunctionExpression(expr, asyncModifier);
                    }
                }
                return undefined;
            }
            function isUnParenthesizedAsyncArrowFunctionWorker() {
                // AsyncArrowFunctionExpression:
                //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
                //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
                if (token() === 120 /* AsyncKeyword */) {
                    nextToken();
                    // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
                    // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
                    if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) {
                        return 0 /* False */;
                    }
                    // Check for un-parenthesized AsyncArrowFunction
                    var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
                    if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) {
                        return 1 /* True */;
                    }
                }
                return 0 /* False */;
            }
            function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
                var node = createNodeWithJSDoc(195 /* ArrowFunction */);
                node.modifiers = parseModifiersForArrowFunction();
                var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
                // Arrow functions are never generators.
                //
                // If we're speculatively parsing a signature for a parenthesized arrow function, then
                // we have to have a complete parameter list.  Otherwise we might see something like
                // a => (b => c)
                // And think that "(b =>" was actually a parenthesized arrow function with a missing
                // close paren.
                if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
                    return undefined;
                }
                // Parsing a signature isn't enough.
                // Parenthesized arrow signatures often look like other valid expressions.
                // For instance:
                //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
                //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
                //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
                //
                // So we need just a bit of lookahead to ensure that it can only be a signature.
                if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) {
                    // Returning undefined here will cause our caller to rewind to where we started from.
                    return undefined;
                }
                return node;
            }
            function parseArrowFunctionExpressionBody(isAsync) {
                if (token() === 17 /* OpenBraceToken */) {
                    return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
                }
                if (token() !== 25 /* SemicolonToken */ &&
                    token() !== 89 /* FunctionKeyword */ &&
                    token() !== 75 /* ClassKeyword */ &&
                    isStartOfStatement() &&
                    !isStartOfExpressionStatement()) {
                    // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
                    //
                    // Here we try to recover from a potential error situation in the case where the
                    // user meant to supply a block. For example, if the user wrote:
                    //
                    //  a =>
                    //      let v = 0;
                    //  }
                    //
                    // they may be missing an open brace.  Check to see if that's the case so we can
                    // try to recover better.  If we don't do this, then the next close curly we see may end
                    // up preemptively closing the containing construct.
                    //
                    // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
                    return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
                }
                return isAsync
                    ? doInAwaitContext(parseAssignmentExpressionOrHigher)
                    : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
            }
            function parseConditionalExpressionRest(leftOperand) {
                // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
                var questionToken = parseOptionalToken(55 /* QuestionToken */);
                if (!questionToken) {
                    return leftOperand;
                }
                // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
                // we do not that for the 'whenFalse' part.
                var node = createNode(203 /* ConditionalExpression */, leftOperand.pos);
                node.condition = leftOperand;
                node.questionToken = questionToken;
                node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
                node.colonToken = parseExpectedToken(56 /* ColonToken */);
                node.whenFalse = ts.nodeIsPresent(node.colonToken)
                    ? parseAssignmentExpressionOrHigher()
                    : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */));
                return finishNode(node);
            }
            function parseBinaryExpressionOrHigher(precedence) {
                var leftOperand = parseUnaryExpressionOrHigher();
                return parseBinaryExpressionRest(precedence, leftOperand);
            }
            function isInOrOfKeyword(t) {
                return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */;
            }
            function parseBinaryExpressionRest(precedence, leftOperand) {
                while (true) {
                    // We either have a binary operator here, or we're finished.  We call
                    // reScanGreaterToken so that we merge token sequences like > and = into >=
                    reScanGreaterToken();
                    var newPrecedence = ts.getBinaryOperatorPrecedence(token());
                    // Check the precedence to see if we should "take" this operator
                    // - For left associative operator (all operator but **), consume the operator,
                    //   recursively call the function below, and parse binaryExpression as a rightOperand
                    //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
                    //   For example:
                    //      a - b - c;
                    //            ^token; leftOperand = b. Return b to the caller as a rightOperand
                    //      a * b - c
                    //            ^token; leftOperand = b. Return b to the caller as a rightOperand
                    //      a - b * c;
                    //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
                    // - For right associative operator (**), consume the operator, recursively call the function
                    //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
                    //   the operator is strictly grater than the current precedence
                    //   For example:
                    //      a ** b ** c;
                    //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
                    //      a - b ** c;
                    //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
                    //      a ** b - c
                    //             ^token; leftOperand = b. Return b to the caller as a rightOperand
                    var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ?
                        newPrecedence >= precedence :
                        newPrecedence > precedence;
                    if (!consumeCurrentOperator) {
                        break;
                    }
                    if (token() === 92 /* InKeyword */ && inDisallowInContext()) {
                        break;
                    }
                    if (token() === 118 /* AsKeyword */) {
                        // Make sure we *do* perform ASI for constructs like this:
                        //    var x = foo
                        //    as (Bar)
                        // This should be parsed as an initialized variable, followed
                        // by a function call to 'as' with the argument 'Bar'
                        if (scanner.hasPrecedingLineBreak()) {
                            break;
                        }
                        else {
                            nextToken();
                            leftOperand = makeAsExpression(leftOperand, parseType());
                        }
                    }
                    else {
                        leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
                    }
                }
                return leftOperand;
            }
            function isBinaryOperator() {
                if (inDisallowInContext() && token() === 92 /* InKeyword */) {
                    return false;
                }
                return ts.getBinaryOperatorPrecedence(token()) > 0;
            }
            function makeBinaryExpression(left, operatorToken, right) {
                var node = createNode(202 /* BinaryExpression */, left.pos);
                node.left = left;
                node.operatorToken = operatorToken;
                node.right = right;
                return finishNode(node);
            }
            function makeAsExpression(left, right) {
                var node = createNode(210 /* AsExpression */, left.pos);
                node.expression = left;
                node.type = right;
                return finishNode(node);
            }
            function parsePrefixUnaryExpression() {
                var node = createNode(200 /* PrefixUnaryExpression */);
                node.operator = token();
                nextToken();
                node.operand = parseSimpleUnaryExpression();
                return finishNode(node);
            }
            function parseDeleteExpression() {
                var node = createNode(196 /* DeleteExpression */);
                nextToken();
                node.expression = parseSimpleUnaryExpression();
                return finishNode(node);
            }
            function parseTypeOfExpression() {
                var node = createNode(197 /* TypeOfExpression */);
                nextToken();
                node.expression = parseSimpleUnaryExpression();
                return finishNode(node);
            }
            function parseVoidExpression() {
                var node = createNode(198 /* VoidExpression */);
                nextToken();
                node.expression = parseSimpleUnaryExpression();
                return finishNode(node);
            }
            function isAwaitExpression() {
                if (token() === 121 /* AwaitKeyword */) {
                    if (inAwaitContext()) {
                        return true;
                    }
                    // here we are using similar heuristics as 'isYieldExpression'
                    return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
                }
                return false;
            }
            function parseAwaitExpression() {
                var node = createNode(199 /* AwaitExpression */);
                nextToken();
                node.expression = parseSimpleUnaryExpression();
                return finishNode(node);
            }
            /**
             * Parse ES7 exponential expression and await expression
             *
             * ES7 ExponentiationExpression:
             *      1) UnaryExpression[?Yield]
             *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
             *
             */
            function parseUnaryExpressionOrHigher() {
                /**
                 * ES7 UpdateExpression:
                 *      1) LeftHandSideExpression[?Yield]
                 *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
                 *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
                 *      4) ++UnaryExpression[?Yield]
                 *      5) --UnaryExpression[?Yield]
                 */
                if (isUpdateExpression()) {
                    var updateExpression = parseUpdateExpression();
                    return token() === 40 /* AsteriskAsteriskToken */ ?
                        parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
                        updateExpression;
                }
                /**
                 * ES7 UnaryExpression:
                 *      1) UpdateExpression[?yield]
                 *      2) delete UpdateExpression[?yield]
                 *      3) void UpdateExpression[?yield]
                 *      4) typeof UpdateExpression[?yield]
                 *      5) + UpdateExpression[?yield]
                 *      6) - UpdateExpression[?yield]
                 *      7) ~ UpdateExpression[?yield]
                 *      8) ! UpdateExpression[?yield]
                 */
                var unaryOperator = token();
                var simpleUnaryExpression = parseSimpleUnaryExpression();
                if (token() === 40 /* AsteriskAsteriskToken */) {
                    var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
                    var end = simpleUnaryExpression.end;
                    if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) {
                        parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
                    }
                    else {
                        parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator));
                    }
                }
                return simpleUnaryExpression;
            }
            /**
             * Parse ES7 simple-unary expression or higher:
             *
             * ES7 UnaryExpression:
             *      1) UpdateExpression[?yield]
             *      2) delete UnaryExpression[?yield]
             *      3) void UnaryExpression[?yield]
             *      4) typeof UnaryExpression[?yield]
             *      5) + UnaryExpression[?yield]
             *      6) - UnaryExpression[?yield]
             *      7) ~ UnaryExpression[?yield]
             *      8) ! UnaryExpression[?yield]
             *      9) [+Await] await UnaryExpression[?yield]
             */
            function parseSimpleUnaryExpression() {
                switch (token()) {
                    case 37 /* PlusToken */:
                    case 38 /* MinusToken */:
                    case 52 /* TildeToken */:
                    case 51 /* ExclamationToken */:
                        return parsePrefixUnaryExpression();
                    case 80 /* DeleteKeyword */:
                        return parseDeleteExpression();
                    case 103 /* TypeOfKeyword */:
                        return parseTypeOfExpression();
                    case 105 /* VoidKeyword */:
                        return parseVoidExpression();
                    case 27 /* LessThanToken */:
                        // This is modified UnaryExpression grammar in TypeScript
                        //  UnaryExpression (modified):
                        //      < type > UnaryExpression
                        return parseTypeAssertion();
                    case 121 /* AwaitKeyword */:
                        if (isAwaitExpression()) {
                            return parseAwaitExpression();
                        }
                    // falls through
                    default:
                        return parseUpdateExpression();
                }
            }
            /**
             * Check if the current token can possibly be an ES7 increment expression.
             *
             * ES7 UpdateExpression:
             *      LeftHandSideExpression[?Yield]
             *      LeftHandSideExpression[?Yield][no LineTerminator here]++
             *      LeftHandSideExpression[?Yield][no LineTerminator here]--
             *      ++LeftHandSideExpression[?Yield]
             *      --LeftHandSideExpression[?Yield]
             */
            function isUpdateExpression() {
                // This function is called inside parseUnaryExpression to decide
                // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
                switch (token()) {
                    case 37 /* PlusToken */:
                    case 38 /* MinusToken */:
                    case 52 /* TildeToken */:
                    case 51 /* ExclamationToken */:
                    case 80 /* DeleteKeyword */:
                    case 103 /* TypeOfKeyword */:
                    case 105 /* VoidKeyword */:
                    case 121 /* AwaitKeyword */:
                        return false;
                    case 27 /* LessThanToken */:
                        // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
                        if (sourceFile.languageVariant !== 1 /* JSX */) {
                            return false;
                        }
                    // We are in JSX context and the token is part of JSXElement.
                    // falls through
                    default:
                        return true;
                }
            }
            /**
             * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
             *
             * ES7 UpdateExpression[yield]:
             *      1) LeftHandSideExpression[?yield]
             *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
             *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
             *      4) ++LeftHandSideExpression[?yield]
             *      5) --LeftHandSideExpression[?yield]
             * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
             */
            function parseUpdateExpression() {
                if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) {
                    var node = createNode(200 /* PrefixUnaryExpression */);
                    node.operator = token();
                    nextToken();
                    node.operand = parseLeftHandSideExpressionOrHigher();
                    return finishNode(node);
                }
                else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
                    // JSXElement is part of primaryExpression
                    return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
                }
                var expression = parseLeftHandSideExpressionOrHigher();
                ts.Debug.assert(ts.isLeftHandSideExpression(expression));
                if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
                    var node = createNode(201 /* PostfixUnaryExpression */, expression.pos);
                    node.operand = expression;
                    node.operator = token();
                    nextToken();
                    return finishNode(node);
                }
                return expression;
            }
            function parseLeftHandSideExpressionOrHigher() {
                // Original Ecma:
                // LeftHandSideExpression: See 11.2
                //      NewExpression
                //      CallExpression
                //
                // Our simplification:
                //
                // LeftHandSideExpression: See 11.2
                //      MemberExpression
                //      CallExpression
                //
                // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
                // MemberExpression to make our lives easier.
                //
                // to best understand the below code, it's important to see how CallExpression expands
                // out into its own productions:
                //
                // CallExpression:
                //      MemberExpression Arguments
                //      CallExpression Arguments
                //      CallExpression[Expression]
                //      CallExpression.IdentifierName
                //      import (AssignmentExpression)
                //      super Arguments
                //      super.IdentifierName
                //
                // Because of the recursion in these calls, we need to bottom out first. There are three
                // bottom out states we can run into: 1) We see 'super' which must start either of
                // the last two CallExpression productions. 2) We see 'import' which must start import call.
                // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
                // or starts the beginning of the first four CallExpression productions.
                var expression;
                if (token() === 91 /* ImportKeyword */) {
                    if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
                        // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
                        // For example:
                        //      var foo3 = require("subfolder
                        //      import * as foo1 from "module-from-node
                        // We want this import to be a statement rather than import call expression
                        sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */;
                        expression = parseTokenNode();
                    }
                    else if (lookAhead(nextTokenIsDot)) {
                        // This is an 'import.*' metaproperty (i.e. 'import.meta')
                        var fullStart = scanner.getStartPos();
                        nextToken(); // advance past the 'import'
                        nextToken(); // advance past the dot
                        var node = createNode(212 /* MetaProperty */, fullStart);
                        node.keywordToken = 91 /* ImportKeyword */;
                        node.name = parseIdentifierName();
                        expression = finishNode(node);
                        sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */;
                    }
                    else {
                        expression = parseMemberExpressionOrHigher();
                    }
                }
                else {
                    expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
                }
                // Now, we *may* be complete.  However, we might have consumed the start of a
                // CallExpression.  As such, we need to consume the rest of it here to be complete.
                return parseCallExpressionRest(expression);
            }
            function parseMemberExpressionOrHigher() {
                // Note: to make our lives simpler, we decompose the NewExpression productions and
                // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
                // like so:
                //
                //   PrimaryExpression : See 11.1
                //      this
                //      Identifier
                //      Literal
                //      ArrayLiteral
                //      ObjectLiteral
                //      (Expression)
                //      FunctionExpression
                //      new MemberExpression Arguments?
                //
                //   MemberExpression : See 11.2
                //      PrimaryExpression
                //      MemberExpression[Expression]
                //      MemberExpression.IdentifierName
                //
                //   CallExpression : See 11.2
                //      MemberExpression
                //      CallExpression Arguments
                //      CallExpression[Expression]
                //      CallExpression.IdentifierName
                //
                // Technically this is ambiguous.  i.e. CallExpression defines:
                //
                //   CallExpression:
                //      CallExpression Arguments
                //
                // If you see: "new Foo()"
                //
                // Then that could be treated as a single ObjectCreationExpression, or it could be
                // treated as the invocation of "new Foo".  We disambiguate that in code (to match
                // the original grammar) by making sure that if we see an ObjectCreationExpression
                // we always consume arguments if they are there. So we treat "new Foo()" as an
                // object creation only, and not at all as an invocation.  Another way to think
                // about this is that for every "new" that we see, we will consume an argument list if
                // it is there as part of the *associated* object creation node.  Any additional
                // argument lists we see, will become invocation expressions.
                //
                // Because there are no other places in the grammar now that refer to FunctionExpression
                // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
                // production.
                //
                // Because CallExpression and MemberExpression are left recursive, we need to bottom out
                // of the recursion immediately.  So we parse out a primary expression to start with.
                var expression = parsePrimaryExpression();
                return parseMemberExpressionRest(expression);
            }
            function parseSuperExpression() {
                var expression = parseTokenNode();
                if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) {
                    return expression;
                }
                // If we have seen "super" it must be followed by '(' or '.'.
                // If it wasn't then just try to parse out a '.' and report an error.
                var node = createNode(187 /* PropertyAccessExpression */, expression.pos);
                node.expression = expression;
                parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
                node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
                return finishNode(node);
            }
            function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
                var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
                var result;
                if (opening.kind === 260 /* JsxOpeningElement */) {
                    var node = createNode(258 /* JsxElement */, opening.pos);
                    node.openingElement = opening;
                    node.children = parseJsxChildren(node.openingElement);
                    node.closingElement = parseJsxClosingElement(inExpressionContext);
                    if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
                        parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
                    }
                    result = finishNode(node);
                }
                else if (opening.kind === 263 /* JsxOpeningFragment */) {
                    var node = createNode(262 /* JsxFragment */, opening.pos);
                    node.openingFragment = opening;
                    node.children = parseJsxChildren(node.openingFragment);
                    node.closingFragment = parseJsxClosingFragment(inExpressionContext);
                    result = finishNode(node);
                }
                else {
                    ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */);
                    // Nothing else to do for self-closing elements
                    result = opening;
                }
                // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
                // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
                // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
                // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
                // does less damage and we can report a better error.
                // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
                // of one sort or another.
                if (inExpressionContext && token() === 27 /* LessThanToken */) {
                    var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
                    if (invalidElement) {
                        parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
                        var badNode = createNode(202 /* BinaryExpression */, result.pos);
                        badNode.end = invalidElement.end;
                        badNode.left = result;
                        badNode.right = invalidElement;
                        badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217
                        badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
                        return badNode;
                    }
                }
                return result;
            }
            function parseJsxText() {
                var node = createNode(10 /* JsxText */);
                node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */;
                currentToken = scanner.scanJsxToken();
                return finishNode(node);
            }
            function parseJsxChild(openingTag, token) {
                switch (token) {
                    case 1 /* EndOfFileToken */:
                        // If we hit EOF, issue the error at the tag that lacks the closing element
                        // rather than at the end of the file (which is useless)
                        if (ts.isJsxOpeningFragment(openingTag)) {
                            parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
                        }
                        else {
                            parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
                        }
                        return undefined;
                    case 28 /* LessThanSlashToken */:
                    case 7 /* ConflictMarkerTrivia */:
                        return undefined;
                    case 10 /* JsxText */:
                    case 11 /* JsxTextAllWhiteSpaces */:
                        return parseJsxText();
                    case 17 /* OpenBraceToken */:
                        return parseJsxExpression(/*inExpressionContext*/ false);
                    case 27 /* LessThanToken */:
                        return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
                    default:
                        return ts.Debug.assertNever(token);
                }
            }
            function parseJsxChildren(openingTag) {
                var list = [];
                var listPos = getNodePos();
                var saveParsingContext = parsingContext;
                parsingContext |= 1 << 14 /* JsxChildren */;
                while (true) {
                    var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
                    if (!child)
                        break;
                    list.push(child);
                }
                parsingContext = saveParsingContext;
                return createNodeArray(list, listPos);
            }
            function parseJsxAttributes() {
                var jsxAttributes = createNode(266 /* JsxAttributes */);
                jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
                return finishNode(jsxAttributes);
            }
            function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
                var fullStart = scanner.getStartPos();
                parseExpected(27 /* LessThanToken */);
                if (token() === 29 /* GreaterThanToken */) {
                    // See below for explanation of scanJsxText
                    var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart);
                    scanJsxText();
                    return finishNode(node_1);
                }
                var tagName = parseJsxElementName();
                var typeArguments = tryParseTypeArguments();
                var attributes = parseJsxAttributes();
                var node;
                if (token() === 29 /* GreaterThanToken */) {
                    // Closing tag, so scan the immediately-following text with the JSX scanning instead
                    // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
                    // scanning errors
                    node = createNode(260 /* JsxOpeningElement */, fullStart);
                    scanJsxText();
                }
                else {
                    parseExpected(41 /* SlashToken */);
                    if (inExpressionContext) {
                        parseExpected(29 /* GreaterThanToken */);
                    }
                    else {
                        parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
                        scanJsxText();
                    }
                    node = createNode(259 /* JsxSelfClosingElement */, fullStart);
                }
                node.tagName = tagName;
                node.typeArguments = typeArguments;
                node.attributes = attributes;
                return finishNode(node);
            }
            function parseJsxElementName() {
                scanJsxIdentifier();
                // JsxElement can have name in the form of
                //      propertyAccessExpression
                //      primaryExpression in the form of an identifier and "this" keyword
                // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
                // We only want to consider "this" as a primaryExpression
                var expression = token() === 99 /* ThisKeyword */ ?
                    parseTokenNode() : parseIdentifierName();
                while (parseOptional(23 /* DotToken */)) {
                    var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos);
                    propertyAccess.expression = expression;
                    propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
                    expression = finishNode(propertyAccess);
                }
                return expression;
            }
            function parseJsxExpression(inExpressionContext) {
                var node = createNode(268 /* JsxExpression */);
                if (!parseExpected(17 /* OpenBraceToken */)) {
                    return undefined;
                }
                if (token() !== 18 /* CloseBraceToken */) {
                    node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
                    node.expression = parseAssignmentExpressionOrHigher();
                }
                if (inExpressionContext) {
                    parseExpected(18 /* CloseBraceToken */);
                }
                else {
                    parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false);
                    scanJsxText();
                }
                return finishNode(node);
            }
            function parseJsxAttribute() {
                if (token() === 17 /* OpenBraceToken */) {
                    return parseJsxSpreadAttribute();
                }
                scanJsxIdentifier();
                var node = createNode(265 /* JsxAttribute */);
                node.name = parseIdentifierName();
                if (token() === 58 /* EqualsToken */) {
                    switch (scanJsxAttributeValue()) {
                        case 9 /* StringLiteral */:
                            node.initializer = parseLiteralNode();
                            break;
                        default:
                            node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
                            break;
                    }
                }
                return finishNode(node);
            }
            function parseJsxSpreadAttribute() {
                var node = createNode(267 /* JsxSpreadAttribute */);
                parseExpected(17 /* OpenBraceToken */);
                parseExpected(24 /* DotDotDotToken */);
                node.expression = parseExpression();
                parseExpected(18 /* CloseBraceToken */);
                return finishNode(node);
            }
            function parseJsxClosingElement(inExpressionContext) {
                var node = createNode(261 /* JsxClosingElement */);
                parseExpected(28 /* LessThanSlashToken */);
                node.tagName = parseJsxElementName();
                if (inExpressionContext) {
                    parseExpected(29 /* GreaterThanToken */);
                }
                else {
                    parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
                    scanJsxText();
                }
                return finishNode(node);
            }
            function parseJsxClosingFragment(inExpressionContext) {
                var node = createNode(264 /* JsxClosingFragment */);
                parseExpected(28 /* LessThanSlashToken */);
                if (ts.tokenIsIdentifierOrKeyword(token())) {
                    parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
                }
                if (inExpressionContext) {
                    parseExpected(29 /* GreaterThanToken */);
                }
                else {
                    parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
                    scanJsxText();
                }
                return finishNode(node);
            }
            function parseTypeAssertion() {
                var node = createNode(192 /* TypeAssertionExpression */);
                parseExpected(27 /* LessThanToken */);
                node.type = parseType();
                parseExpected(29 /* GreaterThanToken */);
                node.expression = parseSimpleUnaryExpression();
                return finishNode(node);
            }
            function parseMemberExpressionRest(expression) {
                while (true) {
                    var dotToken = parseOptionalToken(23 /* DotToken */);
                    if (dotToken) {
                        var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos);
                        propertyAccess.expression = expression;
                        propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
                        expression = finishNode(propertyAccess);
                        continue;
                    }
                    if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
                        nextToken();
                        var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos);
                        nonNullExpression.expression = expression;
                        expression = finishNode(nonNullExpression);
                        continue;
                    }
                    // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
                    if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) {
                        var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos);
                        indexedAccess.expression = expression;
                        if (token() === 22 /* CloseBracketToken */) {
                            indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
                        }
                        else {
                            var argument = allowInAnd(parseExpression);
                            if (ts.isStringOrNumericLiteralLike(argument)) {
                                argument.text = internIdentifier(argument.text);
                            }
                            indexedAccess.argumentExpression = argument;
                        }
                        parseExpected(22 /* CloseBracketToken */);
                        expression = finishNode(indexedAccess);
                        continue;
                    }
                    if (isTemplateStartOfTaggedTemplate()) {
                        expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined);
                        continue;
                    }
                    return expression;
                }
            }
            function isTemplateStartOfTaggedTemplate() {
                return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */;
            }
            function parseTaggedTemplateRest(tag, typeArguments) {
                var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos);
                tagExpression.tag = tag;
                tagExpression.typeArguments = typeArguments;
                tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */
                    ? parseLiteralNode()
                    : parseTemplateExpression();
                return finishNode(tagExpression);
            }
            function parseCallExpressionRest(expression) {
                while (true) {
                    expression = parseMemberExpressionRest(expression);
                    if (token() === 27 /* LessThanToken */) {
                        // See if this is the start of a generic invocation.  If so, consume it and
                        // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
                        // part of an arithmetic expression.  Break out so we consume it higher in the
                        // stack.
                        var typeArguments = tryParse(parseTypeArgumentsInExpression);
                        if (!typeArguments) {
                            return expression;
                        }
                        if (isTemplateStartOfTaggedTemplate()) {
                            expression = parseTaggedTemplateRest(expression, typeArguments);
                            continue;
                        }
                        var callExpr = createNode(189 /* CallExpression */, expression.pos);
                        callExpr.expression = expression;
                        callExpr.typeArguments = typeArguments;
                        callExpr.arguments = parseArgumentList();
                        expression = finishNode(callExpr);
                        continue;
                    }
                    else if (token() === 19 /* OpenParenToken */) {
                        var callExpr = createNode(189 /* CallExpression */, expression.pos);
                        callExpr.expression = expression;
                        callExpr.arguments = parseArgumentList();
                        expression = finishNode(callExpr);
                        continue;
                    }
                    return expression;
                }
            }
            function parseArgumentList() {
                parseExpected(19 /* OpenParenToken */);
                var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
                parseExpected(20 /* CloseParenToken */);
                return result;
            }
            function parseTypeArgumentsInExpression() {
                if (!parseOptional(27 /* LessThanToken */)) {
                    return undefined;
                }
                var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
                if (!parseExpected(29 /* GreaterThanToken */)) {
                    // If it doesn't have the closing `>` then it's definitely not an type argument list.
                    return undefined;
                }
                // If we have a '<', then only parse this as a argument list if the type arguments
                // are complete and we have an open paren.  if we don't, rewind and return nothing.
                return typeArguments && canFollowTypeArgumentsInExpression()
                    ? typeArguments
                    : undefined;
            }
            function canFollowTypeArgumentsInExpression() {
                switch (token()) {
                    case 19 /* OpenParenToken */: // foo<x>(
                    case 13 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
                    case 14 /* TemplateHead */: // foo<T> `...${100}...`
                    // these are the only tokens can legally follow a type argument
                    // list. So we definitely want to treat them as type arg lists.
                    case 23 /* DotToken */: // foo<x>.
                    case 20 /* CloseParenToken */: // foo<x>)
                    case 22 /* CloseBracketToken */: // foo<x>]
                    case 56 /* ColonToken */: // foo<x>:
                    case 25 /* SemicolonToken */: // foo<x>;
                    case 55 /* QuestionToken */: // foo<x>?
                    case 32 /* EqualsEqualsToken */: // foo<x> ==
                    case 34 /* EqualsEqualsEqualsToken */: // foo<x> ===
                    case 33 /* ExclamationEqualsToken */: // foo<x> !=
                    case 35 /* ExclamationEqualsEqualsToken */: // foo<x> !==
                    case 53 /* AmpersandAmpersandToken */: // foo<x> &&
                    case 54 /* BarBarToken */: // foo<x> ||
                    case 50 /* CaretToken */: // foo<x> ^
                    case 48 /* AmpersandToken */: // foo<x> &
                    case 49 /* BarToken */: // foo<x> |
                    case 18 /* CloseBraceToken */: // foo<x> }
                    case 1 /* EndOfFileToken */: // foo<x>
                        // these cases can't legally follow a type arg list.  However, they're not legal
                        // expressions either.  The user is probably in the middle of a generic type. So
                        // treat it as such.
                        return true;
                    case 26 /* CommaToken */: // foo<x>,
                    case 17 /* OpenBraceToken */: // foo<x> {
                    // We don't want to treat these as type arguments.  Otherwise we'll parse this
                    // as an invocation expression.  Instead, we want to parse out the expression
                    // in isolation from the type arguments.
                    default:
                        // Anything else treat as an expression.
                        return false;
                }
            }
            function parsePrimaryExpression() {
                switch (token()) {
                    case 8 /* NumericLiteral */:
                    case 9 /* StringLiteral */:
                    case 13 /* NoSubstitutionTemplateLiteral */:
                        return parseLiteralNode();
                    case 99 /* ThisKeyword */:
                    case 97 /* SuperKeyword */:
                    case 95 /* NullKeyword */:
                    case 101 /* TrueKeyword */:
                    case 86 /* FalseKeyword */:
                        return parseTokenNode();
                    case 19 /* OpenParenToken */:
                        return parseParenthesizedExpression();
                    case 21 /* OpenBracketToken */:
                        return parseArrayLiteralExpression();
                    case 17 /* OpenBraceToken */:
                        return parseObjectLiteralExpression();
                    case 120 /* AsyncKeyword */:
                        // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
                        // If we encounter `async [no LineTerminator here] function` then this is an async
                        // function; otherwise, its an identifier.
                        if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
                            break;
                        }
                        return parseFunctionExpression();
                    case 75 /* ClassKeyword */:
                        return parseClassExpression();
                    case 89 /* FunctionKeyword */:
                        return parseFunctionExpression();
                    case 94 /* NewKeyword */:
                        return parseNewExpressionOrNewDotTarget();
                    case 41 /* SlashToken */:
                    case 63 /* SlashEqualsToken */:
                        if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) {
                            return parseLiteralNode();
                        }
                        break;
                    case 14 /* TemplateHead */:
                        return parseTemplateExpression();
                }
                return parseIdentifier(ts.Diagnostics.Expression_expected);
            }
            function parseParenthesizedExpression() {
                var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */);
                parseExpected(19 /* OpenParenToken */);
                node.expression = allowInAnd(parseExpression);
                parseExpected(20 /* CloseParenToken */);
                return finishNode(node);
            }
            function parseSpreadElement() {
                var node = createNode(206 /* SpreadElement */);
                parseExpected(24 /* DotDotDotToken */);
                node.expression = parseAssignmentExpressionOrHigher();
                return finishNode(node);
            }
            function parseArgumentOrArrayLiteralElement() {
                return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() :
                    token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) :
                        parseAssignmentExpressionOrHigher();
            }
            function parseArgumentExpression() {
                return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
            }
            function parseArrayLiteralExpression() {
                var node = createNode(185 /* ArrayLiteralExpression */);
                parseExpected(21 /* OpenBracketToken */);
                if (scanner.hasPrecedingLineBreak()) {
                    node.multiLine = true;
                }
                node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
                parseExpected(22 /* CloseBracketToken */);
                return finishNode(node);
            }
            function parseObjectLiteralElement() {
                var node = createNodeWithJSDoc(0 /* Unknown */);
                if (parseOptionalToken(24 /* DotDotDotToken */)) {
                    node.kind = 275 /* SpreadAssignment */;
                    node.expression = parseAssignmentExpressionOrHigher();
                    return finishNode(node);
                }
                node.decorators = parseDecorators();
                node.modifiers = parseModifiers();
                if (parseContextualModifier(125 /* GetKeyword */)) {
                    return parseAccessorDeclaration(node, 156 /* GetAccessor */);
                }
                if (parseContextualModifier(136 /* SetKeyword */)) {
                    return parseAccessorDeclaration(node, 157 /* SetAccessor */);
                }
                var asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
                var tokenIsIdentifier = isIdentifier();
                node.name = parsePropertyName();
                // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
                node.questionToken = parseOptionalToken(55 /* QuestionToken */);
                node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */);
                if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
                    return parseMethodDeclaration(node, asteriskToken);
                }
                // check if it is short-hand property assignment or normal property assignment
                // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
                // CoverInitializedName[Yield] :
                //     IdentifierReference[?Yield] Initializer[In, ?Yield]
                // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
                var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */);
                if (isShorthandPropertyAssignment) {
                    node.kind = 274 /* ShorthandPropertyAssignment */;
                    var equalsToken = parseOptionalToken(58 /* EqualsToken */);
                    if (equalsToken) {
                        node.equalsToken = equalsToken;
                        node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
                    }
                }
                else {
                    node.kind = 273 /* PropertyAssignment */;
                    parseExpected(56 /* ColonToken */);
                    node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
                }
                return finishNode(node);
            }
            function parseObjectLiteralExpression() {
                var node = createNode(186 /* ObjectLiteralExpression */);
                parseExpected(17 /* OpenBraceToken */);
                if (scanner.hasPrecedingLineBreak()) {
                    node.multiLine = true;
                }
                node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
                parseExpected(18 /* CloseBraceToken */);
                return finishNode(node);
            }
            function parseFunctionExpression() {
                // GeneratorExpression:
                //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
                //
                // FunctionExpression:
                //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
                var saveDecoratorContext = inDecoratorContext();
                if (saveDecoratorContext) {
                    setDecoratorContext(/*val*/ false);
                }
                var node = createNodeWithJSDoc(194 /* FunctionExpression */);
                node.modifiers = parseModifiers();
                parseExpected(89 /* FunctionKeyword */);
                node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
                var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
                var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
                node.name =
                    isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
                        isGenerator ? doInYieldContext(parseOptionalIdentifier) :
                            isAsync ? doInAwaitContext(parseOptionalIdentifier) :
                                parseOptionalIdentifier();
                fillSignature(56 /* ColonToken */, isGenerator | isAsync, node);
                node.body = parseFunctionBlock(isGenerator | isAsync);
                if (saveDecoratorContext) {
                    setDecoratorContext(/*val*/ true);
                }
                return finishNode(node);
            }
            function parseOptionalIdentifier() {
                return isIdentifier() ? parseIdentifier() : undefined;
            }
            function parseNewExpressionOrNewDotTarget() {
                var fullStart = scanner.getStartPos();
                parseExpected(94 /* NewKeyword */);
                if (parseOptional(23 /* DotToken */)) {
                    var node_2 = createNode(212 /* MetaProperty */, fullStart);
                    node_2.keywordToken = 94 /* NewKeyword */;
                    node_2.name = parseIdentifierName();
                    return finishNode(node_2);
                }
                var expression = parsePrimaryExpression();
                var typeArguments;
                while (true) {
                    expression = parseMemberExpressionRest(expression);
                    typeArguments = tryParse(parseTypeArgumentsInExpression);
                    if (isTemplateStartOfTaggedTemplate()) {
                        ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
                        expression = parseTaggedTemplateRest(expression, typeArguments);
                        typeArguments = undefined;
                    }
                    break;
                }
                var node = createNode(190 /* NewExpression */, fullStart);
                node.expression = expression;
                node.typeArguments = typeArguments;
                if (node.typeArguments || token() === 19 /* OpenParenToken */) {
                    node.arguments = parseArgumentList();
                }
                return finishNode(node);
            }
            // STATEMENTS
            function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
                var node = createNode(216 /* Block */);
                if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
                    if (scanner.hasPrecedingLineBreak()) {
                        node.multiLine = true;
                    }
                    node.statements = parseList(1 /* BlockStatements */, parseStatement);
                    parseExpected(18 /* CloseBraceToken */);
                }
                else {
                    node.statements = createMissingList();
                }
                return finishNode(node);
            }
            function parseFunctionBlock(flags, diagnosticMessage) {
                var savedYieldContext = inYieldContext();
                setYieldContext(!!(flags & 1 /* Yield */));
                var savedAwaitContext = inAwaitContext();
                setAwaitContext(!!(flags & 2 /* Await */));
                // We may be in a [Decorator] context when parsing a function expression or
                // arrow function. The body of the function is not in [Decorator] context.
                var saveDecoratorContext = inDecoratorContext();
                if (saveDecoratorContext) {
                    setDecoratorContext(/*val*/ false);
                }
                var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
                if (saveDecoratorContext) {
                    setDecoratorContext(/*val*/ true);
                }
                setYieldContext(savedYieldContext);
                setAwaitContext(savedAwaitContext);
                return block;
            }
            function parseEmptyStatement() {
                var node = createNode(218 /* EmptyStatement */);
                parseExpected(25 /* SemicolonToken */);
                return finishNode(node);
            }
            function parseIfStatement() {
                var node = createNode(220 /* IfStatement */);
                parseExpected(90 /* IfKeyword */);
                parseExpected(19 /* OpenParenToken */);
                node.expression = allowInAnd(parseExpression);
                parseExpected(20 /* CloseParenToken */);
                node.thenStatement = parseStatement();
                node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined;
                return finishNode(node);
            }
            function parseDoStatement() {
                var node = createNode(221 /* DoStatement */);
                parseExpected(81 /* DoKeyword */);
                node.statement = parseStatement();
                parseExpected(106 /* WhileKeyword */);
                parseExpected(19 /* OpenParenToken */);
                node.expression = allowInAnd(parseExpression);
                parseExpected(20 /* CloseParenToken */);
                // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
                // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
                // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
                //  do;while(0)x will have a semicolon inserted before x.
                parseOptional(25 /* SemicolonToken */);
                return finishNode(node);
            }
            function parseWhileStatement() {
                var node = createNode(222 /* WhileStatement */);
                parseExpected(106 /* WhileKeyword */);
                parseExpected(19 /* OpenParenToken */);
                node.expression = allowInAnd(parseExpression);
                parseExpected(20 /* CloseParenToken */);
                node.statement = parseStatement();
                return finishNode(node);
            }
            function parseForOrForInOrForOfStatement() {
                var pos = getNodePos();
                parseExpected(88 /* ForKeyword */);
                var awaitToken = parseOptionalToken(121 /* AwaitKeyword */);
                parseExpected(19 /* OpenParenToken */);
                var initializer;
                if (token() !== 25 /* SemicolonToken */) {
                    if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) {
                        initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
                    }
                    else {
                        initializer = disallowInAnd(parseExpression);
                    }
                }
                var forOrForInOrForOfStatement;
                if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) {
                    var forOfStatement = createNode(225 /* ForOfStatement */, pos);
                    forOfStatement.awaitModifier = awaitToken;
                    forOfStatement.initializer = initializer;
                    forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
                    parseExpected(20 /* CloseParenToken */);
                    forOrForInOrForOfStatement = forOfStatement;
                }
                else if (parseOptional(92 /* InKeyword */)) {
                    var forInStatement = createNode(224 /* ForInStatement */, pos);
                    forInStatement.initializer = initializer;
                    forInStatement.expression = allowInAnd(parseExpression);
                    parseExpected(20 /* CloseParenToken */);
                    forOrForInOrForOfStatement = forInStatement;
                }
                else {
                    var forStatement = createNode(223 /* ForStatement */, pos);
                    forStatement.initializer = initializer;
                    parseExpected(25 /* SemicolonToken */);
                    if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) {
                        forStatement.condition = allowInAnd(parseExpression);
                    }
                    parseExpected(25 /* SemicolonToken */);
                    if (token() !== 20 /* CloseParenToken */) {
                        forStatement.incrementor = allowInAnd(parseExpression);
                    }
                    parseExpected(20 /* CloseParenToken */);
                    forOrForInOrForOfStatement = forStatement;
                }
                forOrForInOrForOfStatement.statement = parseStatement();
                return finishNode(forOrForInOrForOfStatement);
            }
            function parseBreakOrContinueStatement(kind) {
                var node = createNode(kind);
                parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */);
                if (!canParseSemicolon()) {
                    node.label = parseIdentifier();
                }
                parseSemicolon();
                return finishNode(node);
            }
            function parseReturnStatement() {
                var node = createNode(228 /* ReturnStatement */);
                parseExpected(96 /* ReturnKeyword */);
                if (!canParseSemicolon()) {
                    node.expression = allowInAnd(parseExpression);
                }
                parseSemicolon();
                return finishNode(node);
            }
            function parseWithStatement() {
                var node = createNode(229 /* WithStatement */);
                parseExpected(107 /* WithKeyword */);
                parseExpected(19 /* OpenParenToken */);
                node.expression = allowInAnd(parseExpression);
                parseExpected(20 /* CloseParenToken */);
                node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement);
                return finishNode(node);
            }
            function parseCaseClause() {
                var node = createNode(269 /* CaseClause */);
                parseExpected(73 /* CaseKeyword */);
                node.expression = allowInAnd(parseExpression);
                parseExpected(56 /* ColonToken */);
                node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
                return finishNode(node);
            }
            function parseDefaultClause() {
                var node = createNode(270 /* DefaultClause */);
                parseExpected(79 /* DefaultKeyword */);
                parseExpected(56 /* ColonToken */);
                node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
                return finishNode(node);
            }
            function parseCaseOrDefaultClause() {
                return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
            }
            function parseSwitchStatement() {
                var node = createNode(230 /* SwitchStatement */);
                parseExpected(98 /* SwitchKeyword */);
                parseExpected(19 /* OpenParenToken */);
                node.expression = allowInAnd(parseExpression);
                parseExpected(20 /* CloseParenToken */);
                var caseBlock = createNode(244 /* CaseBlock */);
                parseExpected(17 /* OpenBraceToken */);
                caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
                parseExpected(18 /* CloseBraceToken */);
                node.caseBlock = finishNode(caseBlock);
                return finishNode(node);
            }
            function parseThrowStatement() {
                // ThrowStatement[Yield] :
                //      throw [no LineTerminator here]Expression[In, ?Yield];
                // Because of automatic semicolon insertion, we need to report error if this
                // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
                // directly as that might consume an expression on the following line.
                // We just return 'undefined' in that case.  The actual error will be reported in the
                // grammar walker.
                var node = createNode(232 /* ThrowStatement */);
                parseExpected(100 /* ThrowKeyword */);
                node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
                parseSemicolon();
                return finishNode(node);
            }
            // TODO: Review for error recovery
            function parseTryStatement() {
                var node = createNode(233 /* TryStatement */);
                parseExpected(102 /* TryKeyword */);
                node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
                node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined;
                // If we don't have a catch clause, then we must have a finally clause.  Try to parse
                // one out no matter what.
                if (!node.catchClause || token() === 87 /* FinallyKeyword */) {
                    parseExpected(87 /* FinallyKeyword */);
                    node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
                }
                return finishNode(node);
            }
            function parseCatchClause() {
                var result = createNode(272 /* CatchClause */);
                parseExpected(74 /* CatchKeyword */);
                if (parseOptional(19 /* OpenParenToken */)) {
                    result.variableDeclaration = parseVariableDeclaration();
                    parseExpected(20 /* CloseParenToken */);
                }
                else {
                    // Keep shape of node to avoid degrading performance.
                    result.variableDeclaration = undefined;
                }
                result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
                return finishNode(result);
            }
            function parseDebuggerStatement() {
                var node = createNode(234 /* DebuggerStatement */);
                parseExpected(78 /* DebuggerKeyword */);
                parseSemicolon();
                return finishNode(node);
            }
            function parseExpressionOrLabeledStatement() {
                // Avoiding having to do the lookahead for a labeled statement by just trying to parse
                // out an expression, seeing if it is identifier and then seeing if it is followed by
                // a colon.
                var node = createNodeWithJSDoc(0 /* Unknown */);
                var expression = allowInAnd(parseExpression);
                if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) {
                    node.kind = 231 /* LabeledStatement */;
                    node.label = expression;
                    node.statement = parseStatement();
                }
                else {
                    node.kind = 219 /* ExpressionStatement */;
                    node.expression = expression;
                    parseSemicolon();
                }
                return finishNode(node);
            }
            function nextTokenIsIdentifierOrKeywordOnSameLine() {
                nextToken();
                return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
            }
            function nextTokenIsClassKeywordOnSameLine() {
                nextToken();
                return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
            }
            function nextTokenIsFunctionKeywordOnSameLine() {
                nextToken();
                return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
            }
            function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
                nextToken();
                return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
            }
            function isDeclaration() {
                while (true) {
                    switch (token()) {
                        case 104 /* VarKeyword */:
                        case 110 /* LetKeyword */:
                        case 76 /* ConstKeyword */:
                        case 89 /* FunctionKeyword */:
                        case 75 /* ClassKeyword */:
                        case 83 /* EnumKeyword */:
                            return true;
                        // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
                        // however, an identifier cannot be followed by another identifier on the same line. This is what we
                        // count on to parse out the respective declarations. For instance, we exploit this to say that
                        //
                        //    namespace n
                        //
                        // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
                        //
                        //    namespace
                        //    n
                        //
                        // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
                        // We need to look one token ahead to see if it permissible to try parsing a declaration.
                        //
                        // *Note*: 'interface' is actually a strict mode reserved word. So while
                        //
                        //   "use strict"
                        //   interface
                        //   I {}
                        //
                        // could be legal, it would add complexity for very little gain.
                        case 109 /* InterfaceKeyword */:
                        case 139 /* TypeKeyword */:
                            return nextTokenIsIdentifierOnSameLine();
                        case 129 /* ModuleKeyword */:
                        case 130 /* NamespaceKeyword */:
                            return nextTokenIsIdentifierOrStringLiteralOnSameLine();
                        case 117 /* AbstractKeyword */:
                        case 120 /* AsyncKeyword */:
                        case 124 /* DeclareKeyword */:
                        case 112 /* PrivateKeyword */:
                        case 113 /* ProtectedKeyword */:
                        case 114 /* PublicKeyword */:
                        case 132 /* ReadonlyKeyword */:
                            nextToken();
                            // ASI takes effect for this modifier.
                            if (scanner.hasPrecedingLineBreak()) {
                                return false;
                            }
                            continue;
                        case 144 /* GlobalKeyword */:
                            nextToken();
                            return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */;
                        case 91 /* ImportKeyword */:
                            nextToken();
                            return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ ||
                                token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
                        case 84 /* ExportKeyword */:
                            nextToken();
                            if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ ||
                                token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ ||
                                token() === 118 /* AsKeyword */) {
                                return true;
                            }
                            continue;
                        case 115 /* StaticKeyword */:
                            nextToken();
                            continue;
                        default:
                            return false;
                    }
                }
            }
            function isStartOfDeclaration() {
                return lookAhead(isDeclaration);
            }
            function isStartOfStatement() {
                switch (token()) {
                    case 57 /* AtToken */:
                    case 25 /* SemicolonToken */:
                    case 17 /* OpenBraceToken */:
                    case 104 /* VarKeyword */:
                    case 110 /* LetKeyword */:
                    case 89 /* FunctionKeyword */:
                    case 75 /* ClassKeyword */:
                    case 83 /* EnumKeyword */:
                    case 90 /* IfKeyword */:
                    case 81 /* DoKeyword */:
                    case 106 /* WhileKeyword */:
                    case 88 /* ForKeyword */:
                    case 77 /* ContinueKeyword */:
                    case 72 /* BreakKeyword */:
                    case 96 /* ReturnKeyword */:
                    case 107 /* WithKeyword */:
                    case 98 /* SwitchKeyword */:
                    case 100 /* ThrowKeyword */:
                    case 102 /* TryKeyword */:
                    case 78 /* DebuggerKeyword */:
                    // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
                    // however, we say they are here so that we may gracefully parse them and error later.
                    case 74 /* CatchKeyword */:
                    case 87 /* FinallyKeyword */:
                        return true;
                    case 91 /* ImportKeyword */:
                        return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
                    case 76 /* ConstKeyword */:
                    case 84 /* ExportKeyword */:
                        return isStartOfDeclaration();
                    case 120 /* AsyncKeyword */:
                    case 124 /* DeclareKeyword */:
                    case 109 /* InterfaceKeyword */:
                    case 129 /* ModuleKeyword */:
                    case 130 /* NamespaceKeyword */:
                    case 139 /* TypeKeyword */:
                    case 144 /* GlobalKeyword */:
                        // When these don't start a declaration, they're an identifier in an expression statement
                        return true;
                    case 114 /* PublicKeyword */:
                    case 112 /* PrivateKeyword */:
                    case 113 /* ProtectedKeyword */:
                    case 115 /* StaticKeyword */:
                    case 132 /* ReadonlyKeyword */:
                        // When these don't start a declaration, they may be the start of a class member if an identifier
                        // immediately follows. Otherwise they're an identifier in an expression statement.
                        return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
                    default:
                        return isStartOfExpression();
                }
            }
            function nextTokenIsIdentifierOrStartOfDestructuring() {
                nextToken();
                return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */;
            }
            function isLetDeclaration() {
                // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
                // or [.
                return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
            }
            function parseStatement() {
                switch (token()) {
                    case 25 /* SemicolonToken */:
                        return parseEmptyStatement();
                    case 17 /* OpenBraceToken */:
                        return parseBlock(/*ignoreMissingOpenBrace*/ false);
                    case 104 /* VarKeyword */:
                        return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */));
                    case 110 /* LetKeyword */:
                        if (isLetDeclaration()) {
                            return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */));
                        }
                        break;
                    case 89 /* FunctionKeyword */:
                        return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */));
                    case 75 /* ClassKeyword */:
                        return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */));
                    case 90 /* IfKeyword */:
                        return parseIfStatement();
                    case 81 /* DoKeyword */:
                        return parseDoStatement();
                    case 106 /* WhileKeyword */:
                        return parseWhileStatement();
                    case 88 /* ForKeyword */:
                        return parseForOrForInOrForOfStatement();
                    case 77 /* ContinueKeyword */:
                        return parseBreakOrContinueStatement(226 /* ContinueStatement */);
                    case 72 /* BreakKeyword */:
                        return parseBreakOrContinueStatement(227 /* BreakStatement */);
                    case 96 /* ReturnKeyword */:
                        return parseReturnStatement();
                    case 107 /* WithKeyword */:
                        return parseWithStatement();
                    case 98 /* SwitchKeyword */:
                        return parseSwitchStatement();
                    case 100 /* ThrowKeyword */:
                        return parseThrowStatement();
                    case 102 /* TryKeyword */:
                    // Include 'catch' and 'finally' for error recovery.
                    case 74 /* CatchKeyword */:
                    case 87 /* FinallyKeyword */:
                        return parseTryStatement();
                    case 78 /* DebuggerKeyword */:
                        return parseDebuggerStatement();
                    case 57 /* AtToken */:
                        return parseDeclaration();
                    case 120 /* AsyncKeyword */:
                    case 109 /* InterfaceKeyword */:
                    case 139 /* TypeKeyword */:
                    case 129 /* ModuleKeyword */:
                    case 130 /* NamespaceKeyword */:
                    case 124 /* DeclareKeyword */:
                    case 76 /* ConstKeyword */:
                    case 83 /* EnumKeyword */:
                    case 84 /* ExportKeyword */:
                    case 91 /* ImportKeyword */:
                    case 112 /* PrivateKeyword */:
                    case 113 /* ProtectedKeyword */:
                    case 114 /* PublicKeyword */:
                    case 117 /* AbstractKeyword */:
                    case 115 /* StaticKeyword */:
                    case 132 /* ReadonlyKeyword */:
                    case 144 /* GlobalKeyword */:
                        if (isStartOfDeclaration()) {
                            return parseDeclaration();
                        }
                        break;
                }
                return parseExpressionOrLabeledStatement();
            }
            function isDeclareModifier(modifier) {
                return modifier.kind === 124 /* DeclareKeyword */;
            }
            function parseDeclaration() {
                var node = createNodeWithJSDoc(0 /* Unknown */);
                node.decorators = parseDecorators();
                node.modifiers = parseModifiers();
                if (ts.some(node.modifiers, isDeclareModifier)) {
                    for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
                        var m = _a[_i];
                        m.flags |= 4194304 /* Ambient */;
                    }
                    return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); });
                }
                else {
                    return parseDeclarationWorker(node);
                }
            }
            function parseDeclarationWorker(node) {
                switch (token()) {
                    case 104 /* VarKeyword */:
                    case 110 /* LetKeyword */:
                    case 76 /* ConstKeyword */:
                        return parseVariableStatement(node);
                    case 89 /* FunctionKeyword */:
                        return parseFunctionDeclaration(node);
                    case 75 /* ClassKeyword */:
                        return parseClassDeclaration(node);
                    case 109 /* InterfaceKeyword */:
                        return parseInterfaceDeclaration(node);
                    case 139 /* TypeKeyword */:
                        return parseTypeAliasDeclaration(node);
                    case 83 /* EnumKeyword */:
                        return parseEnumDeclaration(node);
                    case 144 /* GlobalKeyword */:
                    case 129 /* ModuleKeyword */:
                    case 130 /* NamespaceKeyword */:
                        return parseModuleDeclaration(node);
                    case 91 /* ImportKeyword */:
                        return parseImportDeclarationOrImportEqualsDeclaration(node);
                    case 84 /* ExportKeyword */:
                        nextToken();
                        switch (token()) {
                            case 79 /* DefaultKeyword */:
                            case 58 /* EqualsToken */:
                                return parseExportAssignment(node);
                            case 118 /* AsKeyword */:
                                return parseNamespaceExportDeclaration(node);
                            default:
                                return parseExportDeclaration(node);
                        }
                    default:
                        if (node.decorators || node.modifiers) {
                            // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
                            // would follow. For recovery and error reporting purposes, return an incomplete declaration.
                            var missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
                            missing.pos = node.pos;
                            missing.decorators = node.decorators;
                            missing.modifiers = node.modifiers;
                            return finishNode(missing);
                        }
                        return undefined; // TODO: GH#18217
                }
            }
            function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
                nextToken();
                return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */);
            }
            function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
                if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) {
                    parseSemicolon();
                    return;
                }
                return parseFunctionBlock(flags, diagnosticMessage);
            }
            // DECLARATIONS
            function parseArrayBindingElement() {
                if (token() === 26 /* CommaToken */) {
                    return createNode(208 /* OmittedExpression */);
                }
                var node = createNode(184 /* BindingElement */);
                node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
                node.name = parseIdentifierOrPattern();
                node.initializer = parseInitializer();
                return finishNode(node);
            }
            function parseObjectBindingElement() {
                var node = createNode(184 /* BindingElement */);
                node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */);
                var tokenIsIdentifier = isIdentifier();
                var propertyName = parsePropertyName();
                if (tokenIsIdentifier && token() !== 56 /* ColonToken */) {
                    node.name = propertyName;
                }
                else {
                    parseExpected(56 /* ColonToken */);
                    node.propertyName = propertyName;
                    node.name = parseIdentifierOrPattern();
                }
                node.initializer = parseInitializer();
                return finishNode(node);
            }
            function parseObjectBindingPattern() {
                var node = createNode(182 /* ObjectBindingPattern */);
                parseExpected(17 /* OpenBraceToken */);
                node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
                parseExpected(18 /* CloseBraceToken */);
                return finishNode(node);
            }
            function parseArrayBindingPattern() {
                var node = createNode(183 /* ArrayBindingPattern */);
                parseExpected(21 /* OpenBracketToken */);
                node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
                parseExpected(22 /* CloseBracketToken */);
                return finishNode(node);
            }
            function isIdentifierOrPattern() {
                return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier();
            }
            function parseIdentifierOrPattern() {
                if (token() === 21 /* OpenBracketToken */) {
                    return parseArrayBindingPattern();
                }
                if (token() === 17 /* OpenBraceToken */) {
                    return parseObjectBindingPattern();
                }
                return parseIdentifier();
            }
            function parseVariableDeclarationAllowExclamation() {
                return parseVariableDeclaration(/*allowExclamation*/ true);
            }
            function parseVariableDeclaration(allowExclamation) {
                var node = createNode(235 /* VariableDeclaration */);
                node.name = parseIdentifierOrPattern();
                if (allowExclamation && node.name.kind === 71 /* Identifier */ &&
                    token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
                    node.exclamationToken = parseTokenNode();
                }
                node.type = parseTypeAnnotation();
                if (!isInOrOfKeyword(token())) {
                    node.initializer = parseInitializer();
                }
                return finishNode(node);
            }
            function parseVariableDeclarationList(inForStatementInitializer) {
                var node = createNode(236 /* VariableDeclarationList */);
                switch (token()) {
                    case 104 /* VarKeyword */:
                        break;
                    case 110 /* LetKeyword */:
                        node.flags |= 1 /* Let */;
                        break;
                    case 76 /* ConstKeyword */:
                        node.flags |= 2 /* Const */;
                        break;
                    default:
                        ts.Debug.fail();
                }
                nextToken();
                // The user may have written the following:
                //
                //    for (let of X) { }
                //
                // In this case, we want to parse an empty declaration list, and then parse 'of'
                // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
                // So we need to look ahead to determine if 'of' should be treated as a keyword in
                // this context.
                // The checker will then give an error that there is an empty declaration list.
                if (token() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
                    node.declarations = createMissingList();
                }
                else {
                    var savedDisallowIn = inDisallowInContext();
                    setDisallowInContext(inForStatementInitializer);
                    node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
                    setDisallowInContext(savedDisallowIn);
                }
                return finishNode(node);
            }
            function canFollowContextualOfKeyword() {
                return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */;
            }
            function parseVariableStatement(node) {
                node.kind = 217 /* VariableStatement */;
                node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
                parseSemicolon();
                return finishNode(node);
            }
            function parseFunctionDeclaration(node) {
                node.kind = 237 /* FunctionDeclaration */;
                parseExpected(89 /* FunctionKeyword */);
                node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
                node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier();
                var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
                var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
                fillSignature(56 /* ColonToken */, isGenerator | isAsync, node);
                node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
                return finishNode(node);
            }
            function parseConstructorDeclaration(node) {
                node.kind = 155 /* Constructor */;
                parseExpected(123 /* ConstructorKeyword */);
                fillSignature(56 /* ColonToken */, 0 /* None */, node);
                node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
                return finishNode(node);
            }
            function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
                node.kind = 154 /* MethodDeclaration */;
                node.asteriskToken = asteriskToken;
                var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
                var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */;
                fillSignature(56 /* ColonToken */, isGenerator | isAsync, node);
                node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
                return finishNode(node);
            }
            function parsePropertyDeclaration(node) {
                node.kind = 152 /* PropertyDeclaration */;
                if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
                    node.exclamationToken = parseTokenNode();
                }
                node.type = parseTypeAnnotation();
                // For instance properties specifically, since they are evaluated inside the constructor,
                // we do *not * want to parse yield expressions, so we specifically turn the yield context
                // off. The grammar would look something like this:
                //
                //    MemberVariableDeclaration[Yield]:
                //        AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In];
                //        AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield];
                //
                // The checker may still error in the static case to explicitly disallow the yield expression.
                node.initializer = ts.hasModifier(node, 32 /* Static */)
                    ? allowInAnd(parseInitializer)
                    : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer);
                parseSemicolon();
                return finishNode(node);
            }
            function parsePropertyOrMethodDeclaration(node) {
                var asteriskToken = parseOptionalToken(39 /* AsteriskToken */);
                node.name = parsePropertyName();
                // Note: this is not legal as per the grammar.  But we allow it in the parser and
                // report an error in the grammar checker.
                node.questionToken = parseOptionalToken(55 /* QuestionToken */);
                if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) {
                    return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
                }
                return parsePropertyDeclaration(node);
            }
            function parseAccessorDeclaration(node, kind) {
                node.kind = kind;
                node.name = parsePropertyName();
                fillSignature(56 /* ColonToken */, 0 /* None */, node);
                node.body = parseFunctionBlockOrSemicolon(0 /* None */);
                return finishNode(node);
            }
            function isClassMemberStart() {
                var idToken;
                if (token() === 57 /* AtToken */) {
                    return true;
                }
                // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
                while (ts.isModifierKind(token())) {
                    idToken = token();
                    // If the idToken is a class modifier (protected, private, public, and static), it is
                    // certain that we are starting to parse class member. This allows better error recovery
                    // Example:
                    //      public foo() ...     // true
                    //      public @dec blah ... // true; we will then report an error later
                    //      export public ...    // true; we will then report an error later
                    if (ts.isClassMemberModifier(idToken)) {
                        return true;
                    }
                    nextToken();
                }
                if (token() === 39 /* AsteriskToken */) {
                    return true;
                }
                // Try to get the first property-like token following all modifiers.
                // This can either be an identifier or the 'get' or 'set' keywords.
                if (isLiteralPropertyName()) {
                    idToken = token();
                    nextToken();
                }
                // Index signatures and computed properties are class members; we can parse.
                if (token() === 21 /* OpenBracketToken */) {
                    return true;
                }
                // If we were able to get any potential identifier...
                if (idToken !== undefined) {
                    // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
                    if (!ts.isKeyword(idToken) || idToken === 136 /* SetKeyword */ || idToken === 125 /* GetKeyword */) {
                        return true;
                    }
                    // If it *is* a keyword, but not an accessor, check a little farther along
                    // to see if it should actually be parsed as a class member.
                    switch (token()) {
                        case 19 /* OpenParenToken */: // Method declaration
                        case 27 /* LessThanToken */: // Generic Method declaration
                        case 51 /* ExclamationToken */: // Non-null assertion on property name
                        case 56 /* ColonToken */: // Type Annotation for declaration
                        case 58 /* EqualsToken */: // Initializer for declaration
                        case 55 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
                            return true;
                        default:
                            // Covers
                            //  - Semicolons     (declaration termination)
                            //  - Closing braces (end-of-class, must be declaration)
                            //  - End-of-files   (not valid, but permitted so that it gets caught later on)
                            //  - Line-breaks    (enabling *automatic semicolon insertion*)
                            return canParseSemicolon();
                    }
                }
                return false;
            }
            function parseDecorators() {
                var list;
                var listPos = getNodePos();
                while (true) {
                    var decoratorStart = getNodePos();
                    if (!parseOptional(57 /* AtToken */)) {
                        break;
                    }
                    var decorator = createNode(150 /* Decorator */, decoratorStart);
                    decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
                    finishNode(decorator);
                    (list || (list = [])).push(decorator);
                }
                return list && createNodeArray(list, listPos);
            }
            /*
             * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
             * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
             * and turns it into a standalone declaration), then it is better to parse it and report an error later.
             *
             * In such situations, 'permitInvalidConstAsModifier' should be set to true.
             */
            function parseModifiers(permitInvalidConstAsModifier) {
                var list;
                var listPos = getNodePos();
                while (true) {
                    var modifierStart = scanner.getStartPos();
                    var modifierKind = token();
                    if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) {
                        // We need to ensure that any subsequent modifiers appear on the same line
                        // so that when 'const' is a standalone declaration, we don't issue an error.
                        if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
                            break;
                        }
                    }
                    else {
                        if (!parseAnyContextualModifier()) {
                            break;
                        }
                    }
                    var modifier = finishNode(createNode(modifierKind, modifierStart));
                    (list || (list = [])).push(modifier);
                }
                return list && createNodeArray(list, listPos);
            }
            function parseModifiersForArrowFunction() {
                var modifiers;
                if (token() === 120 /* AsyncKeyword */) {
                    var modifierStart = scanner.getStartPos();
                    var modifierKind = token();
                    nextToken();
                    var modifier = finishNode(createNode(modifierKind, modifierStart));
                    modifiers = createNodeArray([modifier], modifierStart);
                }
                return modifiers;
            }
            function parseClassElement() {
                if (token() === 25 /* SemicolonToken */) {
                    var result = createNode(215 /* SemicolonClassElement */);
                    nextToken();
                    return finishNode(result);
                }
                var node = createNodeWithJSDoc(0 /* Unknown */);
                node.decorators = parseDecorators();
                node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
                if (parseContextualModifier(125 /* GetKeyword */)) {
                    return parseAccessorDeclaration(node, 156 /* GetAccessor */);
                }
                if (parseContextualModifier(136 /* SetKeyword */)) {
                    return parseAccessorDeclaration(node, 157 /* SetAccessor */);
                }
                if (token() === 123 /* ConstructorKeyword */) {
                    return parseConstructorDeclaration(node);
                }
                if (isIndexSignature()) {
                    return parseIndexSignatureDeclaration(node);
                }
                // It is very important that we check this *after* checking indexers because
                // the [ token can start an index signature or a computed property name
                if (ts.tokenIsIdentifierOrKeyword(token()) ||
                    token() === 9 /* StringLiteral */ ||
                    token() === 8 /* NumericLiteral */ ||
                    token() === 39 /* AsteriskToken */ ||
                    token() === 21 /* OpenBracketToken */) {
                    return parsePropertyOrMethodDeclaration(node);
                }
                if (node.decorators || node.modifiers) {
                    // treat this as a property declaration with a missing name.
                    node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
                    return parsePropertyDeclaration(node);
                }
                // 'isClassMemberStart' should have hinted not to attempt parsing.
                return ts.Debug.fail("Should not have attempted to parse class member declaration.");
            }
            function parseClassExpression() {
                return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */);
            }
            function parseClassDeclaration(node) {
                return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */);
            }
            function parseClassDeclarationOrExpression(node, kind) {
                node.kind = kind;
                parseExpected(75 /* ClassKeyword */);
                node.name = parseNameOfClassDeclarationOrExpression();
                node.typeParameters = parseTypeParameters();
                node.heritageClauses = parseHeritageClauses();
                if (parseExpected(17 /* OpenBraceToken */)) {
                    // ClassTail[Yield,Await] : (Modified) See 14.5
                    //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
                    node.members = parseClassMembers();
                    parseExpected(18 /* CloseBraceToken */);
                }
                else {
                    node.members = createMissingList();
                }
                return finishNode(node);
            }
            function parseNameOfClassDeclarationOrExpression() {
                // implements is a future reserved word so
                // 'class implements' might mean either
                // - class expression with omitted name, 'implements' starts heritage clause
                // - class with name 'implements'
                // 'isImplementsClause' helps to disambiguate between these two cases
                return isIdentifier() && !isImplementsClause()
                    ? parseIdentifier()
                    : undefined;
            }
            function isImplementsClause() {
                return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
            }
            function parseHeritageClauses() {
                // ClassTail[Yield,Await] : (Modified) See 14.5
                //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
                if (isHeritageClause()) {
                    return parseList(22 /* HeritageClauses */, parseHeritageClause);
                }
                return undefined;
            }
            function parseHeritageClause() {
                var tok = token();
                ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this.
                var node = createNode(271 /* HeritageClause */);
                node.token = tok;
                nextToken();
                node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
                return finishNode(node);
            }
            function parseExpressionWithTypeArguments() {
                var node = createNode(209 /* ExpressionWithTypeArguments */);
                node.expression = parseLeftHandSideExpressionOrHigher();
                node.typeArguments = tryParseTypeArguments();
                return finishNode(node);
            }
            function tryParseTypeArguments() {
                return token() === 27 /* LessThanToken */
                    ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */)
                    : undefined;
            }
            function isHeritageClause() {
                return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */;
            }
            function parseClassMembers() {
                return parseList(5 /* ClassMembers */, parseClassElement);
            }
            function parseInterfaceDeclaration(node) {
                node.kind = 239 /* InterfaceDeclaration */;
                parseExpected(109 /* InterfaceKeyword */);
                node.name = parseIdentifier();
                node.typeParameters = parseTypeParameters();
                node.heritageClauses = parseHeritageClauses();
                node.members = parseObjectTypeMembers();
                return finishNode(node);
            }
            function parseTypeAliasDeclaration(node) {
                node.kind = 240 /* TypeAliasDeclaration */;
                parseExpected(139 /* TypeKeyword */);
                node.name = parseIdentifier();
                node.typeParameters = parseTypeParameters();
                parseExpected(58 /* EqualsToken */);
                node.type = parseType();
                parseSemicolon();
                return finishNode(node);
            }
            // In an ambient declaration, the grammar only allows integer literals as initializers.
            // In a non-ambient declaration, the grammar allows uninitialized members only in a
            // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
            // or any time an integer literal initializer is encountered.
            function parseEnumMember() {
                var node = createNodeWithJSDoc(276 /* EnumMember */);
                node.name = parsePropertyName();
                node.initializer = allowInAnd(parseInitializer);
                return finishNode(node);
            }
            function parseEnumDeclaration(node) {
                node.kind = 241 /* EnumDeclaration */;
                parseExpected(83 /* EnumKeyword */);
                node.name = parseIdentifier();
                if (parseExpected(17 /* OpenBraceToken */)) {
                    node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember);
                    parseExpected(18 /* CloseBraceToken */);
                }
                else {
                    node.members = createMissingList();
                }
                return finishNode(node);
            }
            function parseModuleBlock() {
                var node = createNode(243 /* ModuleBlock */);
                if (parseExpected(17 /* OpenBraceToken */)) {
                    node.statements = parseList(1 /* BlockStatements */, parseStatement);
                    parseExpected(18 /* CloseBraceToken */);
                }
                else {
                    node.statements = createMissingList();
                }
                return finishNode(node);
            }
            function parseModuleOrNamespaceDeclaration(node, flags) {
                node.kind = 242 /* ModuleDeclaration */;
                // If we are parsing a dotted namespace name, we want to
                // propagate the 'Namespace' flag across the names if set.
                var namespaceFlag = flags & 16 /* Namespace */;
                node.flags |= flags;
                node.name = parseIdentifier();
                node.body = parseOptional(23 /* DotToken */)
                    ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
                    : parseModuleBlock();
                return finishNode(node);
            }
            function parseAmbientExternalModuleDeclaration(node) {
                node.kind = 242 /* ModuleDeclaration */;
                if (token() === 144 /* GlobalKeyword */) {
                    // parse 'global' as name of global scope augmentation
                    node.name = parseIdentifier();
                    node.flags |= 512 /* GlobalAugmentation */;
                }
                else {
                    node.name = parseLiteralNode();
                    node.name.text = internIdentifier(node.name.text);
                }
                if (token() === 17 /* OpenBraceToken */) {
                    node.body = parseModuleBlock();
                }
                else {
                    parseSemicolon();
                }
                return finishNode(node);
            }
            function parseModuleDeclaration(node) {
                var flags = 0;
                if (token() === 144 /* GlobalKeyword */) {
                    // global augmentation
                    return parseAmbientExternalModuleDeclaration(node);
                }
                else if (parseOptional(130 /* NamespaceKeyword */)) {
                    flags |= 16 /* Namespace */;
                }
                else {
                    parseExpected(129 /* ModuleKeyword */);
                    if (token() === 9 /* StringLiteral */) {
                        return parseAmbientExternalModuleDeclaration(node);
                    }
                }
                return parseModuleOrNamespaceDeclaration(node, flags);
            }
            function isExternalModuleReference() {
                return token() === 133 /* RequireKeyword */ &&
                    lookAhead(nextTokenIsOpenParen);
            }
            function nextTokenIsOpenParen() {
                return nextToken() === 19 /* OpenParenToken */;
            }
            function nextTokenIsSlash() {
                return nextToken() === 41 /* SlashToken */;
            }
            function parseNamespaceExportDeclaration(node) {
                node.kind = 245 /* NamespaceExportDeclaration */;
                parseExpected(118 /* AsKeyword */);
                parseExpected(130 /* NamespaceKeyword */);
                node.name = parseIdentifier();
                parseSemicolon();
                return finishNode(node);
            }
            function parseImportDeclarationOrImportEqualsDeclaration(node) {
                parseExpected(91 /* ImportKeyword */);
                var afterImportPos = scanner.getStartPos();
                var identifier;
                if (isIdentifier()) {
                    identifier = parseIdentifier();
                    if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) {
                        return parseImportEqualsDeclaration(node, identifier);
                    }
                }
                // Import statement
                node.kind = 247 /* ImportDeclaration */;
                // ImportDeclaration:
                //  import ImportClause from ModuleSpecifier ;
                //  import ModuleSpecifier;
                if (identifier || // import id
                    token() === 39 /* AsteriskToken */ || // import *
                    token() === 17 /* OpenBraceToken */) { // import {
                    node.importClause = parseImportClause(identifier, afterImportPos);
                    parseExpected(143 /* FromKeyword */);
                }
                node.moduleSpecifier = parseModuleSpecifier();
                parseSemicolon();
                return finishNode(node);
            }
            function parseImportEqualsDeclaration(node, identifier) {
                node.kind = 246 /* ImportEqualsDeclaration */;
                node.name = identifier;
                parseExpected(58 /* EqualsToken */);
                node.moduleReference = parseModuleReference();
                parseSemicolon();
                return finishNode(node);
            }
            function parseImportClause(identifier, fullStart) {
                // ImportClause:
                //  ImportedDefaultBinding
                //  NameSpaceImport
                //  NamedImports
                //  ImportedDefaultBinding, NameSpaceImport
                //  ImportedDefaultBinding, NamedImports
                var importClause = createNode(248 /* ImportClause */, fullStart);
                if (identifier) {
                    // ImportedDefaultBinding:
                    //  ImportedBinding
                    importClause.name = identifier;
                }
                // If there was no default import or if there is comma token after default import
                // parse namespace or named imports
                if (!importClause.name ||
                    parseOptional(26 /* CommaToken */)) {
                    importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */);
                }
                return finishNode(importClause);
            }
            function parseModuleReference() {
                return isExternalModuleReference()
                    ? parseExternalModuleReference()
                    : parseEntityName(/*allowReservedWords*/ false);
            }
            function parseExternalModuleReference() {
                var node = createNode(257 /* ExternalModuleReference */);
                parseExpected(133 /* RequireKeyword */);
                parseExpected(19 /* OpenParenToken */);
                node.expression = parseModuleSpecifier();
                parseExpected(20 /* CloseParenToken */);
                return finishNode(node);
            }
            function parseModuleSpecifier() {
                if (token() === 9 /* StringLiteral */) {
                    var result = parseLiteralNode();
                    result.text = internIdentifier(result.text);
                    return result;
                }
                else {
                    // We allow arbitrary expressions here, even though the grammar only allows string
                    // literals.  We check to ensure that it is only a string literal later in the grammar
                    // check pass.
                    return parseExpression();
                }
            }
            function parseNamespaceImport() {
                // NameSpaceImport:
                //  * as ImportedBinding
                var namespaceImport = createNode(249 /* NamespaceImport */);
                parseExpected(39 /* AsteriskToken */);
                parseExpected(118 /* AsKeyword */);
                namespaceImport.name = parseIdentifier();
                return finishNode(namespaceImport);
            }
            function parseNamedImportsOrExports(kind) {
                var node = createNode(kind);
                // NamedImports:
                //  { }
                //  { ImportsList }
                //  { ImportsList, }
                // ImportsList:
                //  ImportSpecifier
                //  ImportsList, ImportSpecifier
                node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */);
                return finishNode(node);
            }
            function parseExportSpecifier() {
                return parseImportOrExportSpecifier(255 /* ExportSpecifier */);
            }
            function parseImportSpecifier() {
                return parseImportOrExportSpecifier(251 /* ImportSpecifier */);
            }
            function parseImportOrExportSpecifier(kind) {
                var node = createNode(kind);
                // ImportSpecifier:
                //   BindingIdentifier
                //   IdentifierName as BindingIdentifier
                // ExportSpecifier:
                //   IdentifierName
                //   IdentifierName as IdentifierName
                var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
                var checkIdentifierStart = scanner.getTokenPos();
                var checkIdentifierEnd = scanner.getTextPos();
                var identifierName = parseIdentifierName();
                if (token() === 118 /* AsKeyword */) {
                    node.propertyName = identifierName;
                    parseExpected(118 /* AsKeyword */);
                    checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
                    checkIdentifierStart = scanner.getTokenPos();
                    checkIdentifierEnd = scanner.getTextPos();
                    node.name = parseIdentifierName();
                }
                else {
                    node.name = identifierName;
                }
                if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
                    parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
                }
                return finishNode(node);
            }
            function parseExportDeclaration(node) {
                node.kind = 253 /* ExportDeclaration */;
                if (parseOptional(39 /* AsteriskToken */)) {
                    parseExpected(143 /* FromKeyword */);
                    node.moduleSpecifier = parseModuleSpecifier();
                }
                else {
                    node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */);
                    // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
                    // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
                    // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
                    if (token() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
                        parseExpected(143 /* FromKeyword */);
                        node.moduleSpecifier = parseModuleSpecifier();
                    }
                }
                parseSemicolon();
                return finishNode(node);
            }
            function parseExportAssignment(node) {
                node.kind = 252 /* ExportAssignment */;
                if (parseOptional(58 /* EqualsToken */)) {
                    node.isExportEquals = true;
                }
                else {
                    parseExpected(79 /* DefaultKeyword */);
                }
                node.expression = parseAssignmentExpressionOrHigher();
                parseSemicolon();
                return finishNode(node);
            }
            function setExternalModuleIndicator(sourceFile) {
                // Try to use the first top-level import/export when available, then
                // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
                sourceFile.externalModuleIndicator =
                    ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
                        getImportMetaIfNecessary(sourceFile);
            }
            function isAnExternalModuleIndicatorNode(node) {
                return ts.hasModifier(node, 1 /* Export */)
                    || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */
                    || node.kind === 247 /* ImportDeclaration */
                    || node.kind === 252 /* ExportAssignment */
                    || node.kind === 253 /* ExportDeclaration */
                    ? node
                    : undefined;
            }
            function getImportMetaIfNecessary(sourceFile) {
                return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ?
                    walkTreeForExternalModuleIndicators(sourceFile) :
                    undefined;
            }
            function walkTreeForExternalModuleIndicators(node) {
                return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
            }
            function isImportMeta(node) {
                return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta";
            }
            var ParsingContext;
            (function (ParsingContext) {
                ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
                ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
                ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
                ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
                ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
                ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
                ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
                ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
                ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
                ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
                ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
                ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
                ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
                ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
                ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
                ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
                ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
                ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
                ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
                ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
                ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
                ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
                ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
                ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
                ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
            })(ParsingContext || (ParsingContext = {}));
            var Tristate;
            (function (Tristate) {
                Tristate[Tristate["False"] = 0] = "False";
                Tristate[Tristate["True"] = 1] = "True";
                Tristate[Tristate["Unknown"] = 2] = "Unknown";
            })(Tristate || (Tristate = {}));
            var JSDocParser;
            (function (JSDocParser) {
                function parseJSDocTypeExpressionForTests(content, start, length) {
                    initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
                    sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
                    scanner.setText(content, start, length);
                    currentToken = scanner.scan();
                    var jsDocTypeExpression = parseJSDocTypeExpression();
                    var diagnostics = parseDiagnostics;
                    clearState();
                    return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
                }
                JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
                // Parses out a JSDoc type expression.
                function parseJSDocTypeExpression(mayOmitBraces) {
                    var result = createNode(281 /* JSDocTypeExpression */);
                    var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */);
                    result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
                    if (!mayOmitBraces || hasBrace) {
                        parseExpected(18 /* CloseBraceToken */);
                    }
                    fixupParentReferences(result);
                    return finishNode(result);
                }
                JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
                function parseIsolatedJSDocComment(content, start, length) {
                    initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
                    sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
                    var jsDoc = parseJSDocCommentWorker(start, length);
                    var diagnostics = parseDiagnostics;
                    clearState();
                    return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
                }
                JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
                function parseJSDocComment(parent, start, length) {
                    var _a;
                    var saveToken = currentToken;
                    var saveParseDiagnosticsLength = parseDiagnostics.length;
                    var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
                    var comment = parseJSDocCommentWorker(start, length);
                    if (comment) {
                        comment.parent = parent;
                    }
                    if (contextFlags & 65536 /* JavaScriptFile */) {
                        if (!sourceFile.jsDocDiagnostics) {
                            sourceFile.jsDocDiagnostics = [];
                        }
                        (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
                    }
                    currentToken = saveToken;
                    parseDiagnostics.length = saveParseDiagnosticsLength;
                    parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
                    return comment;
                }
                JSDocParser.parseJSDocComment = parseJSDocComment;
                var JSDocState;
                (function (JSDocState) {
                    JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
                    JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
                    JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
                })(JSDocState || (JSDocState = {}));
                var PropertyLikeParse;
                (function (PropertyLikeParse) {
                    PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
                    PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
                    PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
                })(PropertyLikeParse || (PropertyLikeParse = {}));
                function parseJSDocCommentWorker(start, length) {
                    if (start === void 0) {
                        start = 0;
                    }
                    var content = sourceText;
                    var end = length === undefined ? content.length : start + length;
                    length = end - start;
                    ts.Debug.assert(start >= 0);
                    ts.Debug.assert(start <= end);
                    ts.Debug.assert(end <= content.length);
                    // Check for /** (JSDoc opening part)
                    if (!isJSDocLikeText(content, start)) {
                        return undefined;
                    }
                    var tags;
                    var tagsPos;
                    var tagsEnd;
                    var comments = [];
                    // + 3 for leading /**, - 5 in total for /** */
                    return scanner.scanRange(start + 3, length - 5, function () {
                        // Initially we can parse out a tag.  We also have seen a starting asterisk.
                        // This is so that /** * @type */ doesn't parse.
                        var state = 1 /* SawAsterisk */;
                        var margin;
                        // + 4 for leading '/** '
                        var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
                        function pushComment(text) {
                            if (!margin) {
                                margin = indent;
                            }
                            comments.push(text);
                            indent += text.length;
                        }
                        nextJSDocToken();
                        while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
                            ;
                        if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
                            state = 0 /* BeginningOfLine */;
                            indent = 0;
                        }
                        loop: while (true) {
                            switch (token()) {
                                case 57 /* AtToken */:
                                    if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
                                        removeTrailingWhitespace(comments);
                                        addTag(parseTag(indent));
                                        // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
                                        // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
                                        // for malformed examples like `/** @param {string} x @returns {number} the length */`
                                        state = 0 /* BeginningOfLine */;
                                        margin = undefined;
                                        indent++;
                                    }
                                    else {
                                        pushComment(scanner.getTokenText());
                                    }
                                    break;
                                case 4 /* NewLineTrivia */:
                                    comments.push(scanner.getTokenText());
                                    state = 0 /* BeginningOfLine */;
                                    indent = 0;
                                    break;
                                case 39 /* AsteriskToken */:
                                    var asterisk = scanner.getTokenText();
                                    if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
                                        // If we've already seen an asterisk, then we can no longer parse a tag on this line
                                        state = 2 /* SavingComments */;
                                        pushComment(asterisk);
                                    }
                                    else {
                                        // Ignore the first asterisk on a line
                                        state = 1 /* SawAsterisk */;
                                        indent += asterisk.length;
                                    }
                                    break;
                                case 71 /* Identifier */:
                                    // Anything else is doc comment text. We just save it. Because it
                                    // wasn't a tag, we can no longer parse a tag on this line until we hit the next
                                    // line break.
                                    pushComment(scanner.getTokenText());
                                    state = 2 /* SavingComments */;
                                    break;
                                case 5 /* WhitespaceTrivia */:
                                    // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
                                    var whitespace = scanner.getTokenText();
                                    if (state === 2 /* SavingComments */) {
                                        comments.push(whitespace);
                                    }
                                    else if (margin !== undefined && indent + whitespace.length > margin) {
                                        comments.push(whitespace.slice(margin - indent - 1));
                                    }
                                    indent += whitespace.length;
                                    break;
                                case 1 /* EndOfFileToken */:
                                    break loop;
                                default:
                                    // anything other than whitespace or asterisk at the beginning of the line starts the comment text
                                    state = 2 /* SavingComments */;
                                    pushComment(scanner.getTokenText());
                                    break;
                            }
                            nextJSDocToken();
                        }
                        removeLeadingNewlines(comments);
                        removeTrailingWhitespace(comments);
                        return createJSDocComment();
                    });
                    function removeLeadingNewlines(comments) {
                        while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
                            comments.shift();
                        }
                    }
                    function removeTrailingWhitespace(comments) {
                        while (comments.length && comments[comments.length - 1].trim() === "") {
                            comments.pop();
                        }
                    }
                    function createJSDocComment() {
                        var result = createNode(289 /* JSDocComment */, start);
                        result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
                        result.comment = comments.length ? comments.join("") : undefined;
                        return finishNode(result, end);
                    }
                    function isNextNonwhitespaceTokenEndOfFile() {
                        // We must use infinite lookahead, as there could be any number of newlines :(
                        while (true) {
                            nextJSDocToken();
                            if (token() === 1 /* EndOfFileToken */) {
                                return true;
                            }
                            if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
                                return false;
                            }
                        }
                    }
                    function skipWhitespace() {
                        if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
                            if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
                                return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
                            }
                        }
                        while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
                            nextJSDocToken();
                        }
                    }
                    function skipWhitespaceOrAsterisk() {
                        if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
                            if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
                                return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
                            }
                        }
                        var precedingLineBreak = scanner.hasPrecedingLineBreak();
                        while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
                            if (token() === 4 /* NewLineTrivia */) {
                                precedingLineBreak = true;
                            }
                            else if (token() === 39 /* AsteriskToken */) {
                                precedingLineBreak = false;
                            }
                            nextJSDocToken();
                        }
                    }
                    function parseTag(indent) {
                        ts.Debug.assert(token() === 57 /* AtToken */);
                        var atToken = createNode(57 /* AtToken */, scanner.getTokenPos());
                        atToken.end = scanner.getTextPos();
                        nextJSDocToken();
                        var tagName = parseJSDocIdentifierName(/*message*/ undefined);
                        skipWhitespaceOrAsterisk();
                        var tag;
                        switch (tagName.escapedText) {
                            case "augments":
                            case "extends":
                                tag = parseAugmentsTag(atToken, tagName);
                                break;
                            case "class":
                            case "constructor":
                                tag = parseClassTag(atToken, tagName);
                                break;
                            case "this":
                                tag = parseThisTag(atToken, tagName);
                                break;
                            case "enum":
                                tag = parseEnumTag(atToken, tagName);
                                break;
                            case "arg":
                            case "argument":
                            case "param":
                                return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent);
                            case "return":
                            case "returns":
                                tag = parseReturnTag(atToken, tagName);
                                break;
                            case "template":
                                tag = parseTemplateTag(atToken, tagName);
                                break;
                            case "type":
                                tag = parseTypeTag(atToken, tagName);
                                break;
                            case "typedef":
                                tag = parseTypedefTag(atToken, tagName, indent);
                                break;
                            case "callback":
                                tag = parseCallbackTag(atToken, tagName, indent);
                                break;
                            default:
                                tag = parseUnknownTag(atToken, tagName);
                                break;
                        }
                        if (!tag.comment) {
                            // some tags, like typedef and callback, have already parsed their comments earlier
                            tag.comment = parseTagComments(indent + tag.end - tag.pos);
                        }
                        return tag;
                    }
                    function parseTagComments(indent) {
                        var comments = [];
                        var state = 0 /* BeginningOfLine */;
                        var margin;
                        function pushComment(text) {
                            if (!margin) {
                                margin = indent;
                            }
                            comments.push(text);
                            indent += text.length;
                        }
                        var tok = token();
                        loop: while (true) {
                            switch (tok) {
                                case 4 /* NewLineTrivia */:
                                    if (state >= 1 /* SawAsterisk */) {
                                        state = 0 /* BeginningOfLine */;
                                        comments.push(scanner.getTokenText());
                                    }
                                    indent = 0;
                                    break;
                                case 57 /* AtToken */:
                                    scanner.setTextPos(scanner.getTextPos() - 1);
                                // falls through
                                case 1 /* EndOfFileToken */:
                                    // Done
                                    break loop;
                                case 5 /* WhitespaceTrivia */:
                                    if (state === 2 /* SavingComments */) {
                                        pushComment(scanner.getTokenText());
                                    }
                                    else {
                                        var whitespace = scanner.getTokenText();
                                        // if the whitespace crosses the margin, take only the whitespace that passes the margin
                                        if (margin !== undefined && indent + whitespace.length > margin) {
                                            comments.push(whitespace.slice(margin - indent - 1));
                                        }
                                        indent += whitespace.length;
                                    }
                                    break;
                                case 17 /* OpenBraceToken */:
                                    state = 2 /* SavingComments */;
                                    if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) {
                                        pushComment(scanner.getTokenText());
                                        nextJSDocToken();
                                        pushComment(scanner.getTokenText());
                                        nextJSDocToken();
                                    }
                                    pushComment(scanner.getTokenText());
                                    break;
                                case 39 /* AsteriskToken */:
                                    if (state === 0 /* BeginningOfLine */) {
                                        // leading asterisks start recording on the *next* (non-whitespace) token
                                        state = 1 /* SawAsterisk */;
                                        indent += 1;
                                        break;
                                    }
                                // record the * as a comment
                                // falls through
                                default:
                                    state = 2 /* SavingComments */; // leading identifiers start recording as well
                                    pushComment(scanner.getTokenText());
                                    break;
                            }
                            tok = nextJSDocToken();
                        }
                        removeLeadingNewlines(comments);
                        removeTrailingWhitespace(comments);
                        return comments.length === 0 ? undefined : comments.join("");
                    }
                    function parseUnknownTag(atToken, tagName) {
                        var result = createNode(292 /* JSDocTag */, atToken.pos);
                        result.atToken = atToken;
                        result.tagName = tagName;
                        return finishNode(result);
                    }
                    function addTag(tag) {
                        if (!tag) {
                            return;
                        }
                        if (!tags) {
                            tags = [tag];
                            tagsPos = tag.pos;
                        }
                        else {
                            tags.push(tag);
                        }
                        tagsEnd = tag.end;
                    }
                    function tryParseTypeExpression() {
                        skipWhitespaceOrAsterisk();
                        return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
                    }
                    function parseBracketNameInPropertyAndParamTag() {
                        if (token() === 13 /* NoSubstitutionTemplateLiteral */) {
                            // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
                            return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false };
                        }
                        // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
                        var isBracketed = parseOptional(21 /* OpenBracketToken */);
                        var name = parseJSDocEntityName();
                        if (isBracketed) {
                            skipWhitespace();
                            // May have an optional default, e.g. '[foo = 42]'
                            if (parseOptionalToken(58 /* EqualsToken */)) {
                                parseExpression();
                            }
                            parseExpected(22 /* CloseBracketToken */);
                        }
                        return { name: name, isBracketed: isBracketed };
                    }
                    function isObjectOrObjectArrayTypeReference(node) {
                        switch (node.kind) {
                            case 135 /* ObjectKeyword */:
                                return true;
                            case 167 /* ArrayType */:
                                return isObjectOrObjectArrayTypeReference(node.elementType);
                            default:
                                return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object";
                        }
                    }
                    function parseParameterOrPropertyTag(atToken, tagName, target, indent) {
                        var typeExpression = tryParseTypeExpression();
                        var isNameFirst = !typeExpression;
                        skipWhitespaceOrAsterisk();
                        var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
                        skipWhitespace();
                        if (isNameFirst) {
                            typeExpression = tryParseTypeExpression();
                        }
                        var result = target === 1 /* Property */ ?
                            createNode(303 /* JSDocPropertyTag */, atToken.pos) :
                            createNode(297 /* JSDocParameterTag */, atToken.pos);
                        var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
                        var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
                        if (nestedTypeLiteral) {
                            typeExpression = nestedTypeLiteral;
                            isNameFirst = true;
                        }
                        result.atToken = atToken;
                        result.tagName = tagName;
                        result.typeExpression = typeExpression;
                        result.name = name;
                        result.isNameFirst = isNameFirst;
                        result.isBracketed = isBracketed;
                        result.comment = comment;
                        return finishNode(result);
                    }
                    function parseNestedTypeLiteral(typeExpression, name, target, indent) {
                        if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
                            var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos());
                            var child = void 0;
                            var jsdocTypeLiteral = void 0;
                            var start_2 = scanner.getStartPos();
                            var children = void 0;
                            while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
                                if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) {
                                    children = ts.append(children, child);
                                }
                            }
                            if (children) {
                                jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2);
                                jsdocTypeLiteral.jsDocPropertyTags = children;
                                if (typeExpression.type.kind === 167 /* ArrayType */) {
                                    jsdocTypeLiteral.isArrayType = true;
                                }
                                typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
                                return finishNode(typeLiteralExpression);
                            }
                        }
                    }
                    function parseReturnTag(atToken, tagName) {
                        if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) {
                            parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
                        }
                        var result = createNode(298 /* JSDocReturnTag */, atToken.pos);
                        result.atToken = atToken;
                        result.tagName = tagName;
                        result.typeExpression = tryParseTypeExpression();
                        return finishNode(result);
                    }
                    function parseTypeTag(atToken, tagName) {
                        if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) {
                            parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
                        }
                        var result = createNode(300 /* JSDocTypeTag */, atToken.pos);
                        result.atToken = atToken;
                        result.tagName = tagName;
                        result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
                        return finishNode(result);
                    }
                    function parseAugmentsTag(atToken, tagName) {
                        var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos);
                        result.atToken = atToken;
                        result.tagName = tagName;
                        result.class = parseExpressionWithTypeArgumentsForAugments();
                        return finishNode(result);
                    }
                    function parseExpressionWithTypeArgumentsForAugments() {
                        var usedBrace = parseOptional(17 /* OpenBraceToken */);
                        var node = createNode(209 /* ExpressionWithTypeArguments */);
                        node.expression = parsePropertyAccessEntityNameExpression();
                        node.typeArguments = tryParseTypeArguments();
                        var res = finishNode(node);
                        if (usedBrace) {
                            parseExpected(18 /* CloseBraceToken */);
                        }
                        return res;
                    }
                    function parsePropertyAccessEntityNameExpression() {
                        var node = parseJSDocIdentifierName();
                        while (parseOptional(23 /* DotToken */)) {
                            var prop = createNode(187 /* PropertyAccessExpression */, node.pos);
                            prop.expression = node;
                            prop.name = parseJSDocIdentifierName();
                            node = finishNode(prop);
                        }
                        return node;
                    }
                    function parseClassTag(atToken, tagName) {
                        var tag = createNode(294 /* JSDocClassTag */, atToken.pos);
                        tag.atToken = atToken;
                        tag.tagName = tagName;
                        return finishNode(tag);
                    }
                    function parseThisTag(atToken, tagName) {
                        var tag = createNode(299 /* JSDocThisTag */, atToken.pos);
                        tag.atToken = atToken;
                        tag.tagName = tagName;
                        tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
                        skipWhitespace();
                        return finishNode(tag);
                    }
                    function parseEnumTag(atToken, tagName) {
                        var tag = createNode(296 /* JSDocEnumTag */, atToken.pos);
                        tag.atToken = atToken;
                        tag.tagName = tagName;
                        tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
                        skipWhitespace();
                        return finishNode(tag);
                    }
                    function parseTypedefTag(atToken, tagName, indent) {
                        var typeExpression = tryParseTypeExpression();
                        skipWhitespaceOrAsterisk();
                        var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos);
                        typedefTag.atToken = atToken;
                        typedefTag.tagName = tagName;
                        typedefTag.fullName = parseJSDocTypeNameWithNamespace();
                        typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
                        skipWhitespace();
                        typedefTag.comment = parseTagComments(indent);
                        typedefTag.typeExpression = typeExpression;
                        var end;
                        if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
                            var child = void 0;
                            var jsdocTypeLiteral = void 0;
                            var childTypeTag = void 0;
                            var start_3 = atToken.pos;
                            while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
                                if (!jsdocTypeLiteral) {
                                    jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3);
                                }
                                if (child.kind === 300 /* JSDocTypeTag */) {
                                    if (childTypeTag) {
                                        break;
                                    }
                                    else {
                                        childTypeTag = child;
                                    }
                                }
                                else {
                                    jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
                                }
                            }
                            if (jsdocTypeLiteral) {
                                if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) {
                                    jsdocTypeLiteral.isArrayType = true;
                                }
                                typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
                                    childTypeTag.typeExpression :
                                    finishNode(jsdocTypeLiteral);
                                end = typedefTag.typeExpression.end;
                            }
                        }
                        // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
                        return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
                    }
                    function parseJSDocTypeNameWithNamespace(nested) {
                        var pos = scanner.getTokenPos();
                        if (!ts.tokenIsIdentifierOrKeyword(token())) {
                            return undefined;
                        }
                        var typeNameOrNamespaceName = parseJSDocIdentifierName();
                        if (parseOptional(23 /* DotToken */)) {
                            var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos);
                            if (nested) {
                                jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
                            }
                            jsDocNamespaceNode.name = typeNameOrNamespaceName;
                            jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
                            return finishNode(jsDocNamespaceNode);
                        }
                        if (nested) {
                            typeNameOrNamespaceName.isInJSDocNamespace = true;
                        }
                        return typeNameOrNamespaceName;
                    }
                    function parseCallbackTag(atToken, tagName, indent) {
                        var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos);
                        callbackTag.atToken = atToken;
                        callbackTag.tagName = tagName;
                        callbackTag.fullName = parseJSDocTypeNameWithNamespace();
                        callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
                        skipWhitespace();
                        callbackTag.comment = parseTagComments(indent);
                        var child;
                        var start = scanner.getStartPos();
                        var jsdocSignature = createNode(291 /* JSDocSignature */, start);
                        jsdocSignature.parameters = [];
                        while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
                            jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
                        }
                        var returnTag = tryParse(function () {
                            if (parseOptionalJsdoc(57 /* AtToken */)) {
                                var tag = parseTag(indent);
                                if (tag && tag.kind === 298 /* JSDocReturnTag */) {
                                    return tag;
                                }
                            }
                        });
                        if (returnTag) {
                            jsdocSignature.type = returnTag;
                        }
                        callbackTag.typeExpression = finishNode(jsdocSignature);
                        return finishNode(callbackTag);
                    }
                    function getJSDocTypeAliasName(fullName) {
                        if (fullName) {
                            var rightNode = fullName;
                            while (true) {
                                if (ts.isIdentifier(rightNode) || !rightNode.body) {
                                    return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
                                }
                                rightNode = rightNode.body;
                            }
                        }
                    }
                    function escapedTextsEqual(a, b) {
                        while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
                            if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
                                a = a.left;
                                b = b.left;
                            }
                            else {
                                return false;
                            }
                        }
                        return a.escapedText === b.escapedText;
                    }
                    function parseChildPropertyTag(indent) {
                        return parseChildParameterOrPropertyTag(1 /* Property */, indent);
                    }
                    function parseChildParameterOrPropertyTag(target, indent, name) {
                        var canParseTag = true;
                        var seenAsterisk = false;
                        while (true) {
                            switch (nextJSDocToken()) {
                                case 57 /* AtToken */:
                                    if (canParseTag) {
                                        var child = tryParseChildTag(target, indent);
                                        if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) &&
                                            target !== 4 /* CallbackParameter */ &&
                                            name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
                                            return false;
                                        }
                                        return child;
                                    }
                                    seenAsterisk = false;
                                    break;
                                case 4 /* NewLineTrivia */:
                                    canParseTag = true;
                                    seenAsterisk = false;
                                    break;
                                case 39 /* AsteriskToken */:
                                    if (seenAsterisk) {
                                        canParseTag = false;
                                    }
                                    seenAsterisk = true;
                                    break;
                                case 71 /* Identifier */:
                                    canParseTag = false;
                                    break;
                                case 1 /* EndOfFileToken */:
                                    return false;
                            }
                        }
                    }
                    function tryParseChildTag(target, indent) {
                        ts.Debug.assert(token() === 57 /* AtToken */);
                        var atToken = createNode(57 /* AtToken */);
                        atToken.end = scanner.getTextPos();
                        nextJSDocToken();
                        var tagName = parseJSDocIdentifierName();
                        skipWhitespace();
                        var t;
                        switch (tagName.escapedText) {
                            case "type":
                                return target === 1 /* Property */ && parseTypeTag(atToken, tagName);
                            case "prop":
                            case "property":
                                t = 1 /* Property */;
                                break;
                            case "arg":
                            case "argument":
                            case "param":
                                t = 2 /* Parameter */ | 4 /* CallbackParameter */;
                                break;
                            default:
                                return false;
                        }
                        if (!(target & t)) {
                            return false;
                        }
                        return parseParameterOrPropertyTag(atToken, tagName, target, indent);
                    }
                    function parseTemplateTag(atToken, tagName) {
                        // the template tag looks like '@template {Constraint} T,U,V'
                        var constraint;
                        if (token() === 17 /* OpenBraceToken */) {
                            constraint = parseJSDocTypeExpression();
                        }
                        var typeParameters = [];
                        var typeParametersPos = getNodePos();
                        do {
                            skipWhitespace();
                            var typeParameter = createNode(148 /* TypeParameter */);
                            typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
                            finishNode(typeParameter);
                            skipWhitespace();
                            typeParameters.push(typeParameter);
                        } while (parseOptionalJsdoc(26 /* CommaToken */));
                        var result = createNode(301 /* JSDocTemplateTag */, atToken.pos);
                        result.atToken = atToken;
                        result.tagName = tagName;
                        result.constraint = constraint;
                        result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
                        finishNode(result);
                        return result;
                    }
                    function nextJSDocToken() {
                        return currentToken = scanner.scanJSDocToken();
                    }
                    function parseOptionalJsdoc(t) {
                        if (token() === t) {
                            nextJSDocToken();
                            return true;
                        }
                        return false;
                    }
                    function parseJSDocEntityName() {
                        var entity = parseJSDocIdentifierName();
                        if (parseOptional(21 /* OpenBracketToken */)) {
                            parseExpected(22 /* CloseBracketToken */);
                            // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
                            // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
                            // but it's not worth it to enforce that restriction.
                        }
                        while (parseOptional(23 /* DotToken */)) {
                            var name = parseJSDocIdentifierName();
                            if (parseOptional(21 /* OpenBracketToken */)) {
                                parseExpected(22 /* CloseBracketToken */);
                            }
                            entity = createQualifiedName(entity, name);
                        }
                        return entity;
                    }
                    function parseJSDocIdentifierName(message) {
                        if (!ts.tokenIsIdentifierOrKeyword(token())) {
                            return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
                        }
                        var pos = scanner.getTokenPos();
                        var end = scanner.getTextPos();
                        var result = createNode(71 /* Identifier */, pos);
                        result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText());
                        finishNode(result, end);
                        nextJSDocToken();
                        return result;
                    }
                }
                JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker;
            })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
        })(Parser || (Parser = {}));
        var IncrementalParser;
        (function (IncrementalParser) {
            function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
                aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
                checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
                if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
                    // if the text didn't change, then we can just return our current source file as-is.
                    return sourceFile;
                }
                if (sourceFile.statements.length === 0) {
                    // If we don't have any statements in the current source file, then there's no real
                    // way to incrementally parse.  So just do a full parse instead.
                    return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
                }
                // Make sure we're not trying to incrementally update a source file more than once.  Once
                // we do an update the original source file is considered unusable from that point onwards.
                //
                // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
                // tree and give them new positions and parents.  From that point on, trusting the old
                // tree at all is not possible as far too much of it may violate invariants.
                var incrementalSourceFile = sourceFile;
                ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
                incrementalSourceFile.hasBeenIncrementallyParsed = true;
                var oldText = sourceFile.text;
                var syntaxCursor = createSyntaxCursor(sourceFile);
                // Make the actual change larger so that we know to reparse anything whose lookahead
                // might have intersected the change.
                var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
                checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
                // Ensure that extending the affected range only moved the start of the change range
                // earlier in the file.
                ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
                ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
                ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
                // The is the amount the nodes after the edit range need to be adjusted.  It can be
                // positive (if the edit added characters), negative (if the edit deleted characters)
                // or zero (if this was a pure overwrite with nothing added/removed).
                var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
                // If we added or removed characters during the edit, then we need to go and adjust all
                // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
                // may move backward (if we deleted chars).
                //
                // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
                // to reuse are already at the appropriate position in the new text.  That way when we
                // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
                // it very easy to determine if we can reuse a node.  If the node's position is at where
                // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
                // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
                // us, then we'll need to skip it or crumble it as appropriate
                //
                // We will also adjust the positions of nodes that intersect the change range as well.
                // By doing this, we ensure that all the positions in the old tree are consistent, not
                // just the positions of nodes entirely before/after the change range.  By being
                // consistent, we can then easily map from positions to nodes in the old tree easily.
                //
                // Also, mark any syntax elements that intersect the changed span.  We know, up front,
                // that we cannot reuse these elements.
                updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
                // Now that we've set up our internal incremental state just proceed and parse the
                // source file in the normal fashion.  When possible the parser will retrieve and
                // reuse nodes from the old tree.
                //
                // Note: passing in 'true' for setNodeParents is very important.  When incrementally
                // parsing, we will be reusing nodes from the old tree, and placing it into new
                // parents.  If we don't set the parents now, we'll end up with an observably
                // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
                // will immediately bail out of walking any subtrees when we can see that their parents
                // are already correct.
                var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
                return result;
            }
            IncrementalParser.updateSourceFile = updateSourceFile;
            function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
                if (isArray) {
                    visitArray(element);
                }
                else {
                    visitNode(element);
                }
                return;
                function visitNode(node) {
                    var text = "";
                    if (aggressiveChecks && shouldCheckNode(node)) {
                        text = oldText.substring(node.pos, node.end);
                    }
                    // Ditch any existing LS children we may have created.  This way we can avoid
                    // moving them forward.
                    if (node._children) {
                        node._children = undefined;
                    }
                    node.pos += delta;
                    node.end += delta;
                    if (aggressiveChecks && shouldCheckNode(node)) {
                        ts.Debug.assert(text === newText.substring(node.pos, node.end));
                    }
                    forEachChild(node, visitNode, visitArray);
                    if (ts.hasJSDocNodes(node)) {
                        for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
                            var jsDocComment = _a[_i];
                            visitNode(jsDocComment);
                        }
                    }
                    checkNodePositions(node, aggressiveChecks);
                }
                function visitArray(array) {
                    array._children = undefined;
                    array.pos += delta;
                    array.end += delta;
                    for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
                        var node = array_8[_i];
                        visitNode(node);
                    }
                }
            }
            function shouldCheckNode(node) {
                switch (node.kind) {
                    case 9 /* StringLiteral */:
                    case 8 /* NumericLiteral */:
                    case 71 /* Identifier */:
                        return true;
                }
                return false;
            }
            function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
                ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
                ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
                ts.Debug.assert(element.pos <= element.end);
                // We have an element that intersects the change range in some way.  It may have its
                // start, or its end (or both) in the changed range.  We want to adjust any part
                // that intersects such that the final tree is in a consistent state.  i.e. all
                // children have spans within the span of their parent, and all siblings are ordered
                // properly.
                // We may need to update both the 'pos' and the 'end' of the element.
                // If the 'pos' is before the start of the change, then we don't need to touch it.
                // If it isn't, then the 'pos' must be inside the change.  How we update it will
                // depend if delta is positive or negative. If delta is positive then we have
                // something like:
                //
                //  -------------------AAA-----------------
                //  -------------------BBBCCCCCCC-----------------
                //
                // In this case, we consider any node that started in the change range to still be
                // starting at the same position.
                //
                // however, if the delta is negative, then we instead have something like this:
                //
                //  -------------------XXXYYYYYYY-----------------
                //  -------------------ZZZ-----------------
                //
                // In this case, any element that started in the 'X' range will keep its position.
                // However any element that started after that will have their pos adjusted to be
                // at the end of the new range.  i.e. any node that started in the 'Y' range will
                // be adjusted to have their start at the end of the 'Z' range.
                //
                // The element will keep its position if possible.  Or Move backward to the new-end
                // if it's in the 'Y' range.
                element.pos = Math.min(element.pos, changeRangeNewEnd);
                // If the 'end' is after the change range, then we always adjust it by the delta
                // amount.  However, if the end is in the change range, then how we adjust it
                // will depend on if delta is positive or negative.  If delta is positive then we
                // have something like:
                //
                //  -------------------AAA-----------------
                //  -------------------BBBCCCCCCC-----------------
                //
                // In this case, we consider any node that ended inside the change range to keep its
                // end position.
                //
                // however, if the delta is negative, then we instead have something like this:
                //
                //  -------------------XXXYYYYYYY-----------------
                //  -------------------ZZZ-----------------
                //
                // In this case, any element that ended in the 'X' range will keep its position.
                // However any element that ended after that will have their pos adjusted to be
                // at the end of the new range.  i.e. any node that ended in the 'Y' range will
                // be adjusted to have their end at the end of the 'Z' range.
                if (element.end >= changeRangeOldEnd) {
                    // Element ends after the change range.  Always adjust the end pos.
                    element.end += delta;
                }
                else {
                    // Element ends in the change range.  The element will keep its position if
                    // possible. Or Move backward to the new-end if it's in the 'Y' range.
                    element.end = Math.min(element.end, changeRangeNewEnd);
                }
                ts.Debug.assert(element.pos <= element.end);
                if (element.parent) {
                    ts.Debug.assert(element.pos >= element.parent.pos);
                    ts.Debug.assert(element.end <= element.parent.end);
                }
            }
            function checkNodePositions(node, aggressiveChecks) {
                if (aggressiveChecks) {
                    var pos_2 = node.pos;
                    var visitNode_1 = function (child) {
                        ts.Debug.assert(child.pos >= pos_2);
                        pos_2 = child.end;
                    };
                    if (ts.hasJSDocNodes(node)) {
                        for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
                            var jsDocComment = _a[_i];
                            visitNode_1(jsDocComment);
                        }
                    }
                    forEachChild(node, visitNode_1);
                    ts.Debug.assert(pos_2 <= node.end);
                }
            }
            function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
                visitNode(sourceFile);
                return;
                function visitNode(child) {
                    ts.Debug.assert(child.pos <= child.end);
                    if (child.pos > changeRangeOldEnd) {
                        // Node is entirely past the change range.  We need to move both its pos and
                        // end, forward or backward appropriately.
                        moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
                        return;
                    }
                    // Check if the element intersects the change range.  If it does, then it is not
                    // reusable.  Also, we'll need to recurse to see what constituent portions we may
                    // be able to use.
                    var fullEnd = child.end;
                    if (fullEnd >= changeStart) {
                        child.intersectsChange = true;
                        child._children = undefined;
                        // Adjust the pos or end (or both) of the intersecting element accordingly.
                        adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
                        forEachChild(child, visitNode, visitArray);
                        if (ts.hasJSDocNodes(child)) {
                            for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
                                var jsDocComment = _a[_i];
                                visitNode(jsDocComment);
                            }
                        }
                        checkNodePositions(child, aggressiveChecks);
                        return;
                    }
                    // Otherwise, the node is entirely before the change range.  No need to do anything with it.
                    ts.Debug.assert(fullEnd < changeStart);
                }
                function visitArray(array) {
                    ts.Debug.assert(array.pos <= array.end);
                    if (array.pos > changeRangeOldEnd) {
                        // Array is entirely after the change range.  We need to move it, and move any of
                        // its children.
                        moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
                        return;
                    }
                    // Check if the element intersects the change range.  If it does, then it is not
                    // reusable.  Also, we'll need to recurse to see what constituent portions we may
                    // be able to use.
                    var fullEnd = array.end;
                    if (fullEnd >= changeStart) {
                        array.intersectsChange = true;
                        array._children = undefined;
                        // Adjust the pos or end (or both) of the intersecting array accordingly.
                        adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
                        for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
                            var node = array_9[_i];
                            visitNode(node);
                        }
                        return;
                    }
                    // Otherwise, the array is entirely before the change range.  No need to do anything with it.
                    ts.Debug.assert(fullEnd < changeStart);
                }
            }
            function extendToAffectedRange(sourceFile, changeRange) {
                // Consider the following code:
                //      void foo() { /; }
                //
                // If the text changes with an insertion of / just before the semicolon then we end up with:
                //      void foo() { //; }
                //
                // If we were to just use the changeRange a is, then we would not rescan the { token
                // (as it does not intersect the actual original change range).  Because an edit may
                // change the token touching it, we actually need to look back *at least* one token so
                // that the prior token sees that change.
                var maxLookahead = 1;
                var start = changeRange.span.start;
                // the first iteration aligns us with the change start. subsequent iteration move us to
                // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
                // start of the tree.
                for (var i = 0; start > 0 && i <= maxLookahead; i++) {
                    var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
                    ts.Debug.assert(nearestNode.pos <= start);
                    var position = nearestNode.pos;
                    start = Math.max(0, position - 1);
                }
                var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
                var finalLength = changeRange.newLength + (changeRange.span.start - start);
                return ts.createTextChangeRange(finalSpan, finalLength);
            }
            function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
                var bestResult = sourceFile;
                var lastNodeEntirelyBeforePosition;
                forEachChild(sourceFile, visit);
                if (lastNodeEntirelyBeforePosition) {
                    var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
                    if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
                        bestResult = lastChildOfLastEntireNodeBeforePosition;
                    }
                }
                return bestResult;
                function getLastDescendant(node) {
                    while (true) {
                        var lastChild = ts.getLastChild(node);
                        if (lastChild) {
                            node = lastChild;
                        }
                        else {
                            return node;
                        }
                    }
                }
                function visit(child) {
                    if (ts.nodeIsMissing(child)) {
                        // Missing nodes are effectively invisible to us.  We never even consider them
                        // When trying to find the nearest node before us.
                        return;
                    }
                    // If the child intersects this position, then this node is currently the nearest
                    // node that starts before the position.
                    if (child.pos <= position) {
                        if (child.pos >= bestResult.pos) {
                            // This node starts before the position, and is closer to the position than
                            // the previous best node we found.  It is now the new best node.
                            bestResult = child;
                        }
                        // Now, the node may overlap the position, or it may end entirely before the
                        // position.  If it overlaps with the position, then either it, or one of its
                        // children must be the nearest node before the position.  So we can just
                        // recurse into this child to see if we can find something better.
                        if (position < child.end) {
                            // The nearest node is either this child, or one of the children inside
                            // of it.  We've already marked this child as the best so far.  Recurse
                            // in case one of the children is better.
                            forEachChild(child, visit);
                            // Once we look at the children of this node, then there's no need to
                            // continue any further.
                            return true;
                        }
                        else {
                            ts.Debug.assert(child.end <= position);
                            // The child ends entirely before this position.  Say you have the following
                            // (where $ is the position)
                            //
                            //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
                            //
                            // We would want to find the nearest preceding node in "complex expr 2".
                            // To support that, we keep track of this node, and once we're done searching
                            // for a best node, we recurse down this node to see if we can find a good
                            // result in it.
                            //
                            // This approach allows us to quickly skip over nodes that are entirely
                            // before the position, while still allowing us to find any nodes in the
                            // last one that might be what we want.
                            lastNodeEntirelyBeforePosition = child;
                        }
                    }
                    else {
                        ts.Debug.assert(child.pos > position);
                        // We're now at a node that is entirely past the position we're searching for.
                        // This node (and all following nodes) could never contribute to the result,
                        // so just skip them by returning 'true' here.
                        return true;
                    }
                }
            }
            function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
                var oldText = sourceFile.text;
                if (textChangeRange) {
                    ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
                    if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
                        var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
                        var newTextPrefix = newText.substr(0, textChangeRange.span.start);
                        ts.Debug.assert(oldTextPrefix === newTextPrefix);
                        var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
                        var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
                        ts.Debug.assert(oldTextSuffix === newTextSuffix);
                    }
                }
            }
            function createSyntaxCursor(sourceFile) {
                var currentArray = sourceFile.statements;
                var currentArrayIndex = 0;
                ts.Debug.assert(currentArrayIndex < currentArray.length);
                var current = currentArray[currentArrayIndex];
                var lastQueriedPosition = -1 /* Value */;
                return {
                    currentNode: function (position) {
                        // Only compute the current node if the position is different than the last time
                        // we were asked.  The parser commonly asks for the node at the same position
                        // twice.  Once to know if can read an appropriate list element at a certain point,
                        // and then to actually read and consume the node.
                        if (position !== lastQueriedPosition) {
                            // Much of the time the parser will need the very next node in the array that
                            // we just returned a node from.So just simply check for that case and move
                            // forward in the array instead of searching for the node again.
                            if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
                                currentArrayIndex++;
                                current = currentArray[currentArrayIndex];
                            }
                            // If we don't have a node, or the node we have isn't in the right position,
                            // then try to find a viable node at the position requested.
                            if (!current || current.pos !== position) {
                                findHighestListElementThatStartsAtPosition(position);
                            }
                        }
                        // Cache this query so that we don't do any extra work if the parser calls back
                        // into us.  Note: this is very common as the parser will make pairs of calls like
                        // 'isListElement -> parseListElement'.  If we were unable to find a node when
                        // called with 'isListElement', we don't want to redo the work when parseListElement
                        // is called immediately after.
                        lastQueriedPosition = position;
                        // Either we don'd have a node, or we have a node at the position being asked for.
                        ts.Debug.assert(!current || current.pos === position);
                        return current;
                    }
                };
                // Finds the highest element in the tree we can find that starts at the provided position.
                // The element must be a direct child of some node list in the tree.  This way after we
                // return it, we can easily return its next sibling in the list.
                function findHighestListElementThatStartsAtPosition(position) {
                    // Clear out any cached state about the last node we found.
                    currentArray = undefined;
                    currentArrayIndex = -1 /* Value */;
                    current = undefined;
                    // Recurse into the source file to find the highest node at this position.
                    forEachChild(sourceFile, visitNode, visitArray);
                    return;
                    function visitNode(node) {
                        if (position >= node.pos && position < node.end) {
                            // Position was within this node.  Keep searching deeper to find the node.
                            forEachChild(node, visitNode, visitArray);
                            // don't proceed any further in the search.
                            return true;
                        }
                        // position wasn't in this node, have to keep searching.
                        return false;
                    }
                    function visitArray(array) {
                        if (position >= array.pos && position < array.end) {
                            // position was in this array.  Search through this array to see if we find a
                            // viable element.
                            for (var i = 0; i < array.length; i++) {
                                var child = array[i];
                                if (child) {
                                    if (child.pos === position) {
                                        // Found the right node.  We're done.
                                        currentArray = array;
                                        currentArrayIndex = i;
                                        current = child;
                                        return true;
                                    }
                                    else {
                                        if (child.pos < position && position < child.end) {
                                            // Position in somewhere within this child.  Search in it and
                                            // stop searching in this array.
                                            forEachChild(child, visitNode, visitArray);
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                        // position wasn't in this array, have to keep searching.
                        return false;
                    }
                }
            }
            var InvalidPosition;
            (function (InvalidPosition) {
                InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
            })(InvalidPosition || (InvalidPosition = {}));
        })(IncrementalParser || (IncrementalParser = {}));
        /** @internal */
        function isDeclarationFileName(fileName) {
            return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
        }
        ts.isDeclarationFileName = isDeclarationFileName;
        /*@internal*/
        function processCommentPragmas(context, sourceText) {
            var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText);
            var pragmas = [];
            // Keep scanning all the leading trivia in the file until we get to something that
            // isn't trivia.  Any single line comment will be analyzed to see if it is a
            // reference comment.
            while (true) {
                var kind = triviaScanner.scan();
                if (!ts.isTrivia(kind)) {
                    break;
                }
                var range = {
                    kind: triviaScanner.getToken(),
                    pos: triviaScanner.getTokenPos(),
                    end: triviaScanner.getTextPos(),
                };
                var comment = sourceText.substring(range.pos, range.end);
                extractPragmas(pragmas, range, comment);
            }
            context.pragmas = ts.createMap();
            for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) {
                var pragma = pragmas_1[_i];
                if (context.pragmas.has(pragma.name)) { // TODO: GH#18217
                    var currentValue = context.pragmas.get(pragma.name);
                    if (currentValue instanceof Array) {
                        currentValue.push(pragma.args);
                    }
                    else {
                        context.pragmas.set(pragma.name, [currentValue, pragma.args]);
                    }
                    continue;
                }
                context.pragmas.set(pragma.name, pragma.args);
            }
        }
        ts.processCommentPragmas = processCommentPragmas;
        /*@internal*/
        function processPragmasIntoFields(context, reportDiagnostic) {
            context.checkJsDirective = undefined;
            context.referencedFiles = [];
            context.typeReferenceDirectives = [];
            context.libReferenceDirectives = [];
            context.amdDependencies = [];
            context.hasNoDefaultLib = false;
            context.pragmas.forEach(function (entryOrList, key) {
                // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
                // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
                switch (key) {
                    case "reference": {
                        var referencedFiles_1 = context.referencedFiles;
                        var typeReferenceDirectives_1 = context.typeReferenceDirectives;
                        var libReferenceDirectives_1 = context.libReferenceDirectives;
                        ts.forEach(ts.toArray(entryOrList), function (arg) {
                            // TODO: GH#18217
                            if (arg.arguments["no-default-lib"]) {
                                context.hasNoDefaultLib = true;
                            }
                            else if (arg.arguments.types) {
                                typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value });
                            }
                            else if (arg.arguments.lib) {
                                libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value });
                            }
                            else if (arg.arguments.path) {
                                referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value });
                            }
                            else {
                                reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
                            }
                        });
                        break;
                    }
                    case "amd-dependency": {
                        context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217
                        break;
                    }
                    case "amd-module": {
                        if (entryOrList instanceof Array) {
                            for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
                                var entry = entryOrList_1[_i];
                                if (context.moduleName) {
                                    // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
                                    reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
                                }
                                context.moduleName = entry.arguments.name;
                            }
                        }
                        else {
                            context.moduleName = entryOrList.arguments.name;
                        }
                        break;
                    }
                    case "ts-nocheck":
                    case "ts-check": {
                        // _last_ of either nocheck or check in a file is the "winner"
                        ts.forEach(ts.toArray(entryOrList), function (entry) {
                            if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217
                                context.checkJsDirective = {
                                    enabled: key === "ts-check",
                                    end: entry.range.end,
                                    pos: entry.range.pos
                                };
                            }
                        });
                        break;
                    }
                    case "jsx": return; // Accessed directly
                    default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
                }
            });
        }
        ts.processPragmasIntoFields = processPragmasIntoFields;
        var namedArgRegExCache = ts.createMap();
        function getNamedArgRegEx(name) {
            if (namedArgRegExCache.has(name)) {
                return namedArgRegExCache.get(name);
            }
            var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
            namedArgRegExCache.set(name, result);
            return result;
        }
        var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
        var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
        function extractPragmas(pragmas, range, text) {
            var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
            if (tripleSlash) {
                var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
                var pragma = ts.commentPragmas[name];
                if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
                    return;
                }
                if (pragma.args) {
                    var argument = {};
                    for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
                        var arg = _a[_i];
                        var matcher = getNamedArgRegEx(arg.name);
                        var matchResult = matcher.exec(text);
                        if (!matchResult && !arg.optional) {
                            return; // Missing required argument, don't parse
                        }
                        else if (matchResult) {
                            if (arg.captureSpan) {
                                var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
                                argument[arg.name] = {
                                    value: matchResult[3],
                                    pos: startPos,
                                    end: startPos + matchResult[3].length
                                };
                            }
                            else {
                                argument[arg.name] = matchResult[3];
                            }
                        }
                    }
                    pragmas.push({ name: name, args: { arguments: argument, range: range } });
                }
                else {
                    pragmas.push({ name: name, args: { arguments: {}, range: range } });
                }
                return;
            }
            var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
            if (singleLine) {
                return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
            }
            if (range.kind === 3 /* MultiLineCommentTrivia */) {
                var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
                var multiLineMatch = void 0;
                while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
                    addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
                }
            }
        }
        function addPragmaForMatch(pragmas, range, kind, match) {
            if (!match)
                return;
            var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
            var pragma = ts.commentPragmas[name];
            if (!pragma || !(pragma.kind & kind)) {
                return;
            }
            var args = match[2]; // Split on spaces and match up positionally with definition
            var argument = getNamedPragmaArguments(pragma, args);
            if (argument === "fail")
                return; // Missing required argument, fail to parse it
            pragmas.push({ name: name, args: { arguments: argument, range: range } });
            return;
        }
        function getNamedPragmaArguments(pragma, text) {
            if (!text)
                return {};
            if (!pragma.args)
                return {};
            var args = text.split(/\s+/);
            var argMap = {};
            for (var i = 0; i < pragma.args.length; i++) {
                var argument = pragma.args[i];
                if (!args[i] && !argument.optional) {
                    return "fail";
                }
                if (argument.captureSpan) {
                    return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
                }
                argMap[argument.name] = args[i];
            }
            return argMap;
        }
        /** @internal */
        function tagNamesAreEquivalent(lhs, rhs) {
            if (lhs.kind !== rhs.kind) {
                return false;
            }
            if (lhs.kind === 71 /* Identifier */) {
                return lhs.escapedText === rhs.escapedText;
            }
            if (lhs.kind === 99 /* ThisKeyword */) {
                return true;
            }
            // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
            // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
            // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
            return lhs.name.escapedText === rhs.name.escapedText &&
                tagNamesAreEquivalent(lhs.expression, rhs.expression);
        }
        ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        /* @internal */
        ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
        // NOTE: The order here is important to default lib ordering as entries will have the same
        //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
        //       order also affects overload resolution when a type declared in one lib is
        //       augmented in another lib.
        var libEntries = [
            // JavaScript only
            ["es5", "lib.es5.d.ts"],
            ["es6", "lib.es2015.d.ts"],
            ["es2015", "lib.es2015.d.ts"],
            ["es7", "lib.es2016.d.ts"],
            ["es2016", "lib.es2016.d.ts"],
            ["es2017", "lib.es2017.d.ts"],
            ["es2018", "lib.es2018.d.ts"],
            ["esnext", "lib.esnext.d.ts"],
            // Host only
            ["dom", "lib.dom.d.ts"],
            ["dom.iterable", "lib.dom.iterable.d.ts"],
            ["webworker", "lib.webworker.d.ts"],
            ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
            ["scripthost", "lib.scripthost.d.ts"],
            // ES2015 Or ESNext By-feature options
            ["es2015.core", "lib.es2015.core.d.ts"],
            ["es2015.collection", "lib.es2015.collection.d.ts"],
            ["es2015.generator", "lib.es2015.generator.d.ts"],
            ["es2015.iterable", "lib.es2015.iterable.d.ts"],
            ["es2015.promise", "lib.es2015.promise.d.ts"],
            ["es2015.proxy", "lib.es2015.proxy.d.ts"],
            ["es2015.reflect", "lib.es2015.reflect.d.ts"],
            ["es2015.symbol", "lib.es2015.symbol.d.ts"],
            ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
            ["es2016.array.include", "lib.es2016.array.include.d.ts"],
            ["es2017.object", "lib.es2017.object.d.ts"],
            ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
            ["es2017.string", "lib.es2017.string.d.ts"],
            ["es2017.intl", "lib.es2017.intl.d.ts"],
            ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
            ["es2018.intl", "lib.es2018.intl.d.ts"],
            ["es2018.promise", "lib.es2018.promise.d.ts"],
            ["es2018.regexp", "lib.es2018.regexp.d.ts"],
            ["esnext.array", "lib.esnext.array.d.ts"],
            ["esnext.symbol", "lib.esnext.symbol.d.ts"],
            ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
            ["esnext.intl", "lib.esnext.intl.d.ts"]
        ];
        /**
         * An array of supported "lib" reference file names used to determine the order for inclusion
         * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
         * overload resolution when a type declared in one lib is extended by another.
         */
        /* @internal */
        ts.libs = libEntries.map(function (entry) { return entry[0]; });
        /**
         * A map of lib names to lib files. This map is used both for parsing the "lib" command line
         * option as well as for resolving lib reference directives.
         */
        /* @internal */
        ts.libMap = ts.createMapFromEntries(libEntries);
        /* @internal */
        ts.commonOptionsWithBuild = [
            {
                name: "help",
                shortName: "h",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Print_this_message,
            },
            {
                name: "help",
                shortName: "?",
                type: "boolean"
            },
            {
                name: "watch",
                shortName: "w",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Watch_input_files,
            },
            {
                name: "preserveWatchOutput",
                type: "boolean",
                showInSimplifiedHelpView: false,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
            },
            {
                name: "listFiles",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
            },
            {
                name: "listEmittedFiles",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
            },
            {
                name: "traceResolution",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
            },
        ];
        /* @internal */
        ts.optionDeclarations = ts.commonOptionsWithBuild.concat([
            {
                name: "all",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Show_all_compiler_options,
            },
            {
                name: "version",
                shortName: "v",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Print_the_compiler_s_version,
            },
            {
                name: "init",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
            },
            {
                name: "project",
                shortName: "p",
                type: "string",
                isFilePath: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
                description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
            },
            {
                name: "build",
                type: "boolean",
                shortName: "b",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
            },
            {
                name: "pretty",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
            },
            // Basic
            {
                name: "target",
                shortName: "t",
                type: ts.createMapFromTemplate({
                    es3: 0 /* ES3 */,
                    es5: 1 /* ES5 */,
                    es6: 2 /* ES2015 */,
                    es2015: 2 /* ES2015 */,
                    es2016: 3 /* ES2016 */,
                    es2017: 4 /* ES2017 */,
                    es2018: 5 /* ES2018 */,
                    esnext: 6 /* ESNext */,
                }),
                affectsSourceFile: true,
                affectsModuleResolution: true,
                paramType: ts.Diagnostics.VERSION,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
            },
            {
                name: "module",
                shortName: "m",
                type: ts.createMapFromTemplate({
                    none: ts.ModuleKind.None,
                    commonjs: ts.ModuleKind.CommonJS,
                    amd: ts.ModuleKind.AMD,
                    system: ts.ModuleKind.System,
                    umd: ts.ModuleKind.UMD,
                    es6: ts.ModuleKind.ES2015,
                    es2015: ts.ModuleKind.ES2015,
                    esnext: ts.ModuleKind.ESNext
                }),
                affectsModuleResolution: true,
                paramType: ts.Diagnostics.KIND,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext,
            },
            {
                name: "lib",
                type: "list",
                element: {
                    name: "lib",
                    type: ts.libMap
                },
                affectsModuleResolution: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation
            },
            {
                name: "allowJs",
                type: "boolean",
                affectsModuleResolution: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
            },
            {
                name: "checkJs",
                type: "boolean",
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Report_errors_in_js_files
            },
            {
                name: "jsx",
                type: ts.createMapFromTemplate({
                    "preserve": 1 /* Preserve */,
                    "react-native": 3 /* ReactNative */,
                    "react": 2 /* React */
                }),
                affectsSourceFile: true,
                paramType: ts.Diagnostics.KIND,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
            },
            {
                name: "declaration",
                shortName: "d",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Generates_corresponding_d_ts_file,
            },
            {
                name: "declarationMap",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
            },
            {
                name: "emitDeclarationOnly",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
            },
            {
                name: "sourceMap",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Generates_corresponding_map_file,
            },
            {
                name: "outFile",
                type: "string",
                isFilePath: true,
                paramType: ts.Diagnostics.FILE,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
            },
            {
                name: "outDir",
                type: "string",
                isFilePath: true,
                paramType: ts.Diagnostics.DIRECTORY,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
            },
            {
                name: "rootDir",
                type: "string",
                isFilePath: true,
                paramType: ts.Diagnostics.LOCATION,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
            },
            {
                name: "composite",
                type: "boolean",
                isTSConfigOnly: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Enable_project_compilation,
            },
            {
                name: "removeComments",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Do_not_emit_comments_to_output,
            },
            {
                name: "noEmit",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Do_not_emit_outputs,
            },
            {
                name: "importHelpers",
                type: "boolean",
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Import_emit_helpers_from_tslib
            },
            {
                name: "downlevelIteration",
                type: "boolean",
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
            },
            {
                name: "isolatedModules",
                type: "boolean",
                category: ts.Diagnostics.Basic_Options,
                description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule
            },
            // Strict Type Checks
            {
                name: "strict",
                type: "boolean",
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Strict_Type_Checking_Options,
                description: ts.Diagnostics.Enable_all_strict_type_checking_options
            },
            {
                name: "noImplicitAny",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                strictFlag: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Strict_Type_Checking_Options,
                description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
            },
            {
                name: "strictNullChecks",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                strictFlag: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Strict_Type_Checking_Options,
                description: ts.Diagnostics.Enable_strict_null_checks
            },
            {
                name: "strictFunctionTypes",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                strictFlag: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Strict_Type_Checking_Options,
                description: ts.Diagnostics.Enable_strict_checking_of_function_types
            },
            {
                name: "strictPropertyInitialization",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                strictFlag: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Strict_Type_Checking_Options,
                description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
            },
            {
                name: "noImplicitThis",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                strictFlag: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Strict_Type_Checking_Options,
                description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
            },
            {
                name: "alwaysStrict",
                type: "boolean",
                affectsSourceFile: true,
                strictFlag: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Strict_Type_Checking_Options,
                description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
            },
            // Additional Checks
            {
                name: "noUnusedLocals",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Additional_Checks,
                description: ts.Diagnostics.Report_errors_on_unused_locals,
            },
            {
                name: "noUnusedParameters",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Additional_Checks,
                description: ts.Diagnostics.Report_errors_on_unused_parameters,
            },
            {
                name: "noImplicitReturns",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Additional_Checks,
                description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
            },
            {
                name: "noFallthroughCasesInSwitch",
                type: "boolean",
                affectsBindDiagnostics: true,
                affectsSemanticDiagnostics: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Additional_Checks,
                description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
            },
            // Module Resolution
            {
                name: "moduleResolution",
                type: ts.createMapFromTemplate({
                    node: ts.ModuleResolutionKind.NodeJs,
                    classic: ts.ModuleResolutionKind.Classic,
                }),
                affectsModuleResolution: true,
                paramType: ts.Diagnostics.STRATEGY,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
            },
            {
                name: "baseUrl",
                type: "string",
                affectsModuleResolution: true,
                isFilePath: true,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
            },
            {
                // this option can only be specified in tsconfig.json
                // use type = object to copy the value as-is
                name: "paths",
                type: "object",
                affectsModuleResolution: true,
                isTSConfigOnly: true,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl
            },
            {
                // this option can only be specified in tsconfig.json
                // use type = object to copy the value as-is
                name: "rootDirs",
                type: "list",
                isTSConfigOnly: true,
                element: {
                    name: "rootDirs",
                    type: "string",
                    isFilePath: true
                },
                affectsModuleResolution: true,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime
            },
            {
                name: "typeRoots",
                type: "list",
                element: {
                    name: "typeRoots",
                    type: "string",
                    isFilePath: true
                },
                affectsModuleResolution: true,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
            },
            {
                name: "types",
                type: "list",
                element: {
                    name: "types",
                    type: "string"
                },
                affectsModuleResolution: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation
            },
            {
                name: "allowSyntheticDefaultImports",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
            },
            {
                name: "esModuleInterop",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                showInSimplifiedHelpView: true,
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
            },
            {
                name: "preserveSymlinks",
                type: "boolean",
                category: ts.Diagnostics.Module_Resolution_Options,
                description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
            },
            // Source Maps
            {
                name: "sourceRoot",
                type: "string",
                paramType: ts.Diagnostics.LOCATION,
                category: ts.Diagnostics.Source_Map_Options,
                description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
            },
            {
                name: "mapRoot",
                type: "string",
                paramType: ts.Diagnostics.LOCATION,
                category: ts.Diagnostics.Source_Map_Options,
                description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
            },
            {
                name: "inlineSourceMap",
                type: "boolean",
                category: ts.Diagnostics.Source_Map_Options,
                description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
            },
            {
                name: "inlineSources",
                type: "boolean",
                category: ts.Diagnostics.Source_Map_Options,
                description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
            },
            // Experimental
            {
                name: "experimentalDecorators",
                type: "boolean",
                category: ts.Diagnostics.Experimental_Options,
                description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
            },
            {
                name: "emitDecoratorMetadata",
                type: "boolean",
                category: ts.Diagnostics.Experimental_Options,
                description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
            },
            // Advanced
            {
                name: "jsxFactory",
                type: "string",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
            },
            {
                name: "diagnostics",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Show_diagnostic_information
            },
            {
                name: "extendedDiagnostics",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Show_verbose_diagnostic_information
            },
            {
                name: "resolveJsonModule",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Include_modules_imported_with_json_extension
            },
            {
                name: "out",
                type: "string",
                isFilePath: false,
                // for correct behaviour, please use outFile
                category: ts.Diagnostics.Advanced_Options,
                paramType: ts.Diagnostics.FILE,
                description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
            },
            {
                name: "reactNamespace",
                type: "string",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
            },
            {
                name: "skipDefaultLibCheck",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
            },
            {
                name: "charset",
                type: "string",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.The_character_set_of_the_input_files
            },
            {
                name: "emitBOM",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
            },
            {
                name: "locale",
                type: "string",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
            },
            {
                name: "newLine",
                type: ts.createMapFromTemplate({
                    crlf: 0 /* CarriageReturnLineFeed */,
                    lf: 1 /* LineFeed */
                }),
                paramType: ts.Diagnostics.NEWLINE,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
            },
            {
                name: "noErrorTruncation",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_truncate_error_messages
            },
            {
                name: "noLib",
                type: "boolean",
                affectsModuleResolution: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts
            },
            {
                name: "noResolve",
                type: "boolean",
                affectsModuleResolution: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files
            },
            {
                name: "stripInternal",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
            },
            {
                name: "disableSizeLimit",
                type: "boolean",
                affectsSourceFile: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
            },
            {
                name: "noImplicitUseStrict",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
            },
            {
                name: "noEmitHelpers",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
            },
            {
                name: "noEmitOnError",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
            },
            {
                name: "preserveConstEnums",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
            },
            {
                name: "declarationDir",
                type: "string",
                isFilePath: true,
                paramType: ts.Diagnostics.DIRECTORY,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Output_directory_for_generated_declaration_files
            },
            {
                name: "skipLibCheck",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
            },
            {
                name: "allowUnusedLabels",
                type: "boolean",
                affectsBindDiagnostics: true,
                affectsSemanticDiagnostics: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
            },
            {
                name: "allowUnreachableCode",
                type: "boolean",
                affectsBindDiagnostics: true,
                affectsSemanticDiagnostics: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
            },
            {
                name: "suppressExcessPropertyErrors",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
            },
            {
                name: "suppressImplicitAnyIndexErrors",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
            },
            {
                name: "forceConsistentCasingInFileNames",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
            },
            {
                name: "maxNodeModuleJsDepth",
                type: "number",
                // TODO: GH#27108 affectsModuleResolution: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
            },
            {
                name: "noStrictGenericChecks",
                type: "boolean",
                affectsSemanticDiagnostics: true,
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
            },
            {
                name: "keyofStringsOnly",
                type: "boolean",
                category: ts.Diagnostics.Advanced_Options,
                description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
            },
            {
                // A list of plugins to load in the language service
                name: "plugins",
                type: "list",
                isTSConfigOnly: true,
                element: {
                    name: "plugin",
                    type: "object"
                },
                description: ts.Diagnostics.List_of_language_service_plugins
            }
        ]);
        /* @internal */
        ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
        /* @internal */
        ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
        /* @internal */
        ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
            return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
        });
        /* @internal */
        ts.buildOpts = ts.commonOptionsWithBuild.concat([
            {
                name: "verbose",
                shortName: "v",
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Enable_verbose_logging,
                type: "boolean"
            },
            {
                name: "dry",
                shortName: "d",
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
                type: "boolean"
            },
            {
                name: "force",
                shortName: "f",
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
                type: "boolean"
            },
            {
                name: "clean",
                category: ts.Diagnostics.Command_line_Options,
                description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
                type: "boolean"
            }
        ]);
        /* @internal */
        ts.typeAcquisitionDeclarations = [
            {
                /* @deprecated typingOptions.enableAutoDiscovery
                 * Use typeAcquisition.enable instead.
                 */
                name: "enableAutoDiscovery",
                type: "boolean",
            },
            {
                name: "enable",
                type: "boolean",
            },
            {
                name: "include",
                type: "list",
                element: {
                    name: "include",
                    type: "string"
                }
            },
            {
                name: "exclude",
                type: "list",
                element: {
                    name: "exclude",
                    type: "string"
                }
            }
        ];
        /* @internal */
        ts.defaultInitCompilerOptions = {
            module: ts.ModuleKind.CommonJS,
            target: 1 /* ES5 */,
            strict: true,
            esModuleInterop: true
        };
        var optionNameMapCache;
        /* @internal */
        function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
            // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
            if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
                return {
                    enable: typeAcquisition.enableAutoDiscovery,
                    include: typeAcquisition.include || [],
                    exclude: typeAcquisition.exclude || []
                };
            }
            return typeAcquisition;
        }
        ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
        function getOptionNameMap() {
            return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations));
        }
        /*@internal*/
        function createOptionNameMap(optionDeclarations) {
            var optionNameMap = ts.createMap();
            var shortOptionNames = ts.createMap();
            ts.forEach(optionDeclarations, function (option) {
                optionNameMap.set(option.name.toLowerCase(), option);
                if (option.shortName) {
                    shortOptionNames.set(option.shortName, option.name);
                }
            });
            return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames };
        }
        ts.createOptionNameMap = createOptionNameMap;
        /* @internal */
        function createCompilerDiagnosticForInvalidCustomType(opt) {
            return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
        }
        ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
        function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
            var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
            return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
        }
        /* @internal */
        function parseCustomTypeOption(opt, value, errors) {
            return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
        }
        ts.parseCustomTypeOption = parseCustomTypeOption;
        /* @internal */
        function parseListTypeOption(opt, value, errors) {
            if (value === void 0) {
                value = "";
            }
            value = trimString(value);
            if (ts.startsWith(value, "-")) {
                return undefined;
            }
            if (value === "") {
                return [];
            }
            var values = value.split(",");
            switch (opt.element.type) {
                case "number":
                    return ts.map(values, parseInt);
                case "string":
                    return ts.map(values, function (v) { return v || ""; });
                default:
                    return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
            }
        }
        ts.parseListTypeOption = parseListTypeOption;
        function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) {
            var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1];
            var options = {};
            var fileNames = [];
            var errors = [];
            parseStrings(commandLine);
            return {
                options: options,
                fileNames: fileNames,
                errors: errors
            };
            function parseStrings(args) {
                var i = 0;
                while (i < args.length) {
                    var s = args[i];
                    i++;
                    if (s.charCodeAt(0) === 64 /* at */) {
                        parseResponseFile(s.slice(1));
                    }
                    else if (s.charCodeAt(0) === 45 /* minus */) {
                        var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true);
                        if (opt) {
                            if (opt.isTSConfigOnly) {
                                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name));
                            }
                            else {
                                // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
                                if (!args[i] && opt.type !== "boolean") {
                                    errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name));
                                }
                                switch (opt.type) {
                                    case "number":
                                        options[opt.name] = parseInt(args[i]);
                                        i++;
                                        break;
                                    case "boolean":
                                        // boolean flag has optional value true, false, others
                                        var optValue = args[i];
                                        options[opt.name] = optValue !== "false";
                                        // consume next argument as boolean flag value
                                        if (optValue === "false" || optValue === "true") {
                                            i++;
                                        }
                                        break;
                                    case "string":
                                        options[opt.name] = args[i] || "";
                                        i++;
                                        break;
                                    case "list":
                                        var result = parseListTypeOption(opt, args[i], errors); // tslint:disable-line no-unnecessary-type-assertion
                                        options[opt.name] = result || [];
                                        if (result) {
                                            i++;
                                        }
                                        break;
                                    // If not a primitive, the possible types are specified in what is effectively a map of options.
                                    default:
                                        options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
                                        i++;
                                        break;
                                }
                            }
                        }
                        else {
                            errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s));
                        }
                    }
                    else {
                        fileNames.push(s);
                    }
                }
            }
            function parseResponseFile(fileName) {
                var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName);
                if (!text) {
                    errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName));
                    return;
                }
                var args = [];
                var pos = 0;
                while (true) {
                    while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
                        pos++;
                    if (pos >= text.length)
                        break;
                    var start = pos;
                    if (text.charCodeAt(start) === 34 /* doubleQuote */) {
                        pos++;
                        while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
                            pos++;
                        if (pos < text.length) {
                            args.push(text.substring(start + 1, pos));
                            pos++;
                        }
                        else {
                            errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
                        }
                    }
                    else {
                        while (text.charCodeAt(pos) > 32 /* space */)
                            pos++;
                        args.push(text.substring(start, pos));
                    }
                }
                parseStrings(args);
            }
        }
        function parseCommandLine(commandLine, readFile) {
            return parseCommandLineWorker(getOptionNameMap, [
                ts.Diagnostics.Unknown_compiler_option_0,
                ts.Diagnostics.Compiler_option_0_expects_an_argument
            ], commandLine, readFile);
        }
        ts.parseCommandLine = parseCommandLine;
        /** @internal */
        function getOptionFromName(optionName, allowShort) {
            return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort);
        }
        ts.getOptionFromName = getOptionFromName;
        function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
            if (allowShort === void 0) {
                allowShort = false;
            }
            optionName = optionName.toLowerCase();
            var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames;
            // Try to translate short option names to their full equivalents.
            if (allowShort) {
                var short = shortOptionNames.get(optionName);
                if (short !== undefined) {
                    optionName = short;
                }
            }
            return optionNameMap.get(optionName);
        }
        /*@internal*/
        function parseBuildCommand(args) {
            var buildOptionNameMap;
            var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); };
            var _a = parseCommandLineWorker(returnBuildOptionNameMap, [
                ts.Diagnostics.Unknown_build_option_0,
                ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
            ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors;
            var buildOptions = options;
            if (projects.length === 0) {
                // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
                projects.push(".");
            }
            // Nonsensical combinations
            if (buildOptions.clean && buildOptions.force) {
                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
            }
            if (buildOptions.clean && buildOptions.verbose) {
                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
            }
            if (buildOptions.clean && buildOptions.watch) {
                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
            }
            if (buildOptions.watch && buildOptions.dry) {
                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
            }
            return { buildOptions: buildOptions, projects: projects, errors: errors };
        }
        ts.parseBuildCommand = parseBuildCommand;
        function getDiagnosticText(_message) {
            var _args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                _args[_i - 1] = arguments[_i];
            }
            var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
            return diagnostic.messageText;
        }
        /* @internal */
        function printVersion() {
            ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine);
        }
        ts.printVersion = printVersion;
        /* @internal */
        function printHelp(optionsList, syntaxPrefix) {
            if (syntaxPrefix === void 0) {
                syntaxPrefix = "";
            }
            var output = [];
            // We want to align our "syntax" and "examples" commands to a certain margin.
            var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length;
            var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length;
            var marginLength = Math.max(syntaxLength, examplesLength);
            // Build up the syntactic skeleton.
            var syntax = makePadding(marginLength - syntaxLength);
            syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]";
            output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax));
            output.push(ts.sys.newLine + ts.sys.newLine);
            // Build up the list of examples.
            var padding = makePadding(marginLength);
            output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine);
            output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine);
            output.push(padding + "tsc @args.txt" + ts.sys.newLine);
            output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine);
            output.push(ts.sys.newLine);
            output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine);
            // We want our descriptions to align at the same column in our output,
            // so we keep track of the longest option usage string.
            marginLength = 0;
            var usageColumn = []; // Things like "-d, --declaration" go in here.
            var descriptionColumn = [];
            var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind
            for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) {
                var option = optionsList_1[_i];
                // If an option lacks a description,
                // it is not officially supported.
                if (!option.description) {
                    continue;
                }
                var usageText_1 = " ";
                if (option.shortName) {
                    usageText_1 += "-" + option.shortName;
                    usageText_1 += getParamType(option);
                    usageText_1 += ", ";
                }
                usageText_1 += "--" + option.name;
                usageText_1 += getParamType(option);
                usageColumn.push(usageText_1);
                var description = void 0;
                if (option.name === "lib") {
                    description = getDiagnosticText(option.description);
                    var element = option.element;
                    var typeMap = element.type;
                    optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; }));
                }
                else {
                    description = getDiagnosticText(option.description);
                }
                descriptionColumn.push(description);
                // Set the new margin for the description column if necessary.
                marginLength = Math.max(usageText_1.length, marginLength);
            }
            // Special case that can't fit in the loop.
            var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">";
            usageColumn.push(usageText);
            descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file));
            marginLength = Math.max(usageText.length, marginLength);
            // Print out each row, aligning all the descriptions on the same column.
            for (var i = 0; i < usageColumn.length; i++) {
                var usage = usageColumn[i];
                var description = descriptionColumn[i];
                var kindsList = optionsDescriptionMap.get(description);
                output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine);
                if (kindsList) {
                    output.push(makePadding(marginLength + 4));
                    for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) {
                        var kind = kindsList_1[_a];
                        output.push(kind + " ");
                    }
                    output.push(ts.sys.newLine);
                }
            }
            for (var _b = 0, output_1 = output; _b < output_1.length; _b++) {
                var line = output_1[_b];
                ts.sys.write(line);
            }
            return;
            function getParamType(option) {
                if (option.paramType !== undefined) {
                    return " " + getDiagnosticText(option.paramType);
                }
                return "";
            }
            function makePadding(paddingLength) {
                return Array(paddingLength + 1).join(" ");
            }
        }
        ts.printHelp = printHelp;
        /**
         * Reads the config file, reports errors if any and exits if the config file cannot be found
         */
        function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
            var configFileText;
            try {
                configFileText = host.readFile(configFileName);
            }
            catch (e) {
                var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
                host.onUnRecoverableConfigFileDiagnostic(error);
                return undefined;
            }
            if (!configFileText) {
                var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
                host.onUnRecoverableConfigFileDiagnostic(error);
                return undefined;
            }
            var result = ts.parseJsonText(configFileName, configFileText);
            var cwd = host.getCurrentDirectory();
            return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
        }
        ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
        /**
         * Read tsconfig.json file
         * @param fileName The path to the config file
         */
        function readConfigFile(fileName, readFile) {
            var textOrDiagnostic = tryReadFile(fileName, readFile);
            return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
        }
        ts.readConfigFile = readConfigFile;
        /**
         * Parse the text of the tsconfig.json file
         * @param fileName The path to the config file
         * @param jsonText The text of the config file
         */
        function parseConfigFileTextToJson(fileName, jsonText) {
            var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
            return {
                config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
                error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
            };
        }
        ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
        /**
         * Read tsconfig.json file
         * @param fileName The path to the config file
         */
        function readJsonConfigFile(fileName, readFile) {
            var textOrDiagnostic = tryReadFile(fileName, readFile);
            return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
        }
        ts.readJsonConfigFile = readJsonConfigFile;
        function tryReadFile(fileName, readFile) {
            var text;
            try {
                text = readFile(fileName);
            }
            catch (e) {
                return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
            }
            return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text;
        }
        function commandLineOptionsToMap(options) {
            return ts.arrayToMap(options, function (option) { return option.name; });
        }
        var _tsconfigRootOptions;
        function getTsconfigRootOptionsMap() {
            if (_tsconfigRootOptions === undefined) {
                _tsconfigRootOptions = {
                    name: undefined,
                    type: "object",
                    elementOptions: commandLineOptionsToMap([
                        {
                            name: "compilerOptions",
                            type: "object",
                            elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
                            extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
                        },
                        {
                            name: "typingOptions",
                            type: "object",
                            elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
                            extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
                        },
                        {
                            name: "typeAcquisition",
                            type: "object",
                            elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
                            extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
                        },
                        {
                            name: "extends",
                            type: "string"
                        },
                        {
                            name: "references",
                            type: "list",
                            element: {
                                name: "references",
                                type: "object"
                            }
                        },
                        {
                            name: "files",
                            type: "list",
                            element: {
                                name: "files",
                                type: "string"
                            }
                        },
                        {
                            name: "include",
                            type: "list",
                            element: {
                                name: "include",
                                type: "string"
                            }
                        },
                        {
                            name: "exclude",
                            type: "list",
                            element: {
                                name: "exclude",
                                type: "string"
                            }
                        },
                        ts.compileOnSaveCommandLineOption
                    ])
                };
            }
            return _tsconfigRootOptions;
        }
        /**
         * Convert the json syntax tree into the json value
         */
        function convertToObject(sourceFile, errors) {
            return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
        }
        ts.convertToObject = convertToObject;
        /**
         * Convert the json syntax tree into the json value and report errors
         * This returns the json value (apart from checking errors) only if returnValue provided is true.
         * Otherwise it just checks the errors and returns undefined
         */
        /*@internal*/
        function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
            if (!sourceFile.statements.length) {
                return returnValue ? {} : undefined;
            }
            return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
            function isRootOptionMap(knownOptions) {
                return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
            }
            function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
                var result = returnValue ? {} : undefined;
                for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
                    var element = _a[_i];
                    if (element.kind !== 273 /* PropertyAssignment */) {
                        errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
                        continue;
                    }
                    if (element.questionToken) {
                        errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
                    }
                    if (!isDoubleQuotedString(element.name)) {
                        errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
                    }
                    var textOfKey = ts.getTextOfPropertyName(element.name);
                    var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
                    var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
                    if (keyText && extraKeyDiagnosticMessage && !option) {
                        errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText));
                    }
                    var value = convertPropertyValueToJson(element.initializer, option);
                    if (typeof keyText !== "undefined") {
                        if (returnValue) {
                            result[keyText] = value;
                        }
                        // Notify key value set, if user asked for it
                        if (jsonConversionNotifier &&
                            // Current callbacks are only on known parent option or if we are setting values in the root
                            (parentOption || isRootOptionMap(knownOptions))) {
                            var isValidOptionValue = isCompilerOptionsValue(option, value);
                            if (parentOption) {
                                if (isValidOptionValue) {
                                    // Notify option set in the parent if its a valid option value
                                    jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
                                }
                            }
                            else if (isRootOptionMap(knownOptions)) {
                                if (isValidOptionValue) {
                                    // Notify about the valid root key value being set
                                    jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
                                }
                                else if (!option) {
                                    // Notify about the unknown root key value being set
                                    jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
                                }
                            }
                        }
                    }
                }
                return result;
            }
            function convertArrayLiteralExpressionToJson(elements, elementOption) {
                return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); });
            }
            function convertPropertyValueToJson(valueExpression, option) {
                switch (valueExpression.kind) {
                    case 101 /* TrueKeyword */:
                        reportInvalidOptionValue(option && option.type !== "boolean");
                        return true;
                    case 86 /* FalseKeyword */:
                        reportInvalidOptionValue(option && option.type !== "boolean");
                        return false;
                    case 95 /* NullKeyword */:
                        reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
                        return null; // tslint:disable-line:no-null-keyword
                    case 9 /* StringLiteral */:
                        if (!isDoubleQuotedString(valueExpression)) {
                            errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
                        }
                        reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
                        var text = valueExpression.text;
                        if (option && !ts.isString(option.type)) {
                            var customOption = option;
                            // Validate custom option type
                            if (!customOption.type.has(text.toLowerCase())) {
                                errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
                            }
                        }
                        return text;
                    case 8 /* NumericLiteral */:
                        reportInvalidOptionValue(option && option.type !== "number");
                        return Number(valueExpression.text);
                    case 200 /* PrefixUnaryExpression */:
                        if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
                            break; // not valid JSON syntax
                        }
                        reportInvalidOptionValue(option && option.type !== "number");
                        return -Number(valueExpression.operand.text);
                    case 186 /* ObjectLiteralExpression */:
                        reportInvalidOptionValue(option && option.type !== "object");
                        var objectLiteralExpression = valueExpression;
                        // Currently having element option declaration in the tsconfig with type "object"
                        // determines if it needs onSetValidOptionKeyValueInParent callback or not
                        // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
                        // that satifies it and need it to modify options set in them (for normalizing file paths)
                        // vs what we set in the json
                        // If need arises, we can modify this interface and callbacks as needed
                        if (option) {
                            var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name;
                            return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName);
                        }
                        else {
                            return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
                            /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
                        }
                    case 185 /* ArrayLiteralExpression */:
                        reportInvalidOptionValue(option && option.type !== "list");
                        return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
                }
                // Not in expected format
                if (option) {
                    reportInvalidOptionValue(/*isError*/ true);
                }
                else {
                    errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal));
                }
                return undefined;
                function reportInvalidOptionValue(isError) {
                    if (isError) {
                        errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
                    }
                }
            }
            function isDoubleQuotedString(node) {
                return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
            }
        }
        ts.convertToObjectWorker = convertToObjectWorker;
        function getCompilerOptionValueTypeString(option) {
            return option.type === "list" ?
                "Array" :
                ts.isString(option.type) ? option.type : "string";
        }
        function isCompilerOptionsValue(option, value) {
            if (option) {
                if (isNullOrUndefined(value))
                    return true; // All options are undefinable/nullable
                if (option.type === "list") {
                    return ts.isArray(value);
                }
                var expectedType = ts.isString(option.type) ? option.type : "string";
                return typeof value === expectedType;
            }
            return false;
        }
        /**
         * Generate tsconfig configuration when running command line "--init"
         * @param options commandlineOptions to be generated into tsconfig.json
         * @param fileNames array of filenames to be generated into tsconfig.json
         */
        /* @internal */
        function generateTSConfig(options, fileNames, newLine) {
            var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
            var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
            return writeConfigurations();
            function getCustomTypeMapOfCommandLineOption(optionDefinition) {
                if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
                    // this is of a type CommandLineOptionOfPrimitiveType
                    return undefined;
                }
                else if (optionDefinition.type === "list") {
                    return getCustomTypeMapOfCommandLineOption(optionDefinition.element); // tslint:disable-line no-unnecessary-type-assertion
                }
                else {
                    return optionDefinition.type;
                }
            }
            function getNameOfCompilerOptionValue(value, customTypeMap) {
                // There is a typeMap associated with this command-line option so use it to map value back to its name
                return ts.forEachEntry(customTypeMap, function (mapValue, key) {
                    if (mapValue === value) {
                        return key;
                    }
                });
            }
            function serializeCompilerOptions(options) {
                var result = ts.createMap();
                var optionsNameMap = getOptionNameMap().optionNameMap;
                var _loop_3 = function (name) {
                    if (ts.hasProperty(options, name)) {
                        // tsconfig only options cannot be specified via command line,
                        // so we can assume that only types that can appear here string | number | boolean
                        if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
                            return "continue";
                        }
                        var value = options[name];
                        var optionDefinition = optionsNameMap.get(name.toLowerCase());
                        if (optionDefinition) {
                            var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
                            if (!customTypeMap_1) {
                                // There is no map associated with this compiler option then use the value as-is
                                // This is the case if the value is expect to be string, number, boolean or list of string
                                result.set(name, value);
                            }
                            else {
                                if (optionDefinition.type === "list") {
                                    result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
                                }
                                else {
                                    // There is a typeMap associated with this command-line option so use it to map value back to its name
                                    result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
                                }
                            }
                        }
                    }
                };
                for (var name in options) {
                    _loop_3(name);
                }
                return result;
            }
            function getDefaultValueForOption(option) {
                switch (option.type) {
                    case "number":
                        return 1;
                    case "boolean":
                        return true;
                    case "string":
                        return option.isFilePath ? "./" : "";
                    case "list":
                        return [];
                    case "object":
                        return {};
                    default:
                        return option.type.keys().next().value; // tslint:disable-line no-unnecessary-type-assertion
                }
            }
            function makePadding(paddingLength) {
                return Array(paddingLength + 1).join(" ");
            }
            function isAllowedOption(_a) {
                var category = _a.category, name = _a.name;
                // Skip options which do not have a category or have category `Command_line_Options`
                // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
                return category !== undefined
                    && category !== ts.Diagnostics.Command_line_Options
                    && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
            }
            function writeConfigurations() {
                // Filter applicable options to place in the file
                var categorizedOptions = ts.createMultiMap();
                for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
                    var option = optionDeclarations_1[_i];
                    var category = option.category;
                    if (isAllowedOption(option)) {
                        categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
                    }
                }
                // Serialize all options and their descriptions
                var marginLength = 0;
                var seenKnownKeys = 0;
                var nameColumn = [];
                var descriptionColumn = [];
                categorizedOptions.forEach(function (options, category) {
                    if (nameColumn.length !== 0) {
                        nameColumn.push("");
                        descriptionColumn.push("");
                    }
                    nameColumn.push("/* " + category + " */");
                    descriptionColumn.push("");
                    for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
                        var option = options_1[_i];
                        var optionName = void 0;
                        if (compilerOptionsMap.has(option.name)) {
                            optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
                        }
                        else {
                            optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
                        }
                        nameColumn.push(optionName);
                        descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */");
                        marginLength = Math.max(optionName.length, marginLength);
                    }
                });
                // Write the output
                var tab = makePadding(2);
                var result = [];
                result.push("{");
                result.push(tab + "\"compilerOptions\": {");
                // Print out each row, aligning all the descriptions on the same column.
                for (var i = 0; i < nameColumn.length; i++) {
                    var optionName = nameColumn[i];
                    var description = descriptionColumn[i];
                    result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description)));
                }
                if (fileNames.length) {
                    result.push(tab + "},");
                    result.push(tab + "\"files\": [");
                    for (var i = 0; i < fileNames.length; i++) {
                        result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
                    }
                    result.push(tab + "]");
                }
                else {
                    result.push(tab + "}");
                }
                result.push("}");
                return result.join(newLine);
            }
        }
        ts.generateTSConfig = generateTSConfig;
        /**
         * Parse the contents of a config file (tsconfig.json).
         * @param json The contents of the config file to parse
         * @param host Instance of ParseConfigHost used to enumerate files in folder.
         * @param basePath A root directory to resolve relative path entries in the config
         *    file to. e.g. outDir
         */
        function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
            return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
        }
        ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
        /**
         * Parse the contents of a config file (tsconfig.json).
         * @param jsonNode The contents of the config file to parse
         * @param host Instance of ParseConfigHost used to enumerate files in folder.
         * @param basePath A root directory to resolve relative path entries in the config
         *    file to. e.g. outDir
         */
        function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
            return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
        }
        ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
        /*@internal*/
        function setConfigFileInOptions(options, configFile) {
            if (configFile) {
                Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
            }
        }
        ts.setConfigFileInOptions = setConfigFileInOptions;
        function isNullOrUndefined(x) {
            // tslint:disable-next-line:no-null-keyword
            return x === undefined || x === null;
        }
        function directoryOfCombinedPath(fileName, basePath) {
            // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
            // until consistient casing errors are reported
            return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
        }
        /**
         * Parse the contents of a config file from json or json source file (tsconfig.json).
         * @param json The contents of the config file to parse
         * @param sourceFile sourceFile corresponding to the Json
         * @param host Instance of ParseConfigHost used to enumerate files in folder.
         * @param basePath A root directory to resolve relative path entries in the config
         *    file to. e.g. outDir
         * @param resolutionStack Only present for backwards-compatibility. Should be empty.
         */
        function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
            if (existingOptions === void 0) {
                existingOptions = {};
            }
            if (resolutionStack === void 0) {
                resolutionStack = [];
            }
            if (extraFileExtensions === void 0) {
                extraFileExtensions = [];
            }
            ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
            var errors = [];
            var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
            var raw = parsedConfig.raw;
            var options = ts.extend(existingOptions, parsedConfig.options || {});
            options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
            setConfigFileInOptions(options, sourceFile);
            var projectReferences;
            var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
            return {
                options: options,
                fileNames: fileNames,
                projectReferences: projectReferences,
                typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
                raw: raw,
                errors: errors,
                wildcardDirectories: wildcardDirectories,
                compileOnSave: !!raw.compileOnSave,
                configFileSpecs: spec
            };
            function getFileNames() {
                var filesSpecs;
                if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
                    if (ts.isArray(raw.files)) {
                        filesSpecs = raw.files;
                        var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
                        var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
                        if (filesSpecs.length === 0 && hasZeroOrNoReferences) {
                            if (sourceFile) {
                                var fileName = configFileName || "tsconfig.json";
                                var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
                                var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
                                var error = nodeValue
                                    ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
                                    : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
                                errors.push(error);
                            }
                            else {
                                createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
                            }
                        }
                    }
                    else {
                        createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
                    }
                }
                var includeSpecs;
                if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
                    if (ts.isArray(raw.include)) {
                        includeSpecs = raw.include;
                    }
                    else {
                        createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
                    }
                }
                var excludeSpecs;
                if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
                    if (ts.isArray(raw.exclude)) {
                        excludeSpecs = raw.exclude;
                    }
                    else {
                        createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
                    }
                }
                else if (raw.compilerOptions) {
                    var outDir = raw.compilerOptions.outDir;
                    var declarationDir = raw.compilerOptions.declarationDir;
                    if (outDir || declarationDir) {
                        excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
                    }
                }
                if (filesSpecs === undefined && includeSpecs === undefined) {
                    includeSpecs = ["**/*"];
                }
                var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
                if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) {
                    errors.push(getErrorForNoInputFiles(result.spec, configFileName));
                }
                if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
                    if (ts.isArray(raw.references)) {
                        for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
                            var ref = _a[_i];
                            if (typeof ref.path !== "string") {
                                createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
                            }
                            else {
                                (projectReferences || (projectReferences = [])).push({
                                    path: ts.getNormalizedAbsolutePath(ref.path, basePath),
                                    originalPath: ref.path,
                                    prepend: ref.prepend,
                                    circular: ref.circular
                                });
                            }
                        }
                    }
                    else {
                        createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
                    }
                }
                return result;
            }
            function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
                if (!sourceFile) {
                    errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
                }
            }
        }
        /*@internal*/
        function isErrorNoInputFiles(error) {
            return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
        }
        ts.isErrorNoInputFiles = isErrorNoInputFiles;
        /*@internal*/
        function getErrorForNoInputFiles(_a, configFileName) {
            var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
            return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []));
        }
        ts.getErrorForNoInputFiles = getErrorForNoInputFiles;
        function isSuccessfulParsedTsconfig(value) {
            return !!value.options;
        }
        /**
         * This *just* extracts options/include/exclude/files out of a config file.
         * It does *not* resolve the included files.
         */
        function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) {
            basePath = ts.normalizeSlashes(basePath);
            var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
            if (resolutionStack.indexOf(resolvedPath) >= 0) {
                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> ")));
                return { raw: json || convertToObject(sourceFile, errors) };
            }
            var ownConfig = json ?
                parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
                parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
            if (ownConfig.extendedConfigPath) {
                // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
                resolutionStack = resolutionStack.concat([resolvedPath]);
                var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors);
                if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
                    var baseRaw_1 = extendedConfig.raw;
                    var raw_1 = ownConfig.raw;
                    var setPropertyInRawIfNotUndefined = function (propertyName) {
                        var value = raw_1[propertyName] || baseRaw_1[propertyName];
                        if (value) {
                            raw_1[propertyName] = value;
                        }
                    };
                    setPropertyInRawIfNotUndefined("include");
                    setPropertyInRawIfNotUndefined("exclude");
                    setPropertyInRawIfNotUndefined("files");
                    if (raw_1.compileOnSave === undefined) {
                        raw_1.compileOnSave = baseRaw_1.compileOnSave;
                    }
                    ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
                    // TODO extend type typeAcquisition
                }
            }
            return ownConfig;
        }
        function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
            if (ts.hasProperty(json, "excludes")) {
                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
            }
            var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
            // typingOptions has been deprecated and is only supported for backward compatibility purposes.
            // It should be removed in future releases - use typeAcquisition instead.
            var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
            json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
            var extendedConfigPath;
            if (json.extends) {
                if (!ts.isString(json.extends)) {
                    errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
                }
                else {
                    var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
                    extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
                }
            }
            return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
        }
        function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
            var options = getDefaultCompilerOptions(configFileName);
            var typeAcquisition, typingOptionstypeAcquisition;
            var extendedConfigPath;
            var optionsIterator = {
                onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
                    ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions");
                    var currentOption = parentOption === "compilerOptions" ?
                        options :
                        parentOption === "typeAcquisition" ?
                            (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) :
                            (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
                    currentOption[option.name] = normalizeOptionValue(option, basePath, value);
                },
                onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
                    switch (key) {
                        case "extends":
                            var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
                            extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
                                return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
                            });
                            return;
                    }
                },
                onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
                    if (key === "excludes") {
                        errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
                    }
                }
            };
            var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
            if (!typeAcquisition) {
                if (typingOptionstypeAcquisition) {
                    typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
                        {
                            enable: typingOptionstypeAcquisition.enableAutoDiscovery,
                            include: typingOptionstypeAcquisition.include,
                            exclude: typingOptionstypeAcquisition.exclude
                        } :
                        typingOptionstypeAcquisition;
                }
                else {
                    typeAcquisition = getDefaultTypeAcquisition(configFileName);
                }
            }
            return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
        }
        function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
            extendedConfig = ts.normalizeSlashes(extendedConfig);
            // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future)
            if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) {
                errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig));
                return undefined;
            }
            var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
            if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
                extendedConfigPath = extendedConfigPath + ".json";
                if (!host.fileExists(extendedConfigPath)) {
                    errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig));
                    return undefined;
                }
            }
            return extendedConfigPath;
        }
        function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
            var _a;
            var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
            if (sourceFile) {
                sourceFile.extendedSourceFiles = [extendedResult.fileName];
            }
            if (extendedResult.parseDiagnostics.length) {
                errors.push.apply(errors, extendedResult.parseDiagnostics);
                return undefined;
            }
            var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
            var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors);
            if (sourceFile && extendedResult.extendedSourceFiles) {
                (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
            }
            if (isSuccessfulParsedTsconfig(extendedConfig)) {
                // Update the paths to reflect base path
                var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
                var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
                var mapPropertiesInRawIfNotUndefined = function (propertyName) {
                    if (raw_2[propertyName]) {
                        raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
                    }
                };
                var raw_2 = extendedConfig.raw;
                mapPropertiesInRawIfNotUndefined("include");
                mapPropertiesInRawIfNotUndefined("exclude");
                mapPropertiesInRawIfNotUndefined("files");
            }
            return extendedConfig;
        }
        function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
            if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
                return false;
            }
            var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
            return typeof result === "boolean" && result;
        }
        function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
            var errors = [];
            var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
            return { options: options, errors: errors };
        }
        ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
        function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
            var errors = [];
            var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
            return { options: options, errors: errors };
        }
        ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
        function getDefaultCompilerOptions(configFileName) {
            var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
                ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
                : {};
            return options;
        }
        function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
            var options = getDefaultCompilerOptions(configFileName);
            convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
            if (configFileName) {
                options.configFilePath = ts.normalizeSlashes(configFileName);
            }
            return options;
        }
        function getDefaultTypeAcquisition(configFileName) {
            return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
        }
        function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
            var options = getDefaultTypeAcquisition(configFileName);
            var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
            convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors);
            return options;
        }
        function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) {
            if (!jsonOptions) {
                return;
            }
            var optionNameMap = commandLineOptionsToMap(optionDeclarations);
            for (var id in jsonOptions) {
                var opt = optionNameMap.get(id);
                if (opt) {
                    defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
                }
                else {
                    errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id));
                }
            }
        }
        function convertJsonOption(opt, value, basePath, errors) {
            if (isCompilerOptionsValue(opt, value)) {
                var optType = opt.type;
                if (optType === "list" && ts.isArray(value)) {
                    return convertJsonOptionOfListType(opt, value, basePath, errors);
                }
                else if (!ts.isString(optType)) {
                    return convertJsonOptionOfCustomType(opt, value, errors);
                }
                return normalizeNonListOptionValue(opt, basePath, value);
            }
            else {
                errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
            }
        }
        function normalizeOptionValue(option, basePath, value) {
            if (isNullOrUndefined(value))
                return undefined;
            if (option.type === "list") {
                var listOption_1 = option; // tslint:disable-line no-unnecessary-type-assertion
                if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
                    return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
                }
                return value;
            }
            else if (!ts.isString(option.type)) {
                return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
            }
            return normalizeNonListOptionValue(option, basePath, value);
        }
        function normalizeNonListOptionValue(option, basePath, value) {
            if (option.isFilePath) {
                value = ts.normalizePath(ts.combinePaths(basePath, value));
                if (value === "") {
                    value = ".";
                }
            }
            return value;
        }
        function convertJsonOptionOfCustomType(opt, value, errors) {
            if (isNullOrUndefined(value))
                return undefined;
            var key = value.toLowerCase();
            var val = opt.type.get(key);
            if (val !== undefined) {
                return val;
            }
            else {
                errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
            }
        }
        function convertJsonOptionOfListType(option, values, basePath, errors) {
            return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
        }
        function trimString(s) {
            return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
        }
        /**
         * Tests for a path that ends in a recursive directory wildcard.
         * Matches **, \**, **\, and \**\, but not a**b.
         *
         * NOTE: used \ in place of / above to avoid issues with multiline comments.
         *
         * Breakdown:
         *  (^|\/)      # matches either the beginning of the string or a directory separator.
         *  \*\*        # matches the recursive directory wildcard "**".
         *  \/?$        # matches an optional trailing directory separator at the end of the string.
         */
        var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
        /**
         * Tests for a path where .. appears after a recursive directory wildcard.
         * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
         *
         * NOTE: used \ in place of / above to avoid issues with multiline comments.
         *
         * Breakdown:
         *  (^|\/)      # matches either the beginning of the string or a directory separator.
         *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
         *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
         *  \.\.        # matches a parent directory path component ".."
         *  ($|\/)      # matches either the end of the string or a directory separator.
         */
        var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
        /**
         * Tests for a path containing a wildcard character in a directory component of the path.
         * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
         *
         * NOTE: used \ in place of / above to avoid issues with multiline comments.
         *
         * Breakdown:
         *  \/          # matches a directory separator.
         *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
         *  [*?]        # matches either a wildcard character (* or ?)
         *  [^/]*       # matches any number of characters excluding directory separators (greedy).
         *  \/          # matches a directory separator.
         */
        var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
        /**
         * Matches the portion of a wildcard path that does not contain wildcards.
         * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
         *
         * NOTE: used \ in place of / above to avoid issues with multiline comments.
         *
         * Breakdown:
         *  ^                   # matches the beginning of the string
         *  [^*?]*              # matches any number of non-wildcard characters
         *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
         *                      # a path component that contains at least one wildcard character (* or ?).
         */
        var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
        /**
         * Expands an array of file specifications.
         *
         * @param filesSpecs The literal file names to include.
         * @param includeSpecs The wildcard file specifications to include.
         * @param excludeSpecs The wildcard file specifications to exclude.
         * @param basePath The base path for any relative file specifications.
         * @param options Compiler options.
         * @param host The host used to resolve files and directories.
         * @param errors An array for diagnostic reporting.
         */
        function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
            basePath = ts.normalizePath(basePath);
            var validatedIncludeSpecs, validatedExcludeSpecs;
            // The exclude spec list is converted into a regular expression, which allows us to quickly
            // test whether a file or directory should be excluded before recursively traversing the
            // file system.
            if (includeSpecs) {
                validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
            }
            if (excludeSpecs) {
                validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
            }
            // Wildcard directories (provided as part of a wildcard path) are stored in a
            // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
            // or a recursive directory. This information is used by filesystem watchers to monitor for
            // new entries in these paths.
            var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
            var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
            return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
        }
        /**
         * Gets the file names from the provided config file specs that contain, files, include, exclude and
         * other properties needed to resolve the file names
         * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
         * @param basePath The base path for any relative file specifications.
         * @param options Compiler options.
         * @param host The host used to resolve files and directories.
         * @param extraFileExtensions optionaly file extra file extension information from host
         */
        /* @internal */
        function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
            if (extraFileExtensions === void 0) {
                extraFileExtensions = [];
            }
            basePath = ts.normalizePath(basePath);
            var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase;
            // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
            // file map with a possibly case insensitive key. We use this map later when when including
            // wildcard paths.
            var literalFileMap = ts.createMap();
            // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
            // file map with a possibly case insensitive key. We use this map to store paths matched
            // via wildcard, and to handle extension priority.
            var wildcardFileMap = ts.createMap();
            var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
            // Rather than requery this for each file and filespec, we query the supported extensions
            // once and store it on the expansion context.
            var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
            // Literal files are always included verbatim. An "include" or "exclude" specification cannot
            // remove a literal file.
            if (filesSpecs) {
                for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
                    var fileName = filesSpecs_1[_i];
                    var file = ts.getNormalizedAbsolutePath(fileName, basePath);
                    literalFileMap.set(keyMapper(file), file);
                }
            }
            if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
                for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
                    var file = _b[_a];
                    // If we have already included a literal or wildcard path with a
                    // higher priority extension, we should skip this file.
                    //
                    // This handles cases where we may encounter both <file>.ts and
                    // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
                    // directory when they are compilation outputs.
                    if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
                        continue;
                    }
                    // We may have included a wildcard path with a lower priority
                    // extension due to the user-defined order of entries in the
                    // "include" array. If there is a lower priority extension in the
                    // same directory, we should remove it.
                    removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
                    var key = keyMapper(file);
                    if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
                        wildcardFileMap.set(key, file);
                    }
                }
            }
            var literalFiles = ts.arrayFrom(literalFileMap.values());
            var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
            return {
                fileNames: literalFiles.concat(wildcardFiles),
                wildcardDirectories: wildcardDirectories,
                spec: spec
            };
        }
        ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
        function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
            return specs.filter(function (spec) {
                var diag = specToDiagnostic(spec, allowTrailingRecursion);
                if (diag !== undefined) {
                    errors.push(createDiagnostic(diag, spec));
                }
                return diag === undefined;
            });
            function createDiagnostic(message, spec) {
                var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
                return element ?
                    ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
                    ts.createCompilerDiagnostic(message, spec);
            }
        }
        function specToDiagnostic(spec, allowTrailingRecursion) {
            if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
                return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
            }
            else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
                return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
            }
        }
        /**
         * Gets directories in a set of include patterns that should be watched for changes.
         */
        function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
            // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
            // of the pattern:
            //
            //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
            //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
            //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
            //
            // We watch a directory without recursion if it contains a wildcard in the file segment of
            // the pattern:
            //
            //  /a/b/*      - Watch /a/b directly to catch any new file
            //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
            var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
            var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
            var wildcardDirectories = {};
            if (include !== undefined) {
                var recursiveKeys = [];
                for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
                    var file = include_1[_i];
                    var spec = ts.normalizePath(ts.combinePaths(path, file));
                    if (excludeRegex && excludeRegex.test(spec)) {
                        continue;
                    }
                    var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
                    if (match) {
                        var key = match.key, flags = match.flags;
                        var existingFlags = wildcardDirectories[key];
                        if (existingFlags === undefined || existingFlags < flags) {
                            wildcardDirectories[key] = flags;
                            if (flags === 1 /* Recursive */) {
                                recursiveKeys.push(key);
                            }
                        }
                    }
                }
                // Remove any subpaths under an existing recursively watched directory.
                for (var key in wildcardDirectories) {
                    if (ts.hasProperty(wildcardDirectories, key)) {
                        for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
                            var recursiveKey = recursiveKeys_1[_a];
                            if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
                                delete wildcardDirectories[key];
                            }
                        }
                    }
                }
            }
            return wildcardDirectories;
        }
        function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
            var match = wildcardDirectoryPattern.exec(spec);
            if (match) {
                return {
                    key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(),
                    flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
                };
            }
            if (ts.isImplicitGlob(spec)) {
                return { key: spec, flags: 1 /* Recursive */ };
            }
            return undefined;
        }
        /**
         * Determines whether a literal or wildcard file has already been included that has a higher
         * extension priority.
         *
         * @param file The path to the file.
         * @param extensionPriority The priority of the extension.
         * @param context The expansion context.
         */
        function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
            var extensionPriority = ts.getExtensionPriority(file, extensions);
            var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
            for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
                var higherPriorityExtension = extensions[i];
                var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
                if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
                    return true;
                }
            }
            return false;
        }
        /**
         * Removes files included via wildcard expansion with a lower extension priority that have
         * already been included.
         *
         * @param file The path to the file.
         * @param extensionPriority The priority of the extension.
         * @param context The expansion context.
         */
        function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
            var extensionPriority = ts.getExtensionPriority(file, extensions);
            var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
            for (var i = nextExtensionPriority; i < extensions.length; i++) {
                var lowerPriorityExtension = extensions[i];
                var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
                wildcardFiles.delete(lowerPriorityPath);
            }
        }
        /**
         * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed.
         * Also converts enum values back to strings.
         */
        /* @internal */
        function convertCompilerOptionsForTelemetry(opts) {
            var out = {};
            for (var key in opts) {
                if (opts.hasOwnProperty(key)) {
                    var type = getOptionFromName(key);
                    if (type !== undefined) { // Ignore unknown options
                        out[key] = getOptionValueWithEmptyStrings(opts[key], type);
                    }
                }
            }
            return out;
        }
        ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
        function getOptionValueWithEmptyStrings(value, option) {
            switch (option.type) {
                case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
                    return "";
                case "string": // Could be any arbitrary string -- use empty string instead.
                    return "";
                case "number": // Allow numbers, but be sure to check it's actually a number.
                    return typeof value === "number" ? value : "";
                case "boolean":
                    return typeof value === "boolean" ? value : "";
                case "list":
                    var elementType_1 = option.element; // tslint:disable-line no-unnecessary-type-assertion
                    return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
                default:
                    return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
                        if (optionEnumValue === value) {
                            return optionStringValue;
                        }
                    }); // TODO: GH#18217
            }
        }
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        function trace(host) {
            host.trace(ts.formatMessage.apply(undefined, arguments));
        }
        ts.trace = trace;
        /* @internal */
        function isTraceEnabled(compilerOptions, host) {
            return !!compilerOptions.traceResolution && host.trace !== undefined;
        }
        ts.isTraceEnabled = isTraceEnabled;
        function withPackageId(packageId, r) {
            return r && { path: r.path, extension: r.ext, packageId: packageId };
        }
        function noPackageId(r) {
            return withPackageId(/*packageId*/ undefined, r);
        }
        function removeIgnoredPackageId(r) {
            if (r) {
                ts.Debug.assert(r.packageId === undefined);
                return { path: r.path, ext: r.extension };
            }
        }
        /**
         * Kinds of file that we are currently looking for.
         * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
         */
        var Extensions;
        (function (Extensions) {
            Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
            Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
            Extensions[Extensions["Json"] = 2] = "Json";
            Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */
        })(Extensions || (Extensions = {}));
        /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
        function resolvedTypeScriptOnly(resolved) {
            if (!resolved) {
                return undefined;
            }
            ts.Debug.assert(ts.extensionIsTS(resolved.extension));
            return { fileName: resolved.path, packageId: resolved.packageId };
        }
        function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) {
            return {
                resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
                failedLookupLocations: failedLookupLocations
            };
        }
        function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
            if (!ts.hasProperty(jsonContent, fieldName)) {
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
                }
                return;
            }
            var value = jsonContent[fieldName];
            if (typeof value !== typeOfTag || value === null) {
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
                }
                return;
            }
            return value;
        }
        function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
            var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
            if (fileName === undefined)
                return;
            var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
            if (state.traceEnabled) {
                trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
            }
            return path;
        }
        function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
            return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
                || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
        }
        function readPackageJsonMainField(jsonContent, baseDirectory, state) {
            return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
        }
        function readPackageJsonTypesVersionsField(jsonContent, state) {
            var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
            if (typesVersions === undefined)
                return;
            if (state.traceEnabled) {
                trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
            }
            return typesVersions;
        }
        function readPackageJsonTypesVersionPaths(jsonContent, state) {
            var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
            if (typesVersions === undefined)
                return;
            if (state.traceEnabled) {
                for (var key in typesVersions) {
                    if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
                        trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
                    }
                }
            }
            var result = getPackageJsonTypesVersionsPaths(typesVersions);
            if (!result) {
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
                }
                return;
            }
            var bestVersionKey = result.version, bestVersionPaths = result.paths;
            if (typeof bestVersionPaths !== "object") {
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
                }
                return;
            }
            return result;
        }
        var typeScriptVersion;
        /* @internal */
        function getPackageJsonTypesVersionsPaths(typesVersions) {
            if (!typeScriptVersion)
                typeScriptVersion = new ts.Version(ts.version);
            for (var key in typesVersions) {
                if (!ts.hasProperty(typesVersions, key))
                    continue;
                var keyRange = ts.VersionRange.tryParse(key);
                if (keyRange === undefined) {
                    continue;
                }
                // return the first entry whose range matches the current compiler version.
                if (keyRange.test(typeScriptVersion)) {
                    return { version: key, paths: typesVersions[key] };
                }
            }
        }
        ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
        function getEffectiveTypeRoots(options, host) {
            if (options.typeRoots) {
                return options.typeRoots;
            }
            var currentDirectory;
            if (options.configFilePath) {
                currentDirectory = ts.getDirectoryPath(options.configFilePath);
            }
            else if (host.getCurrentDirectory) {
                currentDirectory = host.getCurrentDirectory();
            }
            if (currentDirectory !== undefined) {
                return getDefaultTypeRoots(currentDirectory, host);
            }
        }
        ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
        /**
         * Returns the path to every node_modules/@types directory from some ancestor directory.
         * Returns undefined if there are none.
         */
        function getDefaultTypeRoots(currentDirectory, host) {
            if (!host.directoryExists) {
                return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
                // And if it doesn't exist, tough.
            }
            var typeRoots;
            ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
                var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
                if (host.directoryExists(atTypes)) {
                    (typeRoots || (typeRoots = [])).push(atTypes);
                }
                return undefined;
            });
            return typeRoots;
        }
        var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
        /**
         * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
         * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
         * is assumed to be the same as root directory of the project.
         */
        function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) {
            var traceEnabled = isTraceEnabled(options, host);
            var failedLookupLocations = [];
            var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
            var typeRoots = getEffectiveTypeRoots(options, host);
            if (traceEnabled) {
                if (containingFile === undefined) {
                    if (typeRoots === undefined) {
                        trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
                    }
                    else {
                        trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
                    }
                }
                else {
                    if (typeRoots === undefined) {
                        trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
                    }
                    else {
                        trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
                    }
                }
            }
            var resolved = primaryLookup();
            var primary = true;
            if (!resolved) {
                resolved = secondaryLookup();
                primary = false;
            }
            var resolvedTypeReferenceDirective;
            if (resolved) {
                if (!options.preserveSymlinks) {
                    resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) });
                }
                if (traceEnabled) {
                    trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary);
                }
                resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId };
            }
            return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
            function primaryLookup() {
                // Check primary library paths
                if (typeRoots && typeRoots.length) {
                    if (traceEnabled) {
                        trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
                    }
                    return ts.forEach(typeRoots, function (typeRoot) {
                        var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
                        var candidateDirectory = ts.getDirectoryPath(candidate);
                        var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
                        if (!directoryExists && traceEnabled) {
                            trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
                        }
                        return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
                    });
                }
                else {
                    if (traceEnabled) {
                        trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
                    }
                }
            }
            function secondaryLookup() {
                var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
                if (initialLocationForSecondaryLookup !== undefined) {
                    // check secondary locations
                    if (traceEnabled) {
                        trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
                    }
                    var result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined);
                    var resolvedFile = resolvedTypeScriptOnly(result && result.value);
                    if (!resolvedFile && traceEnabled) {
                        trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
                    }
                    return resolvedFile;
                }
                else {
                    if (traceEnabled) {
                        trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
                    }
                }
            }
        }
        ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
        /**
         * Given a set of options, returns the set of type directive names
         *   that should be included for this program automatically.
         * This list could either come from the config file,
         *   or from enumerating the types root + initial secondary types lookup location.
         * More type directives might appear in the program later as a result of loading actual source files;
         *   this list is only the set of defaults that are implicitly included.
         */
        function getAutomaticTypeDirectiveNames(options, host) {
            // Use explicit type list from tsconfig.json
            if (options.types) {
                return options.types;
            }
            // Walk the primary type lookup locations
            var result = [];
            if (host.directoryExists && host.getDirectories) {
                var typeRoots = getEffectiveTypeRoots(options, host);
                if (typeRoots) {
                    for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
                        var root = typeRoots_1[_i];
                        if (host.directoryExists(root)) {
                            for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
                                var typeDirectivePath = _b[_a];
                                var normalized = ts.normalizePath(typeDirectivePath);
                                var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
                                // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
                                // See `createNotNeededPackageJSON` in the types-publisher` repo.
                                // tslint:disable-next-line:no-null-keyword
                                var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
                                if (!isNotNeededPackage) {
                                    // Return just the type directive names
                                    result.push(ts.getBaseFileName(normalized));
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
        ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
        function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
            return createModuleResolutionCacheWithMaps(ts.createMap(), ts.createMap(), currentDirectory, getCanonicalFileName);
        }
        ts.createModuleResolutionCache = createModuleResolutionCache;
        /*@internal*/
        function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
            return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
            function getOrCreateCacheForDirectory(directoryName) {
                var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
                var perFolderCache = directoryToModuleNameMap.get(path);
                if (!perFolderCache) {
                    perFolderCache = ts.createMap();
                    directoryToModuleNameMap.set(path, perFolderCache);
                }
                return perFolderCache;
            }
            function getOrCreateCacheForModuleName(nonRelativeModuleName) {
                ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
                var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName);
                if (!perModuleNameCache) {
                    perModuleNameCache = createPerModuleNameCache();
                    moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache);
                }
                return perModuleNameCache;
            }
            function createPerModuleNameCache() {
                var directoryPathMap = ts.createMap();
                return { get: get, set: set };
                function get(directory) {
                    return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
                }
                /**
                 * At first this function add entry directory -> module resolution result to the table.
                 * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
                 * and for every parent folder in set it adds entry: parent -> module resolution. .
                 * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
                 * Set of parent folders that should have the same result will be:
                 * [
                 *     /a/b/c/d, /a/b/c, /a/b
                 * ]
                 * this means that request for module resolution from file in any of these folder will be immediately found in cache.
                 */
                function set(directory, result) {
                    var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
                    // if entry is already in cache do nothing
                    if (directoryPathMap.has(path)) {
                        return;
                    }
                    directoryPathMap.set(path, result);
                    var resolvedFileName = result.resolvedModule &&
                        (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
                    // find common prefix between directory and resolved file name
                    // this common prefix should be the shortest path that has the same resolution
                    // directory: /a/b/c/d/e
                    // resolvedFileName: /a/b/foo.d.ts
                    // commonPrefix: /a/b
                    // for failed lookups cache the result for every directory up to root
                    var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
                    var current = path;
                    while (current !== commonPrefix) {
                        var parent = ts.getDirectoryPath(current);
                        if (parent === current || directoryPathMap.has(parent)) {
                            break;
                        }
                        directoryPathMap.set(parent, result);
                        current = parent;
                    }
                }
                function getCommonPrefix(directory, resolution) {
                    var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
                    // find first position where directory and resolution differs
                    var i = 0;
                    var limit = Math.min(directory.length, resolutionDirectory.length);
                    while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
                        i++;
                    }
                    if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
                        return directory;
                    }
                    var rootLength = ts.getRootLength(directory);
                    if (i < rootLength) {
                        return undefined;
                    }
                    var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
                    if (sep === -1) {
                        return undefined;
                    }
                    return directory.substr(0, Math.max(sep, rootLength));
                }
            }
        }
        ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
        function resolveModuleNameFromCache(moduleName, containingFile, cache) {
            var containingDirectory = ts.getDirectoryPath(containingFile);
            var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
            return perFolderCache && perFolderCache.get(moduleName);
        }
        ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
        function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
            var traceEnabled = isTraceEnabled(compilerOptions, host);
            if (traceEnabled) {
                trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
            }
            var containingDirectory = ts.getDirectoryPath(containingFile);
            var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
            var result = perFolderCache && perFolderCache.get(moduleName);
            if (result) {
                if (traceEnabled) {
                    trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
                }
            }
            else {
                var moduleResolution = compilerOptions.moduleResolution;
                if (moduleResolution === undefined) {
                    moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
                    if (traceEnabled) {
                        trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
                    }
                }
                else {
                    if (traceEnabled) {
                        trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
                    }
                }
                switch (moduleResolution) {
                    case ts.ModuleResolutionKind.NodeJs:
                        result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache);
                        break;
                    case ts.ModuleResolutionKind.Classic:
                        result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache);
                        break;
                    default:
                        return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
                }
                if (perFolderCache) {
                    perFolderCache.set(moduleName, result);
                    if (!ts.isExternalModuleNameRelative(moduleName)) {
                        // put result in per-module name cache
                        cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result);
                    }
                }
            }
            if (traceEnabled) {
                if (result.resolvedModule) {
                    trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
                }
                else {
                    trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
                }
            }
            return result;
        }
        ts.resolveModuleName = resolveModuleName;
        /**
         * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
         * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
         * can be resolved successfully by TypeScript compiler and runtime module loader.
         * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
         * fallback to standard resolution routine.
         *
         * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
         * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
         * be '/a/b/c/d'
         * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
         * will be resolved based on the content of the module name.
         * Structure of 'paths' compiler options
         * 'paths': {
         *    pattern-1: [...substitutions],
         *    pattern-2: [...substitutions],
         *    ...
         *    pattern-n: [...substitutions]
         * }
         * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
         * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
         * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
         * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
         * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
         * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
         * from the candidate location.
         * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
         * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
         * will be converted to absolute using baseUrl.
         * For example:
         * baseUrl: /a/b/c
         * "paths": {
         *     // match all module names
         *     "*": [
         *         "*",        // use matched name as is,
         *                     // <matched name> will be looked as /a/b/c/<matched name>
         *
         *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
         *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
         *     ],
         *     // match module names that start with 'components/'
         *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
         *                                              // it is rooted so it will be final candidate location
         * }
         *
         * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
         * they were in the same location. For example lets say there are two files
         * '/local/src/content/file1.ts'
         * '/shared/components/contracts/src/content/protocols/file2.ts'
         * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
         * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
         * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
         * root dirs were merged together.
         * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
         * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
         * '/local/src/content/protocols/file2' and try to load it - failure.
         * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
         * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
         * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
         */
        function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
            if (!ts.isExternalModuleNameRelative(moduleName)) {
                return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
            }
            else {
                return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
            }
        }
        function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
            if (!state.compilerOptions.rootDirs) {
                return undefined;
            }
            if (state.traceEnabled) {
                trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
            }
            var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
            var matchedRootDir;
            var matchedNormalizedPrefix;
            for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
                var rootDir = _a[_i];
                // rootDirs are expected to be absolute
                // in case of tsconfig.json this will happen automatically - compiler will expand relative names
                // using location of tsconfig.json as base location
                var normalizedRoot = ts.normalizePath(rootDir);
                if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
                    normalizedRoot += ts.directorySeparator;
                }
                var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
                    (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
                }
                if (isLongestMatchingPrefix) {
                    matchedNormalizedPrefix = normalizedRoot;
                    matchedRootDir = rootDir;
                }
            }
            if (matchedNormalizedPrefix) {
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
                }
                var suffix = candidate.substr(matchedNormalizedPrefix.length);
                // first - try to load from a initial location
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
                }
                var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
                if (resolvedFileName) {
                    return resolvedFileName;
                }
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
                }
                // then try to resolve using remaining entries in rootDirs
                for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
                    var rootDir = _c[_b];
                    if (rootDir === matchedRootDir) {
                        // skip the initially matched entry
                        continue;
                    }
                    var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
                    }
                    var baseDirectory = ts.getDirectoryPath(candidate_1);
                    var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
                    if (resolvedFileName_1) {
                        return resolvedFileName_1;
                    }
                }
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
                }
            }
            return undefined;
        }
        function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
            var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
            if (!baseUrl) {
                return undefined;
            }
            if (state.traceEnabled) {
                trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
            }
            if (paths) {
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
                }
                var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
                if (resolved) {
                    return resolved.value;
                }
            }
            var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
            if (state.traceEnabled) {
                trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
            }
            return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
        }
        /**
         * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
         * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
         * Throws an error if the module can't be resolved.
         */
        /* @internal */
        function resolveJSModule(moduleName, initialDir, host) {
            var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
            if (!resolvedModule) {
                throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
            }
            return resolvedModule.resolvedFileName;
        }
        ts.resolveJSModule = resolveJSModule;
        /* @internal */
        function tryResolveJSModule(moduleName, initialDir, host) {
            var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
            return resolvedModule && resolvedModule.resolvedFileName;
        }
        ts.tryResolveJSModule = tryResolveJSModule;
        function tryResolveJSModuleWorker(moduleName, initialDir, host) {
            return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true);
        }
        function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
            return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false);
        }
        ts.nodeModuleNameResolver = nodeModuleNameResolver;
        function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) {
            var traceEnabled = isTraceEnabled(compilerOptions, host);
            var failedLookupLocations = [];
            var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
            var result = jsOnly ?
                tryResolve(Extensions.JavaScript) :
                (tryResolve(Extensions.TypeScript) ||
                    tryResolve(Extensions.JavaScript) ||
                    (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
            if (result && result.value) {
                var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport;
                return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations);
            }
            return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
            function tryResolve(extensions) {
                var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
                var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
                if (resolved) {
                    return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) });
                }
                if (!ts.isExternalModuleNameRelative(moduleName)) {
                    if (traceEnabled) {
                        trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
                    }
                    var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache);
                    if (!resolved_1)
                        return undefined;
                    var resolvedValue = resolved_1.value;
                    if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
                        var path = realPath(resolvedValue.path, host, traceEnabled);
                        var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
                        resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath });
                    }
                    // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
                    return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
                }
                else {
                    var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
                    var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
                    // Treat explicit "node_modules" import as an external library import.
                    return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
                }
            }
        }
        function realPath(path, host, traceEnabled) {
            if (!host.realpath) {
                return path;
            }
            var real = ts.normalizePath(host.realpath(path));
            if (traceEnabled) {
                trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
            }
            ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line
            return real;
        }
        function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
            if (state.traceEnabled) {
                trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
            }
            if (!ts.hasTrailingDirectorySeparator(candidate)) {
                if (!onlyRecordFailures) {
                    var parentOfCandidate = ts.getDirectoryPath(candidate);
                    if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
                        if (state.traceEnabled) {
                            trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
                        }
                        onlyRecordFailures = true;
                    }
                }
                var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
                if (resolvedFromFile) {
                    var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
                    var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state);
                    var packageId = packageInfo && packageInfo.packageId;
                    return withPackageId(packageId, resolvedFromFile);
                }
            }
            if (!onlyRecordFailures) {
                var candidateExists = ts.directoryProbablyExists(candidate, state.host);
                if (!candidateExists) {
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
                    }
                    onlyRecordFailures = true;
                }
            }
            return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
        }
        /*@internal*/
        ts.nodeModulesPathPart = "/node_modules/";
        /**
         * This will be called on the successfully resolved path from `loadModuleFromFile`.
         * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
         *
         * packageDirectory is the directory of the package itself.
         * subModuleName is the path within the package.
         *   For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.)
         *   For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
         *   For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }.
         *   For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
         */
        function parseNodeModuleFromPath(resolved) {
            var path = ts.normalizePath(resolved.path);
            var idx = path.lastIndexOf(ts.nodeModulesPathPart);
            if (idx === -1) {
                return undefined;
            }
            var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
            var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
            if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
                indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
            }
            var packageDirectory = path.slice(0, indexAfterPackageName);
            var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */;
            return { packageDirectory: packageDirectory, subModuleName: subModuleName };
        }
        function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
            var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
            return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
        }
        function addExtensionAndIndex(path) {
            if (path === "") {
                return "index.d.ts";
            }
            if (ts.endsWith(path, ".d.ts")) {
                return path;
            }
            if (path === "index" || ts.endsWith(path, "/index")) {
                return path + ".d.ts";
            }
            return path + "/index.d.ts";
        }
        function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
            return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
        }
        /**
         * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
         * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
         */
        function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
            if (extensions === Extensions.Json) {
                var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
                return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state);
            }
            // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
            var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
            if (resolvedByAddingExtension) {
                return resolvedByAddingExtension;
            }
            // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
            // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
            if (ts.hasJSFileExtension(candidate)) {
                var extensionless = ts.removeFileExtension(candidate);
                if (state.traceEnabled) {
                    var extension = candidate.substring(extensionless.length);
                    trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
                }
                return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
            }
        }
        /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
        function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
            if (!onlyRecordFailures) {
                // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
                var directory = ts.getDirectoryPath(candidate);
                if (directory) {
                    onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
                }
            }
            switch (extensions) {
                case Extensions.DtsOnly:
                    return tryExtension(".d.ts" /* Dts */);
                case Extensions.TypeScript:
                    return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
                case Extensions.JavaScript:
                    return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
                case Extensions.Json:
                    return tryExtension(".json" /* Json */);
            }
            function tryExtension(ext) {
                var path = tryFile(candidate + ext, onlyRecordFailures, state);
                return path === undefined ? undefined : { path: path, ext: ext };
            }
        }
        /** Return the file if it exists. */
        function tryFile(fileName, onlyRecordFailures, state) {
            if (!onlyRecordFailures) {
                if (state.host.fileExists(fileName)) {
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
                    }
                    return fileName;
                }
                else {
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
                    }
                }
            }
            state.failedLookupLocations.push(fileName);
            return undefined;
        }
        function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
            if (considerPackageJson === void 0) {
                considerPackageJson = true;
            }
            var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined;
            var packageId = packageInfo && packageInfo.packageId;
            var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
            var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state);
            return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
        }
        function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths) {
            var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state);
            if (fromPackageJson) {
                return fromPackageJson;
            }
            var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(candidate, state.host);
            return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), !directoryExists, state);
        }
        function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) {
            var host = state.host, traceEnabled = state.traceEnabled;
            var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
            var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
            if (directoryExists && host.fileExists(packageJsonPath)) {
                var packageJsonContent = ts.readJson(packageJsonPath, host);
                if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
                    var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state);
                    if (typeof path === "string") {
                        subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1));
                    }
                    else {
                        var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state);
                        if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) {
                            var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1);
                            subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) {
                                return ts.tryRemoveExtension(potentialSubModule_1, extension);
                            }) || potentialSubModule_1) + ".d.ts" /* Dts */;
                        }
                        else {
                            subModuleName = "index.d.ts";
                        }
                    }
                }
                if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) {
                    subModuleName = addExtensionAndIndex(subModuleName);
                }
                var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
                var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string"
                    ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version }
                    : undefined;
                if (traceEnabled) {
                    if (packageId) {
                        trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId));
                    }
                    else {
                        trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
                    }
                }
                return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths };
            }
            else {
                if (directoryExists && traceEnabled) {
                    trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
                }
                // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
                state.failedLookupLocations.push(packageJsonPath);
            }
        }
        function loadModuleFromPackageJson(jsonContent, versionPaths, extensions, candidate, state) {
            var file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json
                ? readPackageJsonTypesFields(jsonContent, candidate, state)
                : readPackageJsonMainField(jsonContent, candidate, state);
            if (!file) {
                if (extensions === Extensions.TypeScript) {
                    // When resolving typescript modules, try resolving using main field as well
                    file = readPackageJsonMainField(jsonContent, candidate, state);
                    if (!file) {
                        return undefined;
                    }
                }
                else {
                    return undefined;
                }
            }
            var loader = function (extensions, candidate, onlyRecordFailures, state) {
                var fromFile = tryFile(candidate, onlyRecordFailures, state);
                if (fromFile) {
                    var resolved = resolvedIfExtensionMatches(extensions, fromFile);
                    if (resolved) {
                        return noPackageId(resolved);
                    }
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
                    }
                }
                // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
                var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
                // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
                return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
            };
            var onlyRecordFailures = !ts.directoryProbablyExists(ts.getDirectoryPath(file), state.host);
            if (versionPaths && ts.containsPath(candidate, file)) {
                var moduleName = ts.getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false);
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName);
                }
                var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state);
                if (result) {
                    return removeIgnoredPackageId(result.value);
                }
            }
            // It won't have a `packageId` set, because we disabled `considerPackageJson`.
            return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state));
        }
        /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
        function resolvedIfExtensionMatches(extensions, path) {
            var ext = ts.tryGetExtensionFromPath(path);
            return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
        }
        /** True if `extension` is one of the supported `extensions`. */
        function extensionIsOk(extensions, extension) {
            switch (extensions) {
                case Extensions.JavaScript:
                    return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
                case Extensions.Json:
                    return extension === ".json" /* Json */;
                case Extensions.TypeScript:
                    return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
                case Extensions.DtsOnly:
                    return extension === ".d.ts" /* Dts */;
            }
        }
        /* @internal */
        function parsePackageName(moduleName) {
            var idx = moduleName.indexOf(ts.directorySeparator);
            if (moduleName[0] === "@") {
                idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
            }
            return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
        }
        ts.parsePackageName = parsePackageName;
        function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) {
            return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache);
        }
        function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
            // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
            return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined);
        }
        function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) {
            var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName);
            return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
                if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
                    var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
                    if (resolutionFromCache) {
                        return resolutionFromCache;
                    }
                    return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
                }
            });
        }
        function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
            var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
            var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
            if (!nodeModulesFolderExists && state.traceEnabled) {
                trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
            }
            var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
            if (packageResult) {
                return packageResult;
            }
            if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
                var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
                var nodeModulesAtTypesExists = nodeModulesFolderExists;
                if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
                    }
                    nodeModulesAtTypesExists = false;
                }
                return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
            }
        }
        function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
            var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
            // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
            var packageJsonContent;
            var packageId;
            var versionPaths;
            var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state);
            if (packageInfo) {
                (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths);
                var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
                if (fromFile) {
                    return noPackageId(fromFile);
                }
                var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths);
                return withPackageId(packageId, fromDirectory);
            }
            var loader = function (extensions, candidate, onlyRecordFailures, state) {
                var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
                    loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths);
                return withPackageId(packageId, pathAndExtension);
            };
            var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
            if (rest !== "") { // If "rest" is empty, we just did this search above.
                var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
                // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
                var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state);
                if (packageInfo_1)
                    (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths);
                if (versionPaths) {
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest);
                    }
                    var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
                    var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state);
                    if (fromPaths) {
                        return fromPaths.value;
                    }
                }
            }
            return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
        }
        function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
            var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
            if (matchedPattern) {
                var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
                var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
                }
                var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
                    var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
                    var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
                    if (state.traceEnabled) {
                        trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
                    }
                    // A path mapping may have an extension, in contrast to an import, which should omit it.
                    var extension = ts.tryGetExtensionFromPath(candidate);
                    if (extension !== undefined) {
                        var path_1 = tryFile(candidate, onlyRecordFailures, state);
                        if (path_1 !== undefined) {
                            return noPackageId({ path: path_1, ext: extension });
                        }
                    }
                    return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
                });
                return { value: resolved };
            }
        }
        /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
        var mangledScopedPackageSeparator = "__";
        /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
        function mangleScopedPackageNameWithTrace(packageName, state) {
            var mangled = mangleScopedPackageName(packageName);
            if (state.traceEnabled && mangled !== packageName) {
                trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
            }
            return mangled;
        }
        /* @internal */
        function getTypesPackageName(packageName) {
            return "@types/" + mangleScopedPackageName(packageName);
        }
        ts.getTypesPackageName = getTypesPackageName;
        /* @internal */
        function mangleScopedPackageName(packageName) {
            if (ts.startsWith(packageName, "@")) {
                var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
                if (replaceSlash !== packageName) {
                    return replaceSlash.slice(1); // Take off the "@"
                }
            }
            return packageName;
        }
        ts.mangleScopedPackageName = mangleScopedPackageName;
        /* @internal */
        function getPackageNameFromTypesPackageName(mangledName) {
            var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
            if (withoutAtTypePrefix !== mangledName) {
                return unmangleScopedPackageName(withoutAtTypePrefix);
            }
            return mangledName;
        }
        ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
        /* @internal */
        function unmangleScopedPackageName(typesPackageName) {
            return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
                "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
                typesPackageName;
        }
        ts.unmangleScopedPackageName = unmangleScopedPackageName;
        function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
            var _a;
            var result = cache && cache.get(containingDirectory);
            if (result) {
                if (state.traceEnabled) {
                    trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
                }
                (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations);
                return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
            }
        }
        function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
            var traceEnabled = isTraceEnabled(compilerOptions, host);
            var failedLookupLocations = [];
            var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
            var containingDirectory = ts.getDirectoryPath(containingFile);
            var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
            // No originalPath because classic resolution doesn't resolve realPath
            return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations);
            function tryResolve(extensions) {
                var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
                if (resolvedUsingSettings) {
                    return { value: resolvedUsingSettings };
                }
                if (!ts.isExternalModuleNameRelative(moduleName)) {
                    var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName);
                    // Climb up parent directories looking for a module.
                    var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
                        var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
                        if (resolutionFromCache) {
                            return resolutionFromCache;
                        }
                        var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
                        return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
                    });
                    if (resolved_3) {
                        return resolved_3;
                    }
                    if (extensions === Extensions.TypeScript) {
                        // If we didn't find the file normally, look it up in @types.
                        return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
                    }
                }
                else {
                    var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
                    return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
                }
            }
        }
        ts.classicNameResolver = classicNameResolver;
        /**
         * LSHost may load a module from a global cache of typings.
         * This is the minumum code needed to expose that functionality; the rest is in LSHost.
         */
        /* @internal */
        function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
            var traceEnabled = isTraceEnabled(compilerOptions, host);
            if (traceEnabled) {
                trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
            }
            var failedLookupLocations = [];
            var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
            var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
            return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations);
        }
        ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
        /**
         * Wraps value to SearchResult.
         * @returns undefined if value is undefined or { value } otherwise
         */
        function toSearchResult(value) {
            return value !== undefined ? { value: value } : undefined;
        }
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var ModuleInstanceState;
        (function (ModuleInstanceState) {
            ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
            ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
            ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
        })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
        function getModuleInstanceState(node) {
            return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */;
        }
        ts.getModuleInstanceState = getModuleInstanceState;
        function getModuleInstanceStateWorker(node) {
            // A module is uninstantiated if it contains only
            switch (node.kind) {
                // 1. interface declarations, type alias declarations
                case 239 /* InterfaceDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                    return 0 /* NonInstantiated */;
                // 2. const enum declarations
                case 241 /* EnumDeclaration */:
                    if (ts.isEnumConst(node)) {
                        return 2 /* ConstEnumOnly */;
                    }
                    break;
                // 3. non-exported import declarations
                case 247 /* ImportDeclaration */:
                case 246 /* ImportEqualsDeclaration */:
                    if (!(ts.hasModifier(node, 1 /* Export */))) {
                        return 0 /* NonInstantiated */;
                    }
                    break;
                // 4. other uninstantiated module declarations.
                case 243 /* ModuleBlock */: {
                    var state_1 = 0 /* NonInstantiated */;
                    ts.forEachChild(node, function (n) {
                        var childState = getModuleInstanceStateWorker(n);
                        switch (childState) {
                            case 0 /* NonInstantiated */:
                                // child is non-instantiated - continue searching
                                return;
                            case 2 /* ConstEnumOnly */:
                                // child is const enum only - record state and continue searching
                                state_1 = 2 /* ConstEnumOnly */;
                                return;
                            case 1 /* Instantiated */:
                                // child is instantiated - record state and stop
                                state_1 = 1 /* Instantiated */;
                                return true;
                            default:
                                ts.Debug.assertNever(childState);
                        }
                    });
                    return state_1;
                }
                case 242 /* ModuleDeclaration */:
                    return getModuleInstanceState(node);
                case 71 /* Identifier */:
                    // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
                    // be considered the same as type alias
                    if (node.isInJSDocNamespace) {
                        return 0 /* NonInstantiated */;
                    }
            }
            return 1 /* Instantiated */;
        }
        var ContainerFlags;
        (function (ContainerFlags) {
            // The current node is not a container, and no container manipulation should happen before
            // recursing into it.
            ContainerFlags[ContainerFlags["None"] = 0] = "None";
            // The current node is a container.  It should be set as the current container (and block-
            // container) before recursing into it.  The current node does not have locals.  Examples:
            //
            //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
            ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
            // The current node is a block-scoped-container.  It should be set as the current block-
            // container before recursing into it.  Examples:
            //
            //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
            ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
            // The current node is the container of a control flow path. The current control flow should
            // be saved and restored, and a new control flow initialized within the container.
            ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
            ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
            ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
            ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
            ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
            ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
        })(ContainerFlags || (ContainerFlags = {}));
        var binder = createBinder();
        function bindSourceFile(file, options) {
            ts.performance.mark("beforeBind");
            binder(file, options);
            ts.performance.mark("afterBind");
            ts.performance.measure("Bind", "beforeBind", "afterBind");
        }
        ts.bindSourceFile = bindSourceFile;
        function createBinder() {
            var file;
            var options;
            var languageVersion;
            var parent;
            var container;
            var thisParentContainer; // Container one level up
            var blockScopeContainer;
            var lastContainer;
            var delayedTypeAliases;
            var seenThisKeyword;
            // state used by control flow analysis
            var currentFlow;
            var currentBreakTarget;
            var currentContinueTarget;
            var currentReturnTarget;
            var currentTrueTarget;
            var currentFalseTarget;
            var preSwitchCaseFlow;
            var activeLabels;
            var hasExplicitReturn;
            // state used for emit helpers
            var emitFlags;
            // If this file is an external module, then it is automatically in strict-mode according to
            // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
            // not depending on if we see "use strict" in certain places or if we hit a class/namespace
            // or if compiler options contain alwaysStrict.
            var inStrictMode;
            var symbolCount = 0;
            var Symbol; // tslint:disable-line variable-name
            var classifiableNames;
            var unreachableFlow = { flags: 1 /* Unreachable */ };
            var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
            // state used to aggregate transform flags during bind.
            var subtreeTransformFlags = 0 /* None */;
            var skipTransformFlagAggregation;
            /**
             * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
             * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node)
             * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
             */
            function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
                return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
            }
            function bindSourceFile(f, opts) {
                file = f;
                options = opts;
                languageVersion = ts.getEmitScriptTarget(options);
                inStrictMode = bindInStrictMode(file, opts);
                classifiableNames = ts.createUnderscoreEscapedMap();
                symbolCount = 0;
                skipTransformFlagAggregation = file.isDeclarationFile;
                Symbol = ts.objectAllocator.getSymbolConstructor();
                if (!file.locals) {
                    bind(file);
                    file.symbolCount = symbolCount;
                    file.classifiableNames = classifiableNames;
                    delayedBindJSDocTypedefTag();
                }
                file = undefined;
                options = undefined;
                languageVersion = undefined;
                parent = undefined;
                container = undefined;
                thisParentContainer = undefined;
                blockScopeContainer = undefined;
                lastContainer = undefined;
                delayedTypeAliases = undefined;
                seenThisKeyword = false;
                currentFlow = undefined;
                currentBreakTarget = undefined;
                currentContinueTarget = undefined;
                currentReturnTarget = undefined;
                currentTrueTarget = undefined;
                currentFalseTarget = undefined;
                activeLabels = undefined;
                hasExplicitReturn = false;
                emitFlags = 0 /* None */;
                subtreeTransformFlags = 0 /* None */;
            }
            return bindSourceFile;
            function bindInStrictMode(file, opts) {
                if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
                    // bind in strict mode source files with alwaysStrict option
                    return true;
                }
                else {
                    return !!file.externalModuleIndicator;
                }
            }
            function createSymbol(flags, name) {
                symbolCount++;
                return new Symbol(flags, name);
            }
            function addDeclarationToSymbol(symbol, node, symbolFlags) {
                symbol.flags |= symbolFlags;
                node.symbol = symbol;
                symbol.declarations = ts.append(symbol.declarations, node);
                if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
                    symbol.exports = ts.createSymbolTable();
                }
                if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
                    symbol.members = ts.createSymbolTable();
                }
                if (symbolFlags & 67220415 /* Value */) {
                    setValueDeclaration(symbol, node);
                }
            }
            function setValueDeclaration(symbol, node) {
                var valueDeclaration = symbol.valueDeclaration;
                if (!valueDeclaration ||
                    (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) ||
                    (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) {
                    // other kinds of value declarations take precedence over modules and assignment declarations
                    symbol.valueDeclaration = node;
                }
            }
            // Should not be called on a declaration with a computed property name,
            // unless it is a well known Symbol.
            function getDeclarationName(node) {
                if (node.kind === 252 /* ExportAssignment */) {
                    return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
                }
                var name = ts.getNameOfDeclaration(node);
                if (name) {
                    if (ts.isAmbientModule(node)) {
                        var moduleName = ts.getTextOfIdentifierOrLiteral(name);
                        return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
                    }
                    if (name.kind === 147 /* ComputedPropertyName */) {
                        var nameExpression = name.expression;
                        // treat computed property names where expression is string/numeric literal as just string/numeric literal
                        if (ts.isStringOrNumericLiteralLike(nameExpression)) {
                            return ts.escapeLeadingUnderscores(nameExpression.text);
                        }
                        ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
                        return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
                    }
                    return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
                }
                switch (node.kind) {
                    case 155 /* Constructor */:
                        return "__constructor" /* Constructor */;
                    case 163 /* FunctionType */:
                    case 158 /* CallSignature */:
                    case 291 /* JSDocSignature */:
                        return "__call" /* Call */;
                    case 164 /* ConstructorType */:
                    case 159 /* ConstructSignature */:
                        return "__new" /* New */;
                    case 160 /* IndexSignature */:
                        return "__index" /* Index */;
                    case 253 /* ExportDeclaration */:
                        return "__export" /* ExportStar */;
                    case 277 /* SourceFile */:
                        // json file should behave as
                        // module.exports = ...
                        return "export=" /* ExportEquals */;
                    case 202 /* BinaryExpression */:
                        if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
                            // module.exports = ...
                            return "export=" /* ExportEquals */;
                        }
                        ts.Debug.fail("Unknown binary declaration kind");
                        break;
                    case 287 /* JSDocFunctionType */:
                        return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
                    case 149 /* Parameter */:
                        // Parameters with names are handled at the top of this function.  Parameters
                        // without names can only come from JSDocFunctionTypes.
                        ts.Debug.assert(node.parent.kind === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
                        var functionType = node.parent;
                        var index = functionType.parameters.indexOf(node);
                        return "arg" + index;
                }
            }
            function getDisplayName(node) {
                return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node)));
            }
            /**
             * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
             * @param symbolTable - The symbol table which node will be added to.
             * @param parent - node's parent declaration.
             * @param node - The declaration to be added to the symbol table
             * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
             * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
             */
            function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
                ts.Debug.assert(!ts.hasDynamicName(node));
                var isDefaultExport = ts.hasModifier(node, 512 /* Default */);
                // The exported symbol for an export default function/class node is always named "default"
                var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
                var symbol;
                if (name === undefined) {
                    symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
                }
                else {
                    // Check and see if the symbol table already has a symbol with this name.  If not,
                    // create a new symbol with this name and add it to the table.  Note that we don't
                    // give the new symbol any flags *yet*.  This ensures that it will not conflict
                    // with the 'excludes' flags we pass in.
                    //
                    // If we do get an existing symbol, see if it conflicts with the new symbol we're
                    // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
                    // the same symbol table.  If we have a conflict, report the issue on each
                    // declaration we have for this symbol, and then create a new symbol for this
                    // declaration.
                    //
                    // Note that when properties declared in Javascript constructors
                    // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
                    // Always. This allows the common Javascript pattern of overwriting a prototype method
                    // with an bound instance method of the same type: `this.method = this.method.bind(this)`
                    //
                    // If we created a new symbol, either because we didn't have a symbol with this name
                    // in the symbol table, or we conflicted with an existing symbol, then just add this
                    // node as the sole declaration of the new symbol.
                    //
                    // Otherwise, we'll be merging into a compatible existing symbol (for example when
                    // you have multiple 'vars' with the same name in the same container).  In this case
                    // just add this node into the declarations list of the symbol.
                    symbol = symbolTable.get(name);
                    if (includes & 2885600 /* Classifiable */) {
                        classifiableNames.set(name, true);
                    }
                    if (!symbol) {
                        symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
                        if (isReplaceableByMethod)
                            symbol.isReplaceableByMethod = true;
                    }
                    else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
                        // A symbol already exists, so don't add this as a declaration.
                        return symbol;
                    }
                    else if (symbol.flags & excludes) {
                        if (symbol.isReplaceableByMethod) {
                            // Javascript constructor-declared symbols can be discarded in favor of
                            // prototype symbols like methods.
                            symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
                        }
                        else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
                            // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
                            if (ts.isNamedDeclaration(node)) {
                                node.name.parent = node;
                            }
                            // Report errors every position with duplicate declaration
                            // Report errors on previous encountered declarations
                            var message_1 = symbol.flags & 2 /* BlockScopedVariable */
                                ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
                                : ts.Diagnostics.Duplicate_identifier_0;
                            var messageNeedsName_1 = true;
                            if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
                                message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
                                messageNeedsName_1 = false;
                            }
                            if (symbol.declarations && symbol.declarations.length) {
                                // If the current node is a default export of some sort, then check if
                                // there are any other default exports that we need to error on.
                                // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
                                if (isDefaultExport) {
                                    message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
                                    messageNeedsName_1 = false;
                                }
                                else {
                                    // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
                                    // Error on multiple export default in the following case:
                                    // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
                                    // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
                                    if (symbol.declarations && symbol.declarations.length &&
                                        (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) {
                                        message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
                                        messageNeedsName_1 = false;
                                    }
                                }
                            }
                            var addError = function (decl) {
                                file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined));
                            };
                            ts.forEach(symbol.declarations, addError);
                            addError(node);
                            symbol = createSymbol(0 /* None */, name);
                        }
                    }
                }
                addDeclarationToSymbol(symbol, node, includes);
                if (symbol.parent) {
                    ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
                }
                else {
                    symbol.parent = parent;
                }
                return symbol;
            }
            function declareModuleMember(node, symbolFlags, symbolExcludes) {
                var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
                if (symbolFlags & 2097152 /* Alias */) {
                    if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) {
                        return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
                    }
                    else {
                        return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
                    }
                }
                else {
                    // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
                    // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
                    //
                    //   1. We treat locals and exports of the same name as mutually exclusive within a container.
                    //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
                    //      with the same name in the same container.
                    //      TODO: Make this a more specific error and decouple it from the exclusion logic.
                    //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
                    //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
                    //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
                    // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
                    //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
                    //       and this case is specially handled. Module augmentations should only be merged with original module definition
                    //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
                    if (ts.isJSDocTypeAlias(node))
                        ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
                    if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
                        if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) {
                            return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
                        }
                        var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0;
                        var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
                        local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
                        node.localSymbol = local;
                        return local;
                    }
                    else {
                        return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
                    }
                }
            }
            // All container nodes are kept on a linked list in declaration order. This list is used by
            // the getLocalNameOfContainer function in the type checker to validate that the local name
            // used for a container is unique.
            function bindContainer(node, containerFlags) {
                // Before we recurse into a node's children, we first save the existing parent, container
                // and block-container.  Then after we pop out of processing the children, we restore
                // these saved values.
                var saveContainer = container;
                var saveThisParentContainer = thisParentContainer;
                var savedBlockScopeContainer = blockScopeContainer;
                // Depending on what kind of node this is, we may have to adjust the current container
                // and block-container.   If the current node is a container, then it is automatically
                // considered the current block-container as well.  Also, for containers that we know
                // may contain locals, we eagerly initialize the .locals field. We do this because
                // it's highly likely that the .locals will be needed to place some child in (for example,
                // a parameter, or variable declaration).
                //
                // However, we do not proactively create the .locals for block-containers because it's
                // totally normal and common for block-containers to never actually have a block-scoped
                // variable in them.  We don't want to end up allocating an object for every 'block' we
                // run into when most of them won't be necessary.
                //
                // Finally, if this is a block-container, then we clear out any existing .locals object
                // it may contain within it.  This happens in incremental scenarios.  Because we can be
                // reusing a node from a previous compilation, that node may have had 'locals' created
                // for it.  We must clear this so we don't accidentally move any stale data forward from
                // a previous compilation.
                if (containerFlags & 1 /* IsContainer */) {
                    if (node.kind !== 195 /* ArrowFunction */) {
                        thisParentContainer = container;
                    }
                    container = blockScopeContainer = node;
                    if (containerFlags & 32 /* HasLocals */) {
                        container.locals = ts.createSymbolTable();
                    }
                    addToContainerChain(container);
                }
                else if (containerFlags & 2 /* IsBlockScopedContainer */) {
                    blockScopeContainer = node;
                    blockScopeContainer.locals = undefined;
                }
                if (containerFlags & 4 /* IsControlFlowContainer */) {
                    var saveCurrentFlow = currentFlow;
                    var saveBreakTarget = currentBreakTarget;
                    var saveContinueTarget = currentContinueTarget;
                    var saveReturnTarget = currentReturnTarget;
                    var saveActiveLabels = activeLabels;
                    var saveHasExplicitReturn = hasExplicitReturn;
                    var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
                        !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
                    // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
                    // similarly to break statements that exit to a label just past the statement body.
                    if (!isIIFE) {
                        currentFlow = { flags: 2 /* Start */ };
                        if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
                            currentFlow.container = node;
                        }
                    }
                    // We create a return control flow graph for IIFEs and constructors. For constructors
                    // we use the return control flow graph in strict property intialization checks.
                    currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined;
                    currentBreakTarget = undefined;
                    currentContinueTarget = undefined;
                    activeLabels = undefined;
                    hasExplicitReturn = false;
                    bindChildren(node);
                    // Reset all reachability check related flags on node (for incremental scenarios)
                    node.flags &= ~1408 /* ReachabilityAndEmitFlags */;
                    if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
                        node.flags |= 128 /* HasImplicitReturn */;
                        if (hasExplicitReturn)
                            node.flags |= 256 /* HasExplicitReturn */;
                    }
                    if (node.kind === 277 /* SourceFile */) {
                        node.flags |= emitFlags;
                    }
                    if (currentReturnTarget) {
                        addAntecedent(currentReturnTarget, currentFlow);
                        currentFlow = finishFlowLabel(currentReturnTarget);
                        if (node.kind === 155 /* Constructor */) {
                            node.returnFlowNode = currentFlow;
                        }
                    }
                    if (!isIIFE) {
                        currentFlow = saveCurrentFlow;
                    }
                    currentBreakTarget = saveBreakTarget;
                    currentContinueTarget = saveContinueTarget;
                    currentReturnTarget = saveReturnTarget;
                    activeLabels = saveActiveLabels;
                    hasExplicitReturn = saveHasExplicitReturn;
                }
                else if (containerFlags & 64 /* IsInterface */) {
                    seenThisKeyword = false;
                    bindChildren(node);
                    node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */;
                }
                else {
                    bindChildren(node);
                }
                container = saveContainer;
                thisParentContainer = saveThisParentContainer;
                blockScopeContainer = savedBlockScopeContainer;
            }
            function bindChildren(node) {
                if (skipTransformFlagAggregation) {
                    bindChildrenWorker(node);
                }
                else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
                    skipTransformFlagAggregation = true;
                    bindChildrenWorker(node);
                    skipTransformFlagAggregation = false;
                    subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
                }
                else {
                    var savedSubtreeTransformFlags = subtreeTransformFlags;
                    subtreeTransformFlags = 0;
                    bindChildrenWorker(node);
                    subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
                }
            }
            function bindEachFunctionsFirst(nodes) {
                bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; });
                bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; });
            }
            function bindEach(nodes, bindFunction) {
                if (bindFunction === void 0) {
                    bindFunction = bind;
                }
                if (nodes === undefined) {
                    return;
                }
                if (skipTransformFlagAggregation) {
                    ts.forEach(nodes, bindFunction);
                }
                else {
                    var savedSubtreeTransformFlags = subtreeTransformFlags;
                    subtreeTransformFlags = 0 /* None */;
                    var nodeArrayFlags = 0 /* None */;
                    for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
                        var node = nodes_2[_i];
                        bindFunction(node);
                        nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
                    }
                    nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
                    subtreeTransformFlags |= savedSubtreeTransformFlags;
                }
            }
            function bindEachChild(node) {
                ts.forEachChild(node, bind, bindEach);
            }
            function bindChildrenWorker(node) {
                if (checkUnreachable(node)) {
                    bindEachChild(node);
                    bindJSDoc(node);
                    return;
                }
                switch (node.kind) {
                    case 222 /* WhileStatement */:
                        bindWhileStatement(node);
                        break;
                    case 221 /* DoStatement */:
                        bindDoStatement(node);
                        break;
                    case 223 /* ForStatement */:
                        bindForStatement(node);
                        break;
                    case 224 /* ForInStatement */:
                    case 225 /* ForOfStatement */:
                        bindForInOrForOfStatement(node);
                        break;
                    case 220 /* IfStatement */:
                        bindIfStatement(node);
                        break;
                    case 228 /* ReturnStatement */:
                    case 232 /* ThrowStatement */:
                        bindReturnOrThrow(node);
                        break;
                    case 227 /* BreakStatement */:
                    case 226 /* ContinueStatement */:
                        bindBreakOrContinueStatement(node);
                        break;
                    case 233 /* TryStatement */:
                        bindTryStatement(node);
                        break;
                    case 230 /* SwitchStatement */:
                        bindSwitchStatement(node);
                        break;
                    case 244 /* CaseBlock */:
                        bindCaseBlock(node);
                        break;
                    case 269 /* CaseClause */:
                        bindCaseClause(node);
                        break;
                    case 231 /* LabeledStatement */:
                        bindLabeledStatement(node);
                        break;
                    case 200 /* PrefixUnaryExpression */:
                        bindPrefixUnaryExpressionFlow(node);
                        break;
                    case 201 /* PostfixUnaryExpression */:
                        bindPostfixUnaryExpressionFlow(node);
                        break;
                    case 202 /* BinaryExpression */:
                        bindBinaryExpressionFlow(node);
                        break;
                    case 196 /* DeleteExpression */:
                        bindDeleteExpressionFlow(node);
                        break;
                    case 203 /* ConditionalExpression */:
                        bindConditionalExpressionFlow(node);
                        break;
                    case 235 /* VariableDeclaration */:
                        bindVariableDeclarationFlow(node);
                        break;
                    case 189 /* CallExpression */:
                        bindCallExpressionFlow(node);
                        break;
                    case 302 /* JSDocTypedefTag */:
                    case 295 /* JSDocCallbackTag */:
                        bindJSDocTypeAlias(node);
                        break;
                    // In source files and blocks, bind functions first to match hoisting that occurs at runtime
                    case 277 /* SourceFile */: {
                        bindEachFunctionsFirst(node.statements);
                        bind(node.endOfFileToken);
                        break;
                    }
                    case 216 /* Block */:
                    case 243 /* ModuleBlock */:
                        bindEachFunctionsFirst(node.statements);
                        break;
                    default:
                        bindEachChild(node);
                        break;
                }
                bindJSDoc(node);
            }
            function isNarrowingExpression(expr) {
                switch (expr.kind) {
                    case 71 /* Identifier */:
                    case 99 /* ThisKeyword */:
                    case 187 /* PropertyAccessExpression */:
                    case 188 /* ElementAccessExpression */:
                        return isNarrowableReference(expr);
                    case 189 /* CallExpression */:
                        return hasNarrowableArgument(expr);
                    case 193 /* ParenthesizedExpression */:
                        return isNarrowingExpression(expr.expression);
                    case 202 /* BinaryExpression */:
                        return isNarrowingBinaryExpression(expr);
                    case 200 /* PrefixUnaryExpression */:
                        return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
                    case 197 /* TypeOfExpression */:
                        return isNarrowingExpression(expr.expression);
                }
                return false;
            }
            function isNarrowableReference(expr) {
                return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ ||
                    ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) ||
                    ts.isElementAccessExpression(expr) && expr.argumentExpression &&
                        (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) &&
                        isNarrowableReference(expr.expression);
            }
            function hasNarrowableArgument(expr) {
                if (expr.arguments) {
                    for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
                        var argument = _a[_i];
                        if (isNarrowableReference(argument)) {
                            return true;
                        }
                    }
                }
                if (expr.expression.kind === 187 /* PropertyAccessExpression */ &&
                    isNarrowableReference(expr.expression.expression)) {
                    return true;
                }
                return false;
            }
            function isNarrowingTypeofOperands(expr1, expr2) {
                return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
            }
            function isNarrowableInOperands(left, right) {
                return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
            }
            function isNarrowingBinaryExpression(expr) {
                switch (expr.operatorToken.kind) {
                    case 58 /* EqualsToken */:
                        return isNarrowableReference(expr.left);
                    case 32 /* EqualsEqualsToken */:
                    case 33 /* ExclamationEqualsToken */:
                    case 34 /* EqualsEqualsEqualsToken */:
                    case 35 /* ExclamationEqualsEqualsToken */:
                        return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
                            isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
                    case 93 /* InstanceOfKeyword */:
                        return isNarrowableOperand(expr.left);
                    case 92 /* InKeyword */:
                        return isNarrowableInOperands(expr.left, expr.right);
                    case 26 /* CommaToken */:
                        return isNarrowingExpression(expr.right);
                }
                return false;
            }
            function isNarrowableOperand(expr) {
                switch (expr.kind) {
                    case 193 /* ParenthesizedExpression */:
                        return isNarrowableOperand(expr.expression);
                    case 202 /* BinaryExpression */:
                        switch (expr.operatorToken.kind) {
                            case 58 /* EqualsToken */:
                                return isNarrowableOperand(expr.left);
                            case 26 /* CommaToken */:
                                return isNarrowableOperand(expr.right);
                        }
                }
                return isNarrowableReference(expr);
            }
            function createBranchLabel() {
                return {
                    flags: 4 /* BranchLabel */,
                    antecedents: undefined
                };
            }
            function createLoopLabel() {
                return {
                    flags: 8 /* LoopLabel */,
                    antecedents: undefined
                };
            }
            function setFlowNodeReferenced(flow) {
                // On first reference we set the Referenced flag, thereafter we set the Shared flag
                flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */;
            }
            function addAntecedent(label, antecedent) {
                if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
                    (label.antecedents || (label.antecedents = [])).push(antecedent);
                    setFlowNodeReferenced(antecedent);
                }
            }
            function createFlowCondition(flags, antecedent, expression) {
                if (antecedent.flags & 1 /* Unreachable */) {
                    return antecedent;
                }
                if (!expression) {
                    return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
                }
                if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
                    expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) {
                    return unreachableFlow;
                }
                if (!isNarrowingExpression(expression)) {
                    return antecedent;
                }
                setFlowNodeReferenced(antecedent);
                return { flags: flags, expression: expression, antecedent: antecedent };
            }
            function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
                if (!isNarrowingExpression(switchStatement.expression)) {
                    return antecedent;
                }
                setFlowNodeReferenced(antecedent);
                return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent };
            }
            function createFlowAssignment(antecedent, node) {
                setFlowNodeReferenced(antecedent);
                return { flags: 16 /* Assignment */, antecedent: antecedent, node: node };
            }
            function createFlowArrayMutation(antecedent, node) {
                setFlowNodeReferenced(antecedent);
                var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node };
                return res;
            }
            function finishFlowLabel(flow) {
                var antecedents = flow.antecedents;
                if (!antecedents) {
                    return unreachableFlow;
                }
                if (antecedents.length === 1) {
                    return antecedents[0];
                }
                return flow;
            }
            function isStatementCondition(node) {
                var parent = node.parent;
                switch (parent.kind) {
                    case 220 /* IfStatement */:
                    case 222 /* WhileStatement */:
                    case 221 /* DoStatement */:
                        return parent.expression === node;
                    case 223 /* ForStatement */:
                    case 203 /* ConditionalExpression */:
                        return parent.condition === node;
                }
                return false;
            }
            function isLogicalExpression(node) {
                while (true) {
                    if (node.kind === 193 /* ParenthesizedExpression */) {
                        node = node.expression;
                    }
                    else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) {
                        node = node.operand;
                    }
                    else {
                        return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ ||
                            node.operatorToken.kind === 54 /* BarBarToken */);
                    }
                }
            }
            function isTopLevelLogicalExpression(node) {
                while (node.parent.kind === 193 /* ParenthesizedExpression */ ||
                    node.parent.kind === 200 /* PrefixUnaryExpression */ &&
                        node.parent.operator === 51 /* ExclamationToken */) {
                    node = node.parent;
                }
                return !isStatementCondition(node) && !isLogicalExpression(node.parent);
            }
            function bindCondition(node, trueTarget, falseTarget) {
                var saveTrueTarget = currentTrueTarget;
                var saveFalseTarget = currentFalseTarget;
                currentTrueTarget = trueTarget;
                currentFalseTarget = falseTarget;
                bind(node);
                currentTrueTarget = saveTrueTarget;
                currentFalseTarget = saveFalseTarget;
                if (!node || !isLogicalExpression(node)) {
                    addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
                    addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
                }
            }
            function bindIterativeStatement(node, breakTarget, continueTarget) {
                var saveBreakTarget = currentBreakTarget;
                var saveContinueTarget = currentContinueTarget;
                currentBreakTarget = breakTarget;
                currentContinueTarget = continueTarget;
                bind(node);
                currentBreakTarget = saveBreakTarget;
                currentContinueTarget = saveContinueTarget;
            }
            function bindWhileStatement(node) {
                var preWhileLabel = createLoopLabel();
                var preBodyLabel = createBranchLabel();
                var postWhileLabel = createBranchLabel();
                addAntecedent(preWhileLabel, currentFlow);
                currentFlow = preWhileLabel;
                bindCondition(node.expression, preBodyLabel, postWhileLabel);
                currentFlow = finishFlowLabel(preBodyLabel);
                bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
                addAntecedent(preWhileLabel, currentFlow);
                currentFlow = finishFlowLabel(postWhileLabel);
            }
            function bindDoStatement(node) {
                var preDoLabel = createLoopLabel();
                var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */
                    ? ts.lastOrUndefined(activeLabels)
                    : undefined;
                // if do statement is wrapped in labeled statement then target labels for break/continue with or without
                // label should be the same
                var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel();
                var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel();
                addAntecedent(preDoLabel, currentFlow);
                currentFlow = preDoLabel;
                bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
                addAntecedent(preConditionLabel, currentFlow);
                currentFlow = finishFlowLabel(preConditionLabel);
                bindCondition(node.expression, preDoLabel, postDoLabel);
                currentFlow = finishFlowLabel(postDoLabel);
            }
            function bindForStatement(node) {
                var preLoopLabel = createLoopLabel();
                var preBodyLabel = createBranchLabel();
                var postLoopLabel = createBranchLabel();
                bind(node.initializer);
                addAntecedent(preLoopLabel, currentFlow);
                currentFlow = preLoopLabel;
                bindCondition(node.condition, preBodyLabel, postLoopLabel);
                currentFlow = finishFlowLabel(preBodyLabel);
                bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
                bind(node.incrementor);
                addAntecedent(preLoopLabel, currentFlow);
                currentFlow = finishFlowLabel(postLoopLabel);
            }
            function bindForInOrForOfStatement(node) {
                var preLoopLabel = createLoopLabel();
                var postLoopLabel = createBranchLabel();
                addAntecedent(preLoopLabel, currentFlow);
                currentFlow = preLoopLabel;
                if (node.kind === 225 /* ForOfStatement */) {
                    bind(node.awaitModifier);
                }
                bind(node.expression);
                addAntecedent(postLoopLabel, currentFlow);
                bind(node.initializer);
                if (node.initializer.kind !== 236 /* VariableDeclarationList */) {
                    bindAssignmentTargetFlow(node.initializer);
                }
                bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
                addAntecedent(preLoopLabel, currentFlow);
                currentFlow = finishFlowLabel(postLoopLabel);
            }
            function bindIfStatement(node) {
                var thenLabel = createBranchLabel();
                var elseLabel = createBranchLabel();
                var postIfLabel = createBranchLabel();
                bindCondition(node.expression, thenLabel, elseLabel);
                currentFlow = finishFlowLabel(thenLabel);
                bind(node.thenStatement);
                addAntecedent(postIfLabel, currentFlow);
                currentFlow = finishFlowLabel(elseLabel);
                bind(node.elseStatement);
                addAntecedent(postIfLabel, currentFlow);
                currentFlow = finishFlowLabel(postIfLabel);
            }
            function bindReturnOrThrow(node) {
                bind(node.expression);
                if (node.kind === 228 /* ReturnStatement */) {
                    hasExplicitReturn = true;
                    if (currentReturnTarget) {
                        addAntecedent(currentReturnTarget, currentFlow);
                    }
                }
                currentFlow = unreachableFlow;
            }
            function findActiveLabel(name) {
                if (activeLabels) {
                    for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) {
                        var label = activeLabels_1[_i];
                        if (label.name === name) {
                            return label;
                        }
                    }
                }
                return undefined;
            }
            function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
                var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget;
                if (flowLabel) {
                    addAntecedent(flowLabel, currentFlow);
                    currentFlow = unreachableFlow;
                }
            }
            function bindBreakOrContinueStatement(node) {
                bind(node.label);
                if (node.label) {
                    var activeLabel = findActiveLabel(node.label.escapedText);
                    if (activeLabel) {
                        activeLabel.referenced = true;
                        bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
                    }
                }
                else {
                    bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
                }
            }
            function bindTryStatement(node) {
                var preFinallyLabel = createBranchLabel();
                var preTryFlow = currentFlow;
                // TODO: Every statement in try block is potentially an exit point!
                bind(node.tryBlock);
                addAntecedent(preFinallyLabel, currentFlow);
                var flowAfterTry = currentFlow;
                var flowAfterCatch = unreachableFlow;
                if (node.catchClause) {
                    currentFlow = preTryFlow;
                    bind(node.catchClause);
                    addAntecedent(preFinallyLabel, currentFlow);
                    flowAfterCatch = currentFlow;
                }
                if (node.finallyBlock) {
                    // in finally flow is combined from pre-try/flow from try/flow from catch
                    // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable
                    // also for finally blocks we inject two extra edges into the flow graph.
                    // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it
                    // second -> edge that represents post-finally flow.
                    // these edges are used in following scenario:
                    // let a; (1)
                    // try { a = someOperation(); (2)}
                    // finally { (3) console.log(a) } (4)
                    // (5) a
                    // flow graph for this case looks roughly like this (arrows show ):
                    // (1-pre-try-flow) <--.. <-- (2-post-try-flow)
                    //  ^                                ^
                    //  |*****(3-pre-finally-label) -----|
                    //                ^
                    //                |-- ... <-- (4-post-finally-label) <--- (5)
                    // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account
                    // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5)
                    // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable
                    // Simply speaking code inside finally block is treated as reachable as pre-try-flow
                    // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally.
                    // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from
                    // final flows of these blocks without taking pre-try flow into account.
                    //
                    // extra edges that we inject allows to control this behavior
                    // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped.
                    var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} };
                    addAntecedent(preFinallyLabel, preFinallyFlow);
                    currentFlow = finishFlowLabel(preFinallyLabel);
                    bind(node.finallyBlock);
                    // if flow after finally is unreachable - keep it
                    // otherwise check if flows after try and after catch are unreachable
                    // if yes - convert current flow to unreachable
                    // i.e.
                    // try { return "1" } finally { console.log(1); }
                    // console.log(2); // this line should be unreachable even if flow falls out of finally block
                    if (!(currentFlow.flags & 1 /* Unreachable */)) {
                        if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) {
                            currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow
                                ? reportedUnreachableFlow
                                : unreachableFlow;
                        }
                    }
                    if (!(currentFlow.flags & 1 /* Unreachable */)) {
                        var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow };
                        preFinallyFlow.lock = afterFinallyFlow;
                        currentFlow = afterFinallyFlow;
                    }
                }
                else {
                    currentFlow = finishFlowLabel(preFinallyLabel);
                }
            }
            function bindSwitchStatement(node) {
                var postSwitchLabel = createBranchLabel();
                bind(node.expression);
                var saveBreakTarget = currentBreakTarget;
                var savePreSwitchCaseFlow = preSwitchCaseFlow;
                currentBreakTarget = postSwitchLabel;
                preSwitchCaseFlow = currentFlow;
                bind(node.caseBlock);
                addAntecedent(postSwitchLabel, currentFlow);
                var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; });
                // We mark a switch statement as possibly exhaustive if it has no default clause and if all
                // case clauses have unreachable end points (e.g. they all return).
                node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
                if (!hasDefault) {
                    addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
                }
                currentBreakTarget = saveBreakTarget;
                preSwitchCaseFlow = savePreSwitchCaseFlow;
                currentFlow = finishFlowLabel(postSwitchLabel);
            }
            function bindCaseBlock(node) {
                var savedSubtreeTransformFlags = subtreeTransformFlags;
                subtreeTransformFlags = 0;
                var clauses = node.clauses;
                var fallthroughFlow = unreachableFlow;
                for (var i = 0; i < clauses.length; i++) {
                    var clauseStart = i;
                    while (!clauses[i].statements.length && i + 1 < clauses.length) {
                        bind(clauses[i]);
                        i++;
                    }
                    var preCaseLabel = createBranchLabel();
                    addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1));
                    addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1));
                    addAntecedent(preCaseLabel, fallthroughFlow);
                    currentFlow = finishFlowLabel(preCaseLabel);
                    var clause = clauses[i];
                    bind(clause);
                    fallthroughFlow = currentFlow;
                    if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
                        errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch);
                    }
                }
                clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
                subtreeTransformFlags |= savedSubtreeTransformFlags;
            }
            function bindCaseClause(node) {
                var saveCurrentFlow = currentFlow;
                currentFlow = preSwitchCaseFlow;
                bind(node.expression);
                currentFlow = saveCurrentFlow;
                bindEach(node.statements);
            }
            function pushActiveLabel(name, breakTarget, continueTarget) {
                var activeLabel = {
                    name: name,
                    breakTarget: breakTarget,
                    continueTarget: continueTarget,
                    referenced: false
                };
                (activeLabels || (activeLabels = [])).push(activeLabel);
                return activeLabel;
            }
            function popActiveLabel() {
                activeLabels.pop();
            }
            function bindLabeledStatement(node) {
                var preStatementLabel = createLoopLabel();
                var postStatementLabel = createBranchLabel();
                bind(node.label);
                addAntecedent(preStatementLabel, currentFlow);
                var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel);
                bind(node.statement);
                popActiveLabel();
                if (!activeLabel.referenced && !options.allowUnusedLabels) {
                    errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
                }
                if (!node.statement || node.statement.kind !== 221 /* DoStatement */) {
                    // do statement sets current flow inside bindDoStatement
                    addAntecedent(postStatementLabel, currentFlow);
                    currentFlow = finishFlowLabel(postStatementLabel);
                }
            }
            function bindDestructuringTargetFlow(node) {
                if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) {
                    bindAssignmentTargetFlow(node.left);
                }
                else {
                    bindAssignmentTargetFlow(node);
                }
            }
            function bindAssignmentTargetFlow(node) {
                if (isNarrowableReference(node)) {
                    currentFlow = createFlowAssignment(currentFlow, node);
                }
                else if (node.kind === 185 /* ArrayLiteralExpression */) {
                    for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
                        var e = _a[_i];
                        if (e.kind === 206 /* SpreadElement */) {
                            bindAssignmentTargetFlow(e.expression);
                        }
                        else {
                            bindDestructuringTargetFlow(e);
                        }
                    }
                }
                else if (node.kind === 186 /* ObjectLiteralExpression */) {
                    for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
                        var p = _c[_b];
                        if (p.kind === 273 /* PropertyAssignment */) {
                            bindDestructuringTargetFlow(p.initializer);
                        }
                        else if (p.kind === 274 /* ShorthandPropertyAssignment */) {
                            bindAssignmentTargetFlow(p.name);
                        }
                        else if (p.kind === 275 /* SpreadAssignment */) {
                            bindAssignmentTargetFlow(p.expression);
                        }
                    }
                }
            }
            function bindLogicalExpression(node, trueTarget, falseTarget) {
                var preRightLabel = createBranchLabel();
                if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) {
                    bindCondition(node.left, preRightLabel, falseTarget);
                }
                else {
                    bindCondition(node.left, trueTarget, preRightLabel);
                }
                currentFlow = finishFlowLabel(preRightLabel);
                bind(node.operatorToken);
                bindCondition(node.right, trueTarget, falseTarget);
            }
            function bindPrefixUnaryExpressionFlow(node) {
                if (node.operator === 51 /* ExclamationToken */) {
                    var saveTrueTarget = currentTrueTarget;
                    currentTrueTarget = currentFalseTarget;
                    currentFalseTarget = saveTrueTarget;
                    bindEachChild(node);
                    currentFalseTarget = currentTrueTarget;
                    currentTrueTarget = saveTrueTarget;
                }
                else {
                    bindEachChild(node);
                    if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) {
                        bindAssignmentTargetFlow(node.operand);
                    }
                }
            }
            function bindPostfixUnaryExpressionFlow(node) {
                bindEachChild(node);
                if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) {
                    bindAssignmentTargetFlow(node.operand);
                }
            }
            function bindBinaryExpressionFlow(node) {
                var operator = node.operatorToken.kind;
                if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) {
                    if (isTopLevelLogicalExpression(node)) {
                        var postExpressionLabel = createBranchLabel();
                        bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
                        currentFlow = finishFlowLabel(postExpressionLabel);
                    }
                    else {
                        bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
                    }
                }
                else {
                    bindEachChild(node);
                    if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
                        bindAssignmentTargetFlow(node.left);
                        if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) {
                            var elementAccess = node.left;
                            if (isNarrowableOperand(elementAccess.expression)) {
                                currentFlow = createFlowArrayMutation(currentFlow, node);
                            }
                        }
                    }
                }
            }
            function bindDeleteExpressionFlow(node) {
                bindEachChild(node);
                if (node.expression.kind === 187 /* PropertyAccessExpression */) {
                    bindAssignmentTargetFlow(node.expression);
                }
            }
            function bindConditionalExpressionFlow(node) {
                var trueLabel = createBranchLabel();
                var falseLabel = createBranchLabel();
                var postExpressionLabel = createBranchLabel();
                bindCondition(node.condition, trueLabel, falseLabel);
                currentFlow = finishFlowLabel(trueLabel);
                bind(node.questionToken);
                bind(node.whenTrue);
                addAntecedent(postExpressionLabel, currentFlow);
                currentFlow = finishFlowLabel(falseLabel);
                bind(node.colonToken);
                bind(node.whenFalse);
                addAntecedent(postExpressionLabel, currentFlow);
                currentFlow = finishFlowLabel(postExpressionLabel);
            }
            function bindInitializedVariableFlow(node) {
                var name = !ts.isOmittedExpression(node) ? node.name : undefined;
                if (ts.isBindingPattern(name)) {
                    for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
                        var child = _a[_i];
                        bindInitializedVariableFlow(child);
                    }
                }
                else {
                    currentFlow = createFlowAssignment(currentFlow, node);
                }
            }
            function bindVariableDeclarationFlow(node) {
                bindEachChild(node);
                if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
                    bindInitializedVariableFlow(node);
                }
            }
            function bindJSDocTypeAlias(node) {
                if (node.fullName) {
                    setParentPointers(node, node.fullName);
                }
            }
            function bindCallExpressionFlow(node) {
                // If the target of the call expression is a function expression or arrow function we have
                // an immediately invoked function expression (IIFE). Initialize the flowNode property to
                // the current control flow (which includes evaluation of the IIFE arguments).
                var expr = node.expression;
                while (expr.kind === 193 /* ParenthesizedExpression */) {
                    expr = expr.expression;
                }
                if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) {
                    bindEach(node.typeArguments);
                    bindEach(node.arguments);
                    bind(node.expression);
                }
                else {
                    bindEachChild(node);
                }
                if (node.expression.kind === 187 /* PropertyAccessExpression */) {
                    var propertyAccess = node.expression;
                    if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
                        currentFlow = createFlowArrayMutation(currentFlow, node);
                    }
                }
            }
            function getContainerFlags(node) {
                switch (node.kind) {
                    case 207 /* ClassExpression */:
                    case 238 /* ClassDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 186 /* ObjectLiteralExpression */:
                    case 166 /* TypeLiteral */:
                    case 290 /* JSDocTypeLiteral */:
                    case 266 /* JsxAttributes */:
                        return 1 /* IsContainer */;
                    case 239 /* InterfaceDeclaration */:
                        return 1 /* IsContainer */ | 64 /* IsInterface */;
                    case 242 /* ModuleDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 179 /* MappedType */:
                        return 1 /* IsContainer */ | 32 /* HasLocals */;
                    case 277 /* SourceFile */:
                        return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
                    case 154 /* MethodDeclaration */:
                        if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
                            return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
                        }
                    // falls through
                    case 155 /* Constructor */:
                    case 237 /* FunctionDeclaration */:
                    case 153 /* MethodSignature */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 158 /* CallSignature */:
                    case 291 /* JSDocSignature */:
                    case 287 /* JSDocFunctionType */:
                    case 163 /* FunctionType */:
                    case 159 /* ConstructSignature */:
                    case 160 /* IndexSignature */:
                    case 164 /* ConstructorType */:
                        return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
                    case 243 /* ModuleBlock */:
                        return 4 /* IsControlFlowContainer */;
                    case 152 /* PropertyDeclaration */:
                        return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
                    case 272 /* CatchClause */:
                    case 223 /* ForStatement */:
                    case 224 /* ForInStatement */:
                    case 225 /* ForOfStatement */:
                    case 244 /* CaseBlock */:
                        return 2 /* IsBlockScopedContainer */;
                    case 216 /* Block */:
                        // do not treat blocks directly inside a function as a block-scoped-container.
                        // Locals that reside in this block should go to the function locals. Otherwise 'x'
                        // would not appear to be a redeclaration of a block scoped local in the following
                        // example:
                        //
                        //      function foo() {
                        //          var x;
                        //          let x;
                        //      }
                        //
                        // If we placed 'var x' into the function locals and 'let x' into the locals of
                        // the block, then there would be no collision.
                        //
                        // By not creating a new block-scoped-container here, we ensure that both 'var x'
                        // and 'let x' go into the Function-container's locals, and we do get a collision
                        // conflict.
                        return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
                }
                return 0 /* None */;
            }
            function addToContainerChain(next) {
                if (lastContainer) {
                    lastContainer.nextContainer = next;
                }
                lastContainer = next;
            }
            function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
                switch (container.kind) {
                    // Modules, source files, and classes need specialized handling for how their
                    // members are declared (for example, a member of a class will go into a specific
                    // symbol table depending on if it is static or not). We defer to specialized
                    // handlers to take care of declaring these child members.
                    case 242 /* ModuleDeclaration */:
                        return declareModuleMember(node, symbolFlags, symbolExcludes);
                    case 277 /* SourceFile */:
                        return declareSourceFileMember(node, symbolFlags, symbolExcludes);
                    case 207 /* ClassExpression */:
                    case 238 /* ClassDeclaration */:
                        return declareClassMember(node, symbolFlags, symbolExcludes);
                    case 241 /* EnumDeclaration */:
                        return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
                    case 166 /* TypeLiteral */:
                    case 290 /* JSDocTypeLiteral */:
                    case 186 /* ObjectLiteralExpression */:
                    case 239 /* InterfaceDeclaration */:
                    case 266 /* JsxAttributes */:
                        // Interface/Object-types always have their children added to the 'members' of
                        // their container. They are only accessible through an instance of their
                        // container, and are never in scope otherwise (even inside the body of the
                        // object / type / interface declaring them). An exception is type parameters,
                        // which are in scope without qualification (similar to 'locals').
                        return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
                    case 163 /* FunctionType */:
                    case 164 /* ConstructorType */:
                    case 158 /* CallSignature */:
                    case 159 /* ConstructSignature */:
                    case 291 /* JSDocSignature */:
                    case 160 /* IndexSignature */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 155 /* Constructor */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                    case 287 /* JSDocFunctionType */:
                    case 302 /* JSDocTypedefTag */:
                    case 295 /* JSDocCallbackTag */:
                    case 240 /* TypeAliasDeclaration */:
                    case 179 /* MappedType */:
                        // All the children of these container types are never visible through another
                        // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
                        // they're only accessed 'lexically' (i.e. from code that exists underneath
                        // their container in the tree). To accomplish this, we simply add their declared
                        // symbol to the 'locals' of the container.  These symbols can then be found as
                        // the type checker walks up the containers, checking them for matching names.
                        return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
                }
            }
            function declareClassMember(node, symbolFlags, symbolExcludes) {
                return ts.hasModifier(node, 32 /* Static */)
                    ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
                    : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
            }
            function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
                return ts.isExternalModule(file)
                    ? declareModuleMember(node, symbolFlags, symbolExcludes)
                    : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
            }
            function hasExportDeclarations(node) {
                var body = node.kind === 277 /* SourceFile */ ? node : node.body;
                if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) {
                    for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
                        var stat = _a[_i];
                        if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) {
                            return true;
                        }
                    }
                }
                return false;
            }
            function setExportContextFlag(node) {
                // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
                // declarations with export modifiers) is an export context in which declarations are implicitly exported.
                if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) {
                    node.flags |= 32 /* ExportContext */;
                }
                else {
                    node.flags &= ~32 /* ExportContext */;
                }
            }
            function bindModuleDeclaration(node) {
                setExportContextFlag(node);
                if (ts.isAmbientModule(node)) {
                    if (ts.hasModifier(node, 1 /* Export */)) {
                        errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
                    }
                    if (ts.isModuleAugmentationExternal(node)) {
                        declareModuleSymbol(node);
                    }
                    else {
                        var pattern = void 0;
                        if (node.name.kind === 9 /* StringLiteral */) {
                            var text = node.name.text;
                            if (ts.hasZeroOrOneAsteriskCharacter(text)) {
                                pattern = ts.tryParsePattern(text);
                            }
                            else {
                                errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
                            }
                        }
                        var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
                        file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
                    }
                }
                else {
                    var state = declareModuleSymbol(node);
                    if (state !== 0 /* NonInstantiated */) {
                        var symbol = node.symbol;
                        // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
                        symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
                            // Current must be `const enum` only
                            && state === 2 /* ConstEnumOnly */
                            // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
                            && symbol.constEnumOnlyModule !== false;
                    }
                }
            }
            function declareModuleSymbol(node) {
                var state = getModuleInstanceState(node);
                var instantiated = state !== 0 /* NonInstantiated */;
                declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
                return state;
            }
            function bindFunctionOrConstructorType(node) {
                // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
                // to the one we would get for: { <...>(...): T }
                //
                // We do that by making an anonymous type literal symbol, and then setting the function
                // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
                // from an actual type literal symbol you would have gotten had you used the long form.
                var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
                addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
                var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
                addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
                typeLiteralSymbol.members = ts.createSymbolTable();
                typeLiteralSymbol.members.set(symbol.escapedName, symbol);
            }
            function bindObjectLiteralExpression(node) {
                var ElementKind;
                (function (ElementKind) {
                    ElementKind[ElementKind["Property"] = 1] = "Property";
                    ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
                })(ElementKind || (ElementKind = {}));
                if (inStrictMode) {
                    var seen = ts.createUnderscoreEscapedMap();
                    for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
                        var prop = _a[_i];
                        if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) {
                            continue;
                        }
                        var identifier = prop.name;
                        // ECMA-262 11.1.5 Object Initializer
                        // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
                        // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
                        // IsDataDescriptor(propId.descriptor) is true.
                        //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
                        //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
                        //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
                        // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
                        var currentKind = prop.kind === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */
                            ? 1 /* Property */
                            : 2 /* Accessor */;
                        var existingKind = seen.get(identifier.escapedText);
                        if (!existingKind) {
                            seen.set(identifier.escapedText, currentKind);
                            continue;
                        }
                        if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
                            var span = ts.getErrorSpanForNode(file, identifier);
                            file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
                        }
                    }
                }
                return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
            }
            function bindJsxAttributes(node) {
                return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
            }
            function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
                return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
            }
            function bindAnonymousDeclaration(node, symbolFlags, name) {
                var symbol = createSymbol(symbolFlags, name);
                if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
                    symbol.parent = container.symbol;
                }
                addDeclarationToSymbol(symbol, node, symbolFlags);
                return symbol;
            }
            function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
                switch (blockScopeContainer.kind) {
                    case 242 /* ModuleDeclaration */:
                        declareModuleMember(node, symbolFlags, symbolExcludes);
                        break;
                    case 277 /* SourceFile */:
                        if (ts.isExternalOrCommonJsModule(container)) {
                            declareModuleMember(node, symbolFlags, symbolExcludes);
                            break;
                        }
                    // falls through
                    default:
                        if (!blockScopeContainer.locals) {
                            blockScopeContainer.locals = ts.createSymbolTable();
                            addToContainerChain(blockScopeContainer);
                        }
                        declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
                }
            }
            function delayedBindJSDocTypedefTag() {
                if (!delayedTypeAliases) {
                    return;
                }
                var saveContainer = container;
                var saveLastContainer = lastContainer;
                var saveBlockScopeContainer = blockScopeContainer;
                var saveParent = parent;
                var saveCurrentFlow = currentFlow;
                for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
                    var typeAlias = delayedTypeAliases_1[_i];
                    var host = ts.getJSDocHost(typeAlias);
                    container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
                    blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
                    currentFlow = { flags: 2 /* Start */ };
                    parent = typeAlias;
                    bind(typeAlias.typeExpression);
                    if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) {
                        parent = typeAlias.parent;
                        bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
                    }
                    else {
                        bind(typeAlias.fullName);
                    }
                }
                container = saveContainer;
                lastContainer = saveLastContainer;
                blockScopeContainer = saveBlockScopeContainer;
                parent = saveParent;
                currentFlow = saveCurrentFlow;
            }
            // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
            // check for reserved words used as identifiers in strict mode code.
            function checkStrictModeIdentifier(node) {
                if (inStrictMode &&
                    node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ &&
                    node.originalKeywordKind <= 116 /* LastFutureReservedWord */ &&
                    !ts.isIdentifierName(node) &&
                    !(node.flags & 4194304 /* Ambient */)) {
                    // Report error only if there are no parse errors in file
                    if (!file.parseDiagnostics.length) {
                        file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
                    }
                }
            }
            function getStrictModeIdentifierMessage(node) {
                // Provide specialized messages to help the user understand why we think they're in
                // strict mode.
                if (ts.getContainingClass(node)) {
                    return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
                }
                if (file.externalModuleIndicator) {
                    return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
                }
                return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
            }
            function checkStrictModeBinaryExpression(node) {
                if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
                    // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
                    // Assignment operator(11.13) or of a PostfixExpression(11.3)
                    checkStrictModeEvalOrArguments(node, node.left);
                }
            }
            function checkStrictModeCatchClause(node) {
                // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
                // Catch production is eval or arguments
                if (inStrictMode && node.variableDeclaration) {
                    checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
                }
            }
            function checkStrictModeDeleteExpression(node) {
                // Grammar checking
                if (inStrictMode && node.expression.kind === 71 /* Identifier */) {
                    // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
                    // UnaryExpression is a direct reference to a variable, function argument, or function name
                    var span = ts.getErrorSpanForNode(file, node.expression);
                    file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
                }
            }
            function isEvalOrArgumentsIdentifier(node) {
                return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
            }
            function checkStrictModeEvalOrArguments(contextNode, name) {
                if (name && name.kind === 71 /* Identifier */) {
                    var identifier = name;
                    if (isEvalOrArgumentsIdentifier(identifier)) {
                        // We check first if the name is inside class declaration or class expression; if so give explicit message
                        // otherwise report generic error message.
                        var span = ts.getErrorSpanForNode(file, name);
                        file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
                    }
                }
            }
            function getStrictModeEvalOrArgumentsMessage(node) {
                // Provide specialized messages to help the user understand why we think they're in
                // strict mode.
                if (ts.getContainingClass(node)) {
                    return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
                }
                if (file.externalModuleIndicator) {
                    return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
                }
                return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
            }
            function checkStrictModeFunctionName(node) {
                if (inStrictMode) {
                    // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
                    checkStrictModeEvalOrArguments(node, node.name);
                }
            }
            function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
                // Provide specialized messages to help the user understand why we think they're in
                // strict mode.
                if (ts.getContainingClass(node)) {
                    return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode;
                }
                if (file.externalModuleIndicator) {
                    return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
                }
                return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
            }
            function checkStrictModeFunctionDeclaration(node) {
                if (languageVersion < 2 /* ES2015 */) {
                    // Report error if function is not top level function declaration
                    if (blockScopeContainer.kind !== 277 /* SourceFile */ &&
                        blockScopeContainer.kind !== 242 /* ModuleDeclaration */ &&
                        !ts.isFunctionLike(blockScopeContainer)) {
                        // We check first if the name is inside class declaration or class expression; if so give explicit message
                        // otherwise report generic error message.
                        var errorSpan = ts.getErrorSpanForNode(file, node);
                        file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
                    }
                }
            }
            function checkStrictModeNumericLiteral(node) {
                if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
                    file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
                }
            }
            function checkStrictModePostfixUnaryExpression(node) {
                // Grammar checking
                // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
                // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
                // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
                if (inStrictMode) {
                    checkStrictModeEvalOrArguments(node, node.operand);
                }
            }
            function checkStrictModePrefixUnaryExpression(node) {
                // Grammar checking
                if (inStrictMode) {
                    if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) {
                        checkStrictModeEvalOrArguments(node, node.operand);
                    }
                }
            }
            function checkStrictModeWithStatement(node) {
                // Grammar checking for withStatement
                if (inStrictMode) {
                    errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
                }
            }
            function checkStrictModeLabeledStatement(node) {
                // Grammar checking for labeledStatement
                if (inStrictMode && options.target >= 2 /* ES2015 */) {
                    if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
                        errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
                    }
                }
            }
            function errorOnFirstToken(node, message, arg0, arg1, arg2) {
                var span = ts.getSpanOfTokenAtPosition(file, node.pos);
                file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
            }
            function errorOrSuggestionOnNode(isError, node, message) {
                errorOrSuggestionOnRange(isError, node, node, message);
            }
            function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
                addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
            }
            function addErrorOrSuggestionDiagnostic(isError, range, message) {
                var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
                if (isError) {
                    file.bindDiagnostics.push(diag);
                }
                else {
                    file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
                }
            }
            function bind(node) {
                if (!node) {
                    return;
                }
                node.parent = parent;
                var saveInStrictMode = inStrictMode;
                // Even though in the AST the jsdoc @typedef node belongs to the current node,
                // its symbol might be in the same scope with the current node's symbol. Consider:
                //
                //     /** @typedef {string | number} MyType */
                //     function foo();
                //
                // Here the current node is "foo", which is a container, but the scope of "MyType" should
                // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
                // and skip binding this tag later when binding all the other jsdoc tags.
                // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
                // and then potentially add the symbol to an appropriate symbol table. Possible
                // destination symbol tables are:
                //
                //  1) The 'exports' table of the current container's symbol.
                //  2) The 'members' table of the current container's symbol.
                //  3) The 'locals' table of the current container.
                //
                // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
                // (like TypeLiterals for example) will not be put in any table.
                bindWorker(node);
                // Then we recurse into the children of the node to bind them as well. For certain
                // symbols we do specialized work when we recurse. For example, we'll keep track of
                // the current 'container' node when it changes. This helps us know which symbol table
                // a local should go into for example. Since terminal nodes are known not to have
                // children, as an optimization we don't process those.
                if (node.kind > 145 /* LastToken */) {
                    var saveParent = parent;
                    parent = node;
                    var containerFlags = getContainerFlags(node);
                    if (containerFlags === 0 /* None */) {
                        bindChildren(node);
                    }
                    else {
                        bindContainer(node, containerFlags);
                    }
                    parent = saveParent;
                }
                else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
                    subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
                    var saveParent = parent;
                    if (node.kind === 1 /* EndOfFileToken */)
                        parent = node;
                    bindJSDoc(node);
                    parent = saveParent;
                }
                inStrictMode = saveInStrictMode;
            }
            function bindJSDoc(node) {
                if (ts.hasJSDocNodes(node)) {
                    if (ts.isInJSFile(node)) {
                        for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
                            var j = _a[_i];
                            bind(j);
                        }
                    }
                    else {
                        for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
                            var j = _c[_b];
                            setParentPointers(node, j);
                        }
                    }
                }
            }
            function updateStrictModeStatementList(statements) {
                if (!inStrictMode) {
                    for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
                        var statement = statements_1[_i];
                        if (!ts.isPrologueDirective(statement)) {
                            return;
                        }
                        if (isUseStrictPrologueDirective(statement)) {
                            inStrictMode = true;
                            return;
                        }
                    }
                }
            }
            /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
            function isUseStrictPrologueDirective(node) {
                var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
                // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
                // string to contain unicode escapes (as per ES5).
                return nodeText === '"use strict"' || nodeText === "'use strict'";
            }
            function bindWorker(node) {
                switch (node.kind) {
                    /* Strict mode checks */
                    case 71 /* Identifier */:
                        // for typedef type names with namespaces, bind the new jsdoc type symbol here
                        // because it requires all containing namespaces to be in effect, namely the
                        // current "blockScopeContainer" needs to be set to its immediate namespace parent.
                        if (node.isInJSDocNamespace) {
                            var parentNode = node.parent;
                            while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
                                parentNode = parentNode.parent;
                            }
                            bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
                            break;
                        }
                    // falls through
                    case 99 /* ThisKeyword */:
                        if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) {
                            node.flowNode = currentFlow;
                        }
                        return checkStrictModeIdentifier(node);
                    case 187 /* PropertyAccessExpression */:
                    case 188 /* ElementAccessExpression */:
                        if (currentFlow && isNarrowableReference(node)) {
                            node.flowNode = currentFlow;
                        }
                        if (ts.isSpecialPropertyDeclaration(node)) {
                            bindSpecialPropertyDeclaration(node);
                        }
                        if (ts.isInJSFile(node) &&
                            file.commonJsModuleIndicator &&
                            ts.isModuleExportsPropertyAccessExpression(node) &&
                            !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
                            declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */);
                        }
                        break;
                    case 202 /* BinaryExpression */:
                        var specialKind = ts.getAssignmentDeclarationKind(node);
                        switch (specialKind) {
                            case 1 /* ExportsProperty */:
                                bindExportsPropertyAssignment(node);
                                break;
                            case 2 /* ModuleExports */:
                                bindModuleExportsAssignment(node);
                                break;
                            case 3 /* PrototypeProperty */:
                                bindPrototypePropertyAssignment(node.left, node);
                                break;
                            case 6 /* Prototype */:
                                bindPrototypeAssignment(node);
                                break;
                            case 4 /* ThisProperty */:
                                bindThisPropertyAssignment(node);
                                break;
                            case 5 /* Property */:
                                bindSpecialPropertyAssignment(node);
                                break;
                            case 0 /* None */:
                                // Nothing to do
                                break;
                            default:
                                ts.Debug.fail("Unknown special property assignment kind");
                        }
                        return checkStrictModeBinaryExpression(node);
                    case 272 /* CatchClause */:
                        return checkStrictModeCatchClause(node);
                    case 196 /* DeleteExpression */:
                        return checkStrictModeDeleteExpression(node);
                    case 8 /* NumericLiteral */:
                        return checkStrictModeNumericLiteral(node);
                    case 201 /* PostfixUnaryExpression */:
                        return checkStrictModePostfixUnaryExpression(node);
                    case 200 /* PrefixUnaryExpression */:
                        return checkStrictModePrefixUnaryExpression(node);
                    case 229 /* WithStatement */:
                        return checkStrictModeWithStatement(node);
                    case 231 /* LabeledStatement */:
                        return checkStrictModeLabeledStatement(node);
                    case 176 /* ThisType */:
                        seenThisKeyword = true;
                        return;
                    case 161 /* TypePredicate */:
                        break; // Binding the children will handle everything
                    case 148 /* TypeParameter */:
                        return bindTypeParameter(node);
                    case 149 /* Parameter */:
                        return bindParameter(node);
                    case 235 /* VariableDeclaration */:
                        return bindVariableDeclarationOrBindingElement(node);
                    case 184 /* BindingElement */:
                        node.flowNode = currentFlow;
                        return bindVariableDeclarationOrBindingElement(node);
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                        return bindPropertyWorker(node);
                    case 273 /* PropertyAssignment */:
                    case 274 /* ShorthandPropertyAssignment */:
                        return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
                    case 276 /* EnumMember */:
                        return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */);
                    case 158 /* CallSignature */:
                    case 159 /* ConstructSignature */:
                    case 160 /* IndexSignature */:
                        return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                        // If this is an ObjectLiteralExpression method, then it sits in the same space
                        // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
                        // so that it will conflict with any other object literal members with the same
                        // name.
                        return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */);
                    case 237 /* FunctionDeclaration */:
                        return bindFunctionDeclaration(node);
                    case 155 /* Constructor */:
                        return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
                    case 156 /* GetAccessor */:
                        return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */);
                    case 157 /* SetAccessor */:
                        return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
                    case 163 /* FunctionType */:
                    case 287 /* JSDocFunctionType */:
                    case 291 /* JSDocSignature */:
                    case 164 /* ConstructorType */:
                        return bindFunctionOrConstructorType(node);
                    case 166 /* TypeLiteral */:
                    case 290 /* JSDocTypeLiteral */:
                    case 179 /* MappedType */:
                        return bindAnonymousTypeWorker(node);
                    case 186 /* ObjectLiteralExpression */:
                        return bindObjectLiteralExpression(node);
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        return bindFunctionExpression(node);
                    case 189 /* CallExpression */:
                        if (ts.isInJSFile(node)) {
                            bindCallExpression(node);
                        }
                        break;
                    // Members of classes, interfaces, and modules
                    case 207 /* ClassExpression */:
                    case 238 /* ClassDeclaration */:
                        // All classes are automatically in strict mode in ES6.
                        inStrictMode = true;
                        return bindClassLikeDeclaration(node);
                    case 239 /* InterfaceDeclaration */:
                        return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */);
                    case 240 /* TypeAliasDeclaration */:
                        return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */);
                    case 241 /* EnumDeclaration */:
                        return bindEnumDeclaration(node);
                    case 242 /* ModuleDeclaration */:
                        return bindModuleDeclaration(node);
                    // Jsx-attributes
                    case 266 /* JsxAttributes */:
                        return bindJsxAttributes(node);
                    case 265 /* JsxAttribute */:
                        return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
                    // Imports and exports
                    case 246 /* ImportEqualsDeclaration */:
                    case 249 /* NamespaceImport */:
                    case 251 /* ImportSpecifier */:
                    case 255 /* ExportSpecifier */:
                        return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
                    case 245 /* NamespaceExportDeclaration */:
                        return bindNamespaceExportDeclaration(node);
                    case 248 /* ImportClause */:
                        return bindImportClause(node);
                    case 253 /* ExportDeclaration */:
                        return bindExportDeclaration(node);
                    case 252 /* ExportAssignment */:
                        return bindExportAssignment(node);
                    case 277 /* SourceFile */:
                        updateStrictModeStatementList(node.statements);
                        return bindSourceFileIfExternalModule();
                    case 216 /* Block */:
                        if (!ts.isFunctionLike(node.parent)) {
                            return;
                        }
                    // falls through
                    case 243 /* ModuleBlock */:
                        return updateStrictModeStatementList(node.statements);
                    case 297 /* JSDocParameterTag */:
                        if (node.parent.kind === 291 /* JSDocSignature */) {
                            return bindParameter(node);
                        }
                        if (node.parent.kind !== 290 /* JSDocTypeLiteral */) {
                            break;
                        }
                    // falls through
                    case 303 /* JSDocPropertyTag */:
                        var propTag = node;
                        var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ?
                            4 /* Property */ | 16777216 /* Optional */ :
                            4 /* Property */;
                        return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
                    case 302 /* JSDocTypedefTag */:
                    case 295 /* JSDocCallbackTag */:
                        return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
                }
            }
            function bindPropertyWorker(node) {
                return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
            }
            function bindAnonymousTypeWorker(node) {
                return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
            }
            function bindSourceFileIfExternalModule() {
                setExportContextFlag(file);
                if (ts.isExternalModule(file)) {
                    bindSourceFileAsExternalModule();
                }
                else if (ts.isJsonSourceFile(file)) {
                    bindSourceFileAsExternalModule();
                    // Create symbol equivalent for the module.exports = {}
                    var originalSymbol = file.symbol;
                    declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
                    file.symbol = originalSymbol;
                }
            }
            function bindSourceFileAsExternalModule() {
                bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
            }
            function bindExportAssignment(node) {
                if (!container.symbol || !container.symbol.exports) {
                    // Export assignment in some sort of block construct
                    bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
                }
                else {
                    var flags = ts.exportAssignmentIsAlias(node)
                        // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
                        ? 2097152 /* Alias */
                        // An export default clause with any other expression exports a value
                        : 4 /* Property */;
                    // If there is an `export default x;` alias declaration, can't `export default` anything else.
                    // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
                    var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
                    if (node.isExportEquals) {
                        // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
                        setValueDeclaration(symbol, node);
                    }
                }
            }
            function bindNamespaceExportDeclaration(node) {
                if (node.modifiers && node.modifiers.length) {
                    file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
                }
                if (node.parent.kind !== 277 /* SourceFile */) {
                    file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level));
                    return;
                }
                else {
                    var parent_1 = node.parent;
                    if (!ts.isExternalModule(parent_1)) {
                        file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files));
                        return;
                    }
                    if (!parent_1.isDeclarationFile) {
                        file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
                        return;
                    }
                }
                file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
                declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
            }
            function bindExportDeclaration(node) {
                if (!container.symbol || !container.symbol.exports) {
                    // Export * in some sort of block construct
                    bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
                }
                else if (!node.exportClause) {
                    // All export * declarations are collected in an __export symbol
                    declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
                }
            }
            function bindImportClause(node) {
                if (node.name) {
                    declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
                }
            }
            function setCommonJsModuleIndicator(node) {
                if (file.externalModuleIndicator) {
                    return false;
                }
                if (!file.commonJsModuleIndicator) {
                    file.commonJsModuleIndicator = node;
                    bindSourceFileAsExternalModule();
                }
                return true;
            }
            function bindExportsPropertyAssignment(node) {
                // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
                // expression is the declaration
                if (!setCommonJsModuleIndicator(node)) {
                    return;
                }
                var lhs = node.left;
                var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) {
                    if (symbol) {
                        addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
                    }
                    return symbol;
                });
                if (symbol) {
                    var flags = ts.isClassExpression(node.right) ?
                        4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
                        4 /* Property */ | 1048576 /* ExportValue */;
                    declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */);
                }
            }
            function bindModuleExportsAssignment(node) {
                // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
                // is still pointing to 'module.exports'.
                // We do not want to consider this as 'export=' since a module can have only one of these.
                // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
                if (!setCommonJsModuleIndicator(node)) {
                    return;
                }
                var assignedExpression = ts.getRightMostAssignedExpression(node.right);
                if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
                    return;
                }
                // 'module.exports = expr' assignment
                var flags = ts.exportAssignmentIsAlias(node)
                    ? 2097152 /* Alias */
                    : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
                declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */);
            }
            function bindThisPropertyAssignment(node) {
                ts.Debug.assert(ts.isInJSFile(node));
                var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
                switch (thisContainer.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                        var constructorSymbol = thisContainer.symbol;
                        // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
                        if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) {
                            var l = thisContainer.parent.left;
                            if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) {
                                constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
                            }
                        }
                        if (constructorSymbol) {
                            // Declare a 'member' if the container is an ES5 class or ES6 constructor
                            constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
                            // It's acceptable for multiple 'this' assignments of the same identifier to occur
                            declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */);
                        }
                        break;
                    case 155 /* Constructor */:
                    case 152 /* PropertyDeclaration */:
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        // this.foo assignment in a JavaScript class
                        // Bind this property to the containing class
                        var containingClass = thisContainer.parent;
                        var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
                        declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
                        break;
                    case 277 /* SourceFile */:
                        // this.foo assignment in a source file
                        // Do not bind. It would be nice to support this someday though.
                        break;
                    default:
                        ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
                }
            }
            function bindSpecialPropertyDeclaration(node) {
                if (node.expression.kind === 99 /* ThisKeyword */) {
                    bindThisPropertyAssignment(node);
                }
                else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) {
                    if (ts.isPrototypeAccess(node.expression)) {
                        bindPrototypePropertyAssignment(node, node.parent);
                    }
                    else {
                        bindStaticPropertyAssignment(node);
                    }
                }
            }
            /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
            function bindPrototypeAssignment(node) {
                node.left.parent = node;
                node.right.parent = node;
                var lhs = node.left;
                bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false);
            }
            /**
             * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
             * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
             */
            function bindPrototypePropertyAssignment(lhs, parent) {
                // Look up the function in the local scope, since prototype assignments should
                // follow the function declaration
                var classPrototype = lhs.expression;
                var constructorFunction = classPrototype.expression;
                // Fix up parent pointers since we're going to use these nodes before we bind into them
                lhs.parent = parent;
                constructorFunction.parent = classPrototype;
                classPrototype.parent = lhs;
                bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true);
            }
            function bindSpecialPropertyAssignment(node) {
                var lhs = node.left;
                // Class declarations in Typescript do not allow property declarations
                var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression);
                if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
                    return;
                }
                // Fix up parent pointers since we're going to use these nodes before we bind into them
                node.left.parent = node;
                node.right.parent = node;
                if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) {
                    // This can be an alias for the 'exports' or 'module.exports' names, e.g.
                    //    var util = module.exports;
                    //    util.property = function ...
                    bindExportsPropertyAssignment(node);
                }
                else {
                    bindStaticPropertyAssignment(lhs);
                }
            }
            /**
             * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared.
             * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
             */
            function bindStaticPropertyAssignment(node) {
                node.expression.parent = node;
                bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false);
            }
            function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
                var namespaceSymbol = lookupSymbolForPropertyAccess(name);
                var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
                    ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */
                    : propertyAccess.parent.parent.kind === 277 /* SourceFile */;
                if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) {
                    // make symbols or add declarations for intermediate containers
                    var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
                    var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
                    namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) {
                        if (symbol) {
                            addDeclarationToSymbol(symbol, id, flags_1);
                            return symbol;
                        }
                        else {
                            var table = parent ? parent.exports :
                                file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
                            return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
                        }
                    });
                }
                if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
                    return;
                }
                // Set up the members collection if it doesn't exist already
                var symbolTable = isPrototypeProperty ?
                    (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
                    (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
                var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess));
                var includes = isMethod ? 8192 /* Method */ : 4 /* Property */;
                var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */;
                declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
            }
            /**
             * Javascript expando values are:
             * - Functions
             * - classes
             * - namespaces
             * - variables initialized with function expressions
             * -                       with class expressions
             * -                       with empty object literals
             * -                       with non-empty object literals if assigned to the prototype property
             */
            function isExpandoSymbol(symbol) {
                if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
                    return true;
                }
                var node = symbol.valueDeclaration;
                var init = !node ? undefined :
                    ts.isVariableDeclaration(node) ? node.initializer :
                        ts.isBinaryExpression(node) ? node.right :
                            ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
                                undefined;
                init = init && ts.getRightMostAssignedExpression(init);
                if (init) {
                    var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
                    return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment);
                }
                return false;
            }
            function getParentOfBinaryExpression(expr) {
                while (ts.isBinaryExpression(expr.parent)) {
                    expr = expr.parent;
                }
                return expr.parent;
            }
            function lookupSymbolForPropertyAccess(node, lookupContainer) {
                if (lookupContainer === void 0) {
                    lookupContainer = container;
                }
                if (ts.isIdentifier(node)) {
                    return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
                }
                else {
                    var symbol = lookupSymbolForPropertyAccess(node.expression);
                    return symbol && symbol.exports && symbol.exports.get(node.name.escapedText);
                }
            }
            function forEachIdentifierInEntityName(e, parent, action) {
                if (isExportsOrModuleExportsOrAlias(file, e)) {
                    return file.symbol;
                }
                else if (ts.isIdentifier(e)) {
                    return action(e, lookupSymbolForPropertyAccess(e), parent);
                }
                else {
                    var s = forEachIdentifierInEntityName(e.expression, parent, action);
                    if (!s || !s.exports)
                        return ts.Debug.fail();
                    return action(e.name, s.exports.get(e.name.escapedText), s);
                }
            }
            function bindCallExpression(node) {
                // We're only inspecting call expressions to detect CommonJS modules, so we can skip
                // this check if we've already seen the module indicator
                if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
                    setCommonJsModuleIndicator(node);
                }
            }
            function bindClassLikeDeclaration(node) {
                if (node.kind === 238 /* ClassDeclaration */) {
                    bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */);
                }
                else {
                    var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
                    bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
                    // Add name of class expression into the map for semantic classifier
                    if (node.name) {
                        classifiableNames.set(node.name.escapedText, true);
                    }
                }
                var symbol = node.symbol;
                // TypeScript 1.0 spec (April 2014): 8.4
                // Every class automatically contains a static property member named 'prototype', the
                // type of which is an instantiation of the class type with type Any supplied as a type
                // argument for each type parameter. It is an error to explicitly declare a static
                // property member with the name 'prototype'.
                //
                // Note: we check for this here because this class may be merging into a module.  The
                // module might have an exported variable called 'prototype'.  We can't allow that as
                // that would clash with the built-in 'prototype' for the class.
                var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
                var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
                if (symbolExport) {
                    if (node.name) {
                        node.name.parent = node;
                    }
                    file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
                }
                symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
                prototypeSymbol.parent = symbol;
            }
            function bindEnumDeclaration(node) {
                return ts.isEnumConst(node)
                    ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */)
                    : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */);
            }
            function bindVariableDeclarationOrBindingElement(node) {
                if (inStrictMode) {
                    checkStrictModeEvalOrArguments(node, node.name);
                }
                if (!ts.isBindingPattern(node.name)) {
                    var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node);
                    var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */);
                    var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */);
                    if (ts.isBlockOrCatchScoped(node)) {
                        bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes);
                    }
                    else if (ts.isParameterDeclaration(node)) {
                        // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
                        // because its parent chain has already been set up, since parents are set before descending into children.
                        //
                        // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
                        // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
                        // For example:
                        //      function foo([a,a]) {} // Duplicate Identifier error
                        //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
                        //                             // which correctly set excluded symbols
                        declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */);
                    }
                    else {
                        declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes);
                    }
                }
            }
            function bindParameter(node) {
                if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) {
                    return;
                }
                if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
                    // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
                    // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
                    checkStrictModeEvalOrArguments(node, node.name);
                }
                if (ts.isBindingPattern(node.name)) {
                    bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
                }
                else {
                    declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */);
                }
                // If this is a property-parameter, then also declare the property symbol into the
                // containing class.
                if (ts.isParameterPropertyDeclaration(node)) {
                    var classDeclaration = node.parent.parent;
                    declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
                }
            }
            function bindFunctionDeclaration(node) {
                if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) {
                    if (ts.isAsyncFunction(node)) {
                        emitFlags |= 1024 /* HasAsyncFunctions */;
                    }
                }
                checkStrictModeFunctionName(node);
                if (inStrictMode) {
                    checkStrictModeFunctionDeclaration(node);
                    bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */);
                }
                else {
                    declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */);
                }
            }
            function bindFunctionExpression(node) {
                if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) {
                    if (ts.isAsyncFunction(node)) {
                        emitFlags |= 1024 /* HasAsyncFunctions */;
                    }
                }
                if (currentFlow) {
                    node.flowNode = currentFlow;
                }
                checkStrictModeFunctionName(node);
                var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
                return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
            }
            function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
                if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) {
                    emitFlags |= 1024 /* HasAsyncFunctions */;
                }
                if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
                    node.flowNode = currentFlow;
                }
                return ts.hasDynamicName(node)
                    ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
                    : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
            }
            function getInferTypeContainer(node) {
                var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
                return extendsType && extendsType.parent;
            }
            function bindTypeParameter(node) {
                if (ts.isJSDocTemplateTag(node.parent)) {
                    var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
                    if (container_1) {
                        if (!container_1.locals) {
                            container_1.locals = ts.createSymbolTable();
                        }
                        declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
                    }
                    else {
                        declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
                    }
                }
                else if (node.parent.kind === 174 /* InferType */) {
                    var container_2 = getInferTypeContainer(node.parent);
                    if (container_2) {
                        if (!container_2.locals) {
                            container_2.locals = ts.createSymbolTable();
                        }
                        declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
                    }
                    else {
                        bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
                    }
                }
                else {
                    declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */);
                }
            }
            // reachability checks
            function shouldReportErrorOnModuleDeclaration(node) {
                var instanceState = getModuleInstanceState(node);
                return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
            }
            function checkUnreachable(node) {
                if (!(currentFlow.flags & 1 /* Unreachable */)) {
                    return false;
                }
                if (currentFlow === unreachableFlow) {
                    var reportError = 
                    // report error on all statements except empty ones
                    (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) ||
                        // report error on class declarations
                        node.kind === 238 /* ClassDeclaration */ ||
                        // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
                        (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
                    if (reportError) {
                        currentFlow = reportedUnreachableFlow;
                        if (!options.allowUnreachableCode) {
                            // unreachable code is reported if
                            // - user has explicitly asked about it AND
                            // - statement is in not ambient context (statements in ambient context is already an error
                            //   so we should not report extras) AND
                            //   - node is not variable statement OR
                            //   - node is block scoped variable statement OR
                            //   - node is not block scoped variable statement and at least one variable declaration has initializer
                            //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
                            //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
                            var isError_1 = ts.unreachableCodeIsError(options) &&
                                !(node.flags & 4194304 /* Ambient */) &&
                                (!ts.isVariableStatement(node) ||
                                    !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
                                    node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
                            eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
                        }
                    }
                }
                return true;
            }
        }
        function eachUnreachableRange(node, cb) {
            if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
                var statements = node.parent.statements;
                var slice_1 = ts.sliceAfter(statements, node);
                ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
            }
            else {
                cb(node, node);
            }
        }
        // As opposed to a pure declaration like an `interface`
        function isExecutableStatement(s) {
            // Don't remove statements that can validly be used before they appear.
            return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
                // `var x;` may declare a variable used above
                !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
        }
        function isPurelyTypeDeclaration(s) {
            switch (s.kind) {
                case 239 /* InterfaceDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                    return true;
                case 242 /* ModuleDeclaration */:
                    return getModuleInstanceState(s) !== 1 /* Instantiated */;
                case 241 /* EnumDeclaration */:
                    return ts.hasModifier(s, 2048 /* Const */);
                default:
                    return false;
            }
        }
        /* @internal */
        function isExportsOrModuleExportsOrAlias(sourceFile, node) {
            return ts.isExportsIdentifier(node) ||
                ts.isModuleExportsPropertyAccessExpression(node) ||
                ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node);
        }
        ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
        function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) {
            var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
            return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) &&
                !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer);
        }
        function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) {
            return isExportsOrModuleExportsOrAlias(sourceFile, node) ||
                (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right)));
        }
        function lookupSymbolForNameWorker(container, name) {
            var local = container.locals && container.locals.get(name);
            if (local) {
                return local.exportSymbol || local;
            }
            if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
                return container.jsGlobalAugmentations.get(name);
            }
            return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
        }
        /**
         * Computes the transform flags for a node, given the transform flags of its subtree
         *
         * @param node The node to analyze
         * @param subtreeFlags Transform flags computed for this node's subtree
         */
        function computeTransformFlagsForNode(node, subtreeFlags) {
            var kind = node.kind;
            switch (kind) {
                case 189 /* CallExpression */:
                    return computeCallExpression(node, subtreeFlags);
                case 190 /* NewExpression */:
                    return computeNewExpression(node, subtreeFlags);
                case 242 /* ModuleDeclaration */:
                    return computeModuleDeclaration(node, subtreeFlags);
                case 193 /* ParenthesizedExpression */:
                    return computeParenthesizedExpression(node, subtreeFlags);
                case 202 /* BinaryExpression */:
                    return computeBinaryExpression(node, subtreeFlags);
                case 219 /* ExpressionStatement */:
                    return computeExpressionStatement(node, subtreeFlags);
                case 149 /* Parameter */:
                    return computeParameter(node, subtreeFlags);
                case 195 /* ArrowFunction */:
                    return computeArrowFunction(node, subtreeFlags);
                case 194 /* FunctionExpression */:
                    return computeFunctionExpression(node, subtreeFlags);
                case 237 /* FunctionDeclaration */:
                    return computeFunctionDeclaration(node, subtreeFlags);
                case 235 /* VariableDeclaration */:
                    return computeVariableDeclaration(node, subtreeFlags);
                case 236 /* VariableDeclarationList */:
                    return computeVariableDeclarationList(node, subtreeFlags);
                case 217 /* VariableStatement */:
                    return computeVariableStatement(node, subtreeFlags);
                case 231 /* LabeledStatement */:
                    return computeLabeledStatement(node, subtreeFlags);
                case 238 /* ClassDeclaration */:
                    return computeClassDeclaration(node, subtreeFlags);
                case 207 /* ClassExpression */:
                    return computeClassExpression(node, subtreeFlags);
                case 271 /* HeritageClause */:
                    return computeHeritageClause(node, subtreeFlags);
                case 272 /* CatchClause */:
                    return computeCatchClause(node, subtreeFlags);
                case 209 /* ExpressionWithTypeArguments */:
                    return computeExpressionWithTypeArguments(node, subtreeFlags);
                case 155 /* Constructor */:
                    return computeConstructor(node, subtreeFlags);
                case 152 /* PropertyDeclaration */:
                    return computePropertyDeclaration(node, subtreeFlags);
                case 154 /* MethodDeclaration */:
                    return computeMethod(node, subtreeFlags);
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                    return computeAccessor(node, subtreeFlags);
                case 246 /* ImportEqualsDeclaration */:
                    return computeImportEquals(node, subtreeFlags);
                case 187 /* PropertyAccessExpression */:
                    return computePropertyAccess(node, subtreeFlags);
                case 188 /* ElementAccessExpression */:
                    return computeElementAccess(node, subtreeFlags);
                default:
                    return computeOther(node, kind, subtreeFlags);
            }
        }
        ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
        function computeCallExpression(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            var expression = node.expression;
            if (node.typeArguments) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            if (subtreeFlags & 524288 /* ContainsSpread */
                || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) {
                // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
                // node.
                transformFlags |= 192 /* AssertES2015 */;
                // super property or element accesses could be inside lambdas, etc, and need a captured `this`,
                // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
                if (expression.transformFlags & 268435456 /* ContainsSuper */) {
                    transformFlags |= 16384 /* ContainsLexicalThis */;
                }
            }
            if (expression.kind === 91 /* ImportKeyword */) {
                transformFlags |= 67108864 /* ContainsDynamicImport */;
                // A dynamic 'import()' call that contains a lexical 'this' will
                // require a captured 'this' when emitting down-level.
                if (subtreeFlags & 16384 /* ContainsLexicalThis */) {
                    transformFlags |= 32768 /* ContainsCapturedLexicalThis */;
                }
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */;
        }
        function computeNewExpression(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            if (node.typeArguments) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            if (subtreeFlags & 524288 /* ContainsSpread */) {
                // If the this node contains a SpreadElementExpression then it is an ES6
                // node.
                transformFlags |= 192 /* AssertES2015 */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */;
        }
        function computeBinaryExpression(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            var operatorTokenKind = node.operatorToken.kind;
            var leftKind = node.left.kind;
            if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) {
                // Destructuring object assignments with are ES2015 syntax
                // and possibly ESNext if they contain rest
                transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
            }
            else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) {
                // Destructuring assignments are ES2015 syntax.
                transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
            }
            else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */
                || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) {
                // Exponentiation is ES2016 syntax.
                transformFlags |= 32 /* AssertES2016 */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeParameter(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            var name = node.name;
            var initializer = node.initializer;
            var dotDotDotToken = node.dotDotDotToken;
            // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
            // syntax.
            if (node.questionToken
                || node.type
                || subtreeFlags & 4096 /* ContainsDecorators */
                || ts.isThisIdentifier(name)) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            // If a parameter has an accessibility modifier, then it is TypeScript syntax.
            if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
                transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */;
            }
            // parameters with object rest destructuring are ES Next syntax
            if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                transformFlags |= 8 /* AssertESNext */;
            }
            // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
            // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
            if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
                transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* ParameterExcludes */;
        }
        function computeParenthesizedExpression(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            var expression = node.expression;
            var expressionKind = expression.kind;
            var expressionTransformFlags = expression.transformFlags;
            // If the node is synthesized, it means the emitter put the parentheses there,
            // not the user. If we didn't want them, the emitter would not have put them
            // there.
            if (expressionKind === 210 /* AsExpression */
                || expressionKind === 192 /* TypeAssertionExpression */) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            // If the expression of a ParenthesizedExpression is a destructuring assignment,
            // then the ParenthesizedExpression is a destructuring assignment.
            if (expressionTransformFlags & 1024 /* DestructuringAssignment */) {
                transformFlags |= 1024 /* DestructuringAssignment */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~536872257 /* OuterExpressionExcludes */;
        }
        function computeClassDeclaration(node, subtreeFlags) {
            var transformFlags;
            if (ts.hasModifier(node, 2 /* Ambient */)) {
                // An ambient declaration is TypeScript syntax.
                transformFlags = 3 /* AssertTypeScript */;
            }
            else {
                // A ClassDeclaration is ES6 syntax.
                transformFlags = subtreeFlags | 192 /* AssertES2015 */;
                // A class with a parameter property assignment, property initializer, computed property name, or decorator is
                // TypeScript syntax.
                // An exported declaration may be TypeScript syntax, but is handled by the visitor
                // for a namespace declaration.
                if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */)
                    || node.typeParameters) {
                    transformFlags |= 3 /* AssertTypeScript */;
                }
                if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) {
                    // A computed property name containing `this` might need to be rewritten,
                    // so propagate the ContainsLexicalThis flag upward.
                    transformFlags |= 16384 /* ContainsLexicalThis */;
                }
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~942011713 /* ClassExcludes */;
        }
        function computeClassExpression(node, subtreeFlags) {
            // A ClassExpression is ES6 syntax.
            var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
            // A class with a parameter property assignment, property initializer, or decorator is
            // TypeScript syntax.
            if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */
                || node.typeParameters) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) {
                // A computed property name containing `this` might need to be rewritten,
                // so propagate the ContainsLexicalThis flag upward.
                transformFlags |= 16384 /* ContainsLexicalThis */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~942011713 /* ClassExcludes */;
        }
        function computeHeritageClause(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            switch (node.token) {
                case 85 /* ExtendsKeyword */:
                    // An `extends` HeritageClause is ES6 syntax.
                    transformFlags |= 192 /* AssertES2015 */;
                    break;
                case 108 /* ImplementsKeyword */:
                    // An `implements` HeritageClause is TypeScript syntax.
                    transformFlags |= 3 /* AssertTypeScript */;
                    break;
                default:
                    ts.Debug.fail("Unexpected token for heritage clause");
                    break;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeCatchClause(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            if (!node.variableDeclaration) {
                transformFlags |= 8 /* AssertESNext */;
            }
            else if (ts.isBindingPattern(node.variableDeclaration.name)) {
                transformFlags |= 192 /* AssertES2015 */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~940574017 /* CatchClauseExcludes */;
        }
        function computeExpressionWithTypeArguments(node, subtreeFlags) {
            // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
            // extends clause of a class.
            var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
            // If an ExpressionWithTypeArguments contains type arguments, then it
            // is TypeScript syntax.
            if (node.typeArguments) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeConstructor(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            // TypeScript-specific modifiers and overloads are TypeScript syntax
            if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
                || !node.body) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            // function declarations with object rest destructuring are ES Next syntax
            if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                transformFlags |= 8 /* AssertESNext */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~1003668801 /* ConstructorExcludes */;
        }
        function computeMethod(node, subtreeFlags) {
            // A MethodDeclaration is ES6 syntax.
            var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
            // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
            // overloads are TypeScript syntax.
            if (node.decorators
                || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
                || node.typeParameters
                || node.type
                || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
                || !node.body) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            // function declarations with object rest destructuring are ES Next syntax
            if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                transformFlags |= 8 /* AssertESNext */;
            }
            // An async method declaration is ES2017 syntax.
            if (ts.hasModifier(node, 256 /* Async */)) {
                transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
            }
            if (node.asteriskToken) {
                transformFlags |= 768 /* AssertGenerator */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */;
        }
        function computeAccessor(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
            // TypeScript syntax.
            if (node.decorators
                || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
                || node.type
                || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
                || !node.body) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            // function declarations with object rest destructuring are ES Next syntax
            if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                transformFlags |= 8 /* AssertESNext */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */;
        }
        function computePropertyDeclaration(node, subtreeFlags) {
            // A PropertyDeclaration is TypeScript syntax.
            var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
            // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
            // so that it handle the transformation.
            if (node.initializer || ts.isComputedPropertyName(node.name)) {
                transformFlags |= 8192 /* ContainsPropertyInitializer */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeFunctionDeclaration(node, subtreeFlags) {
            var transformFlags;
            var modifierFlags = ts.getModifierFlags(node);
            var body = node.body;
            if (!body || (modifierFlags & 2 /* Ambient */)) {
                // An ambient declaration is TypeScript syntax.
                // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
                transformFlags = 3 /* AssertTypeScript */;
            }
            else {
                transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */;
                // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
                // syntax.
                if (modifierFlags & 2270 /* TypeScriptModifier */
                    || node.typeParameters
                    || node.type) {
                    transformFlags |= 3 /* AssertTypeScript */;
                }
                // An async function declaration is ES2017 syntax.
                if (modifierFlags & 256 /* Async */) {
                    transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
                }
                // function declarations with object rest destructuring are ES Next syntax
                if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                    transformFlags |= 8 /* AssertESNext */;
                }
                // If a FunctionDeclaration's subtree has marked the container as needing to capture the
                // lexical this, or the function contains parameters with initializers, then this node is
                // ES6 syntax.
                if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) {
                    transformFlags |= 192 /* AssertES2015 */;
                }
                // If a FunctionDeclaration is generator function and is the body of a
                // transformed async function, then this node can be transformed to a
                // down-level generator.
                // Currently we do not support transforming any other generator fucntions
                // down level.
                if (node.asteriskToken) {
                    transformFlags |= 768 /* AssertGenerator */;
                }
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~1003935041 /* FunctionExcludes */;
        }
        function computeFunctionExpression(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
            // syntax.
            if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
                || node.typeParameters
                || node.type) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            // An async function expression is ES2017 syntax.
            if (ts.hasModifier(node, 256 /* Async */)) {
                transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
            }
            // function expressions with object rest destructuring are ES Next syntax
            if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                transformFlags |= 8 /* AssertESNext */;
            }
            // If a FunctionExpression's subtree has marked the container as needing to capture the
            // lexical this, or the function contains parameters with initializers, then this node is
            // ES6 syntax.
            if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) {
                transformFlags |= 192 /* AssertES2015 */;
            }
            // If a FunctionExpression is generator function and is the body of a
            // transformed async function, then this node can be transformed to a
            // down-level generator.
            if (node.asteriskToken) {
                transformFlags |= 768 /* AssertGenerator */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~1003935041 /* FunctionExcludes */;
        }
        function computeArrowFunction(node, subtreeFlags) {
            // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
            var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
            // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
            // syntax.
            if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
                || node.typeParameters
                || node.type) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            // An async arrow function is ES2017 syntax.
            if (ts.hasModifier(node, 256 /* Async */)) {
                transformFlags |= 16 /* AssertES2017 */;
            }
            // arrow functions with object rest destructuring are ES Next syntax
            if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                transformFlags |= 8 /* AssertESNext */;
            }
            // If an ArrowFunction contains a lexical this, its container must capture the lexical this.
            if (subtreeFlags & 16384 /* ContainsLexicalThis */) {
                transformFlags |= 32768 /* ContainsCapturedLexicalThis */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~1003902273 /* ArrowFunctionExcludes */;
        }
        function computePropertyAccess(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            // If a PropertyAccessExpression starts with a super keyword, then it is
            // ES6 syntax, and requires a lexical `this` binding.
            if (transformFlags & 134217728 /* Super */) {
                transformFlags ^= 134217728 /* Super */;
                transformFlags |= 268435456 /* ContainsSuper */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~671089985 /* PropertyAccessExcludes */;
        }
        function computeElementAccess(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            var expression = node.expression;
            var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
            // If an ElementAccessExpression starts with a super keyword, then it is
            // ES6 syntax, and requires a lexical `this` binding.
            if (expressionFlags & 134217728 /* Super */) {
                transformFlags &= ~134217728 /* Super */;
                transformFlags |= 268435456 /* ContainsSuper */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~671089985 /* PropertyAccessExcludes */;
        }
        function computeVariableDeclaration(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */;
            // A VariableDeclaration containing ObjectRest is ESNext syntax
            if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
                transformFlags |= 8 /* AssertESNext */;
            }
            // Type annotations are TypeScript syntax.
            if (node.type) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeVariableStatement(node, subtreeFlags) {
            var transformFlags;
            var declarationListTransformFlags = node.declarationList.transformFlags;
            // An ambient declaration is TypeScript syntax.
            if (ts.hasModifier(node, 2 /* Ambient */)) {
                transformFlags = 3 /* AssertTypeScript */;
            }
            else {
                transformFlags = subtreeFlags;
                if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) {
                    transformFlags |= 192 /* AssertES2015 */;
                }
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeLabeledStatement(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
            if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */
                && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
                transformFlags |= 192 /* AssertES2015 */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeImportEquals(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            // An ImportEqualsDeclaration with a namespace reference is TypeScript.
            if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
                transformFlags |= 3 /* AssertTypeScript */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeExpressionStatement(node, subtreeFlags) {
            var transformFlags = subtreeFlags;
            // If the expression of an expression statement is a destructuring assignment,
            // then we treat the statement as ES6 so that we can indicate that we do not
            // need to hold on to the right-hand side.
            if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) {
                transformFlags |= 192 /* AssertES2015 */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~939525441 /* NodeExcludes */;
        }
        function computeModuleDeclaration(node, subtreeFlags) {
            var transformFlags = 3 /* AssertTypeScript */;
            var modifierFlags = ts.getModifierFlags(node);
            if ((modifierFlags & 2 /* Ambient */) === 0) {
                transformFlags |= subtreeFlags;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~977327425 /* ModuleExcludes */;
        }
        function computeVariableDeclarationList(node, subtreeFlags) {
            var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */;
            if (subtreeFlags & 8388608 /* ContainsBindingPattern */) {
                transformFlags |= 192 /* AssertES2015 */;
            }
            // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
            if (node.flags & 3 /* BlockScoped */) {
                transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~948962625 /* VariableDeclarationListExcludes */;
        }
        function computeOther(node, kind, subtreeFlags) {
            // Mark transformations needed for each node
            var transformFlags = subtreeFlags;
            var excludeFlags = 939525441 /* NodeExcludes */;
            switch (kind) {
                case 120 /* AsyncKeyword */:
                case 199 /* AwaitExpression */:
                    // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
                    transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
                    break;
                case 192 /* TypeAssertionExpression */:
                case 210 /* AsExpression */:
                case 306 /* PartiallyEmittedExpression */:
                    // These nodes are TypeScript syntax.
                    transformFlags |= 3 /* AssertTypeScript */;
                    excludeFlags = 536872257 /* OuterExpressionExcludes */;
                    break;
                case 114 /* PublicKeyword */:
                case 112 /* PrivateKeyword */:
                case 113 /* ProtectedKeyword */:
                case 117 /* AbstractKeyword */:
                case 124 /* DeclareKeyword */:
                case 76 /* ConstKeyword */:
                case 241 /* EnumDeclaration */:
                case 276 /* EnumMember */:
                case 211 /* NonNullExpression */:
                case 132 /* ReadonlyKeyword */:
                    // These nodes are TypeScript syntax.
                    transformFlags |= 3 /* AssertTypeScript */;
                    break;
                case 258 /* JsxElement */:
                case 259 /* JsxSelfClosingElement */:
                case 260 /* JsxOpeningElement */:
                case 10 /* JsxText */:
                case 261 /* JsxClosingElement */:
                case 262 /* JsxFragment */:
                case 263 /* JsxOpeningFragment */:
                case 264 /* JsxClosingFragment */:
                case 265 /* JsxAttribute */:
                case 266 /* JsxAttributes */:
                case 267 /* JsxSpreadAttribute */:
                case 268 /* JsxExpression */:
                    // These nodes are Jsx syntax.
                    transformFlags |= 4 /* AssertJsx */;
                    break;
                case 13 /* NoSubstitutionTemplateLiteral */:
                case 14 /* TemplateHead */:
                case 15 /* TemplateMiddle */:
                case 16 /* TemplateTail */:
                case 204 /* TemplateExpression */:
                case 191 /* TaggedTemplateExpression */:
                case 274 /* ShorthandPropertyAssignment */:
                case 115 /* StaticKeyword */:
                case 212 /* MetaProperty */:
                    // These nodes are ES6 syntax.
                    transformFlags |= 192 /* AssertES2015 */;
                    break;
                case 9 /* StringLiteral */:
                    if (node.hasExtendedUnicodeEscape) {
                        transformFlags |= 192 /* AssertES2015 */;
                    }
                    break;
                case 8 /* NumericLiteral */:
                    if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
                        transformFlags |= 192 /* AssertES2015 */;
                    }
                    break;
                case 225 /* ForOfStatement */:
                    // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
                    if (node.awaitModifier) {
                        transformFlags |= 8 /* AssertESNext */;
                    }
                    transformFlags |= 192 /* AssertES2015 */;
                    break;
                case 205 /* YieldExpression */:
                    // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
                    // generator).
                    transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */;
                    break;
                case 119 /* AnyKeyword */:
                case 134 /* NumberKeyword */:
                case 131 /* NeverKeyword */:
                case 135 /* ObjectKeyword */:
                case 137 /* StringKeyword */:
                case 122 /* BooleanKeyword */:
                case 138 /* SymbolKeyword */:
                case 105 /* VoidKeyword */:
                case 148 /* TypeParameter */:
                case 151 /* PropertySignature */:
                case 153 /* MethodSignature */:
                case 158 /* CallSignature */:
                case 159 /* ConstructSignature */:
                case 160 /* IndexSignature */:
                case 161 /* TypePredicate */:
                case 162 /* TypeReference */:
                case 163 /* FunctionType */:
                case 164 /* ConstructorType */:
                case 165 /* TypeQuery */:
                case 166 /* TypeLiteral */:
                case 167 /* ArrayType */:
                case 168 /* TupleType */:
                case 169 /* OptionalType */:
                case 170 /* RestType */:
                case 171 /* UnionType */:
                case 172 /* IntersectionType */:
                case 173 /* ConditionalType */:
                case 174 /* InferType */:
                case 175 /* ParenthesizedType */:
                case 239 /* InterfaceDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                case 176 /* ThisType */:
                case 177 /* TypeOperator */:
                case 178 /* IndexedAccessType */:
                case 179 /* MappedType */:
                case 180 /* LiteralType */:
                case 245 /* NamespaceExportDeclaration */:
                    // Types and signatures are TypeScript syntax, and exclude all other facts.
                    transformFlags = 3 /* AssertTypeScript */;
                    excludeFlags = -3 /* TypeExcludes */;
                    break;
                case 147 /* ComputedPropertyName */:
                    // Even though computed property names are ES6, we don't treat them as such.
                    // This is so that they can flow through PropertyName transforms unaffected.
                    // Instead, we mark the container as ES6, so that it can properly handle the transform.
                    transformFlags |= 2097152 /* ContainsComputedPropertyName */;
                    if (subtreeFlags & 16384 /* ContainsLexicalThis */) {
                        // A computed method name like `[this.getName()](x: string) { ... }` needs to
                        // distinguish itself from the normal case of a method body containing `this`:
                        // `this` inside a method doesn't need to be rewritten (the method provides `this`),
                        // whereas `this` inside a computed name *might* need to be rewritten if the class/object
                        // is inside an arrow function:
                        // `_this = this; () => class K { [_this.getName()]() { ... } }`
                        // To make this distinction, use ContainsLexicalThisInComputedPropertyName
                        // instead of ContainsLexicalThis for computed property names
                        transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */;
                    }
                    break;
                case 206 /* SpreadElement */:
                    transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */;
                    break;
                case 275 /* SpreadAssignment */:
                    transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */;
                    break;
                case 97 /* SuperKeyword */:
                    // This node is ES6 syntax.
                    transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */;
                    excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super`
                    break;
                case 99 /* ThisKeyword */:
                    // Mark this node and its ancestors as containing a lexical `this` keyword.
                    transformFlags |= 16384 /* ContainsLexicalThis */;
                    break;
                case 182 /* ObjectBindingPattern */:
                    transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */;
                    if (subtreeFlags & 524288 /* ContainsRest */) {
                        transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */;
                    }
                    excludeFlags = 940049729 /* BindingPatternExcludes */;
                    break;
                case 183 /* ArrayBindingPattern */:
                    transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */;
                    excludeFlags = 940049729 /* BindingPatternExcludes */;
                    break;
                case 184 /* BindingElement */:
                    transformFlags |= 192 /* AssertES2015 */;
                    if (node.dotDotDotToken) {
                        transformFlags |= 524288 /* ContainsRest */;
                    }
                    break;
                case 150 /* Decorator */:
                    // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
                    transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */;
                    break;
                case 186 /* ObjectLiteralExpression */:
                    excludeFlags = 942740801 /* ObjectLiteralExcludes */;
                    if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) {
                        // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
                        // is an ES6 node.
                        transformFlags |= 192 /* AssertES2015 */;
                    }
                    if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) {
                        // A computed property name containing `this` might need to be rewritten,
                        // so propagate the ContainsLexicalThis flag upward.
                        transformFlags |= 16384 /* ContainsLexicalThis */;
                    }
                    if (subtreeFlags & 1048576 /* ContainsObjectSpread */) {
                        // If an ObjectLiteralExpression contains a spread element, then it
                        // is an ES next node.
                        transformFlags |= 8 /* AssertESNext */;
                    }
                    break;
                case 185 /* ArrayLiteralExpression */:
                case 190 /* NewExpression */:
                    excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */;
                    if (subtreeFlags & 524288 /* ContainsSpread */) {
                        // If the this node contains a SpreadExpression, then it is an ES6
                        // node.
                        transformFlags |= 192 /* AssertES2015 */;
                    }
                    break;
                case 221 /* DoStatement */:
                case 222 /* WhileStatement */:
                case 223 /* ForStatement */:
                case 224 /* ForInStatement */:
                    // A loop containing a block scoped binding *may* need to be transformed from ES6.
                    if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) {
                        transformFlags |= 192 /* AssertES2015 */;
                    }
                    break;
                case 277 /* SourceFile */:
                    if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) {
                        transformFlags |= 192 /* AssertES2015 */;
                    }
                    break;
                case 228 /* ReturnStatement */:
                    // Return statements may require an `await` in ESNext.
                    transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */;
                    break;
                case 226 /* ContinueStatement */:
                case 227 /* BreakStatement */:
                    transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */;
                    break;
            }
            node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
            return transformFlags & ~excludeFlags;
        }
        /**
         * Gets the transform flags to exclude when unioning the transform flags of a subtree.
         *
         * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
         *       For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
         *       than calling this function.
         */
        /* @internal */
        function getTransformFlagsSubtreeExclusions(kind) {
            if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) {
                return -3 /* TypeExcludes */;
            }
            switch (kind) {
                case 189 /* CallExpression */:
                case 190 /* NewExpression */:
                case 185 /* ArrayLiteralExpression */:
                    return 940049729 /* ArrayLiteralOrCallOrNewExcludes */;
                case 242 /* ModuleDeclaration */:
                    return 977327425 /* ModuleExcludes */;
                case 149 /* Parameter */:
                    return 939525441 /* ParameterExcludes */;
                case 195 /* ArrowFunction */:
                    return 1003902273 /* ArrowFunctionExcludes */;
                case 194 /* FunctionExpression */:
                case 237 /* FunctionDeclaration */:
                    return 1003935041 /* FunctionExcludes */;
                case 236 /* VariableDeclarationList */:
                    return 948962625 /* VariableDeclarationListExcludes */;
                case 238 /* ClassDeclaration */:
                case 207 /* ClassExpression */:
                    return 942011713 /* ClassExcludes */;
                case 155 /* Constructor */:
                    return 1003668801 /* ConstructorExcludes */;
                case 154 /* MethodDeclaration */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                    return 1003668801 /* MethodOrAccessorExcludes */;
                case 119 /* AnyKeyword */:
                case 134 /* NumberKeyword */:
                case 131 /* NeverKeyword */:
                case 137 /* StringKeyword */:
                case 135 /* ObjectKeyword */:
                case 122 /* BooleanKeyword */:
                case 138 /* SymbolKeyword */:
                case 105 /* VoidKeyword */:
                case 148 /* TypeParameter */:
                case 151 /* PropertySignature */:
                case 153 /* MethodSignature */:
                case 158 /* CallSignature */:
                case 159 /* ConstructSignature */:
                case 160 /* IndexSignature */:
                case 239 /* InterfaceDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                    return -3 /* TypeExcludes */;
                case 186 /* ObjectLiteralExpression */:
                    return 942740801 /* ObjectLiteralExcludes */;
                case 272 /* CatchClause */:
                    return 940574017 /* CatchClauseExcludes */;
                case 182 /* ObjectBindingPattern */:
                case 183 /* ArrayBindingPattern */:
                    return 940049729 /* BindingPatternExcludes */;
                case 192 /* TypeAssertionExpression */:
                case 210 /* AsExpression */:
                case 306 /* PartiallyEmittedExpression */:
                case 193 /* ParenthesizedExpression */:
                case 97 /* SuperKeyword */:
                    return 536872257 /* OuterExpressionExcludes */;
                case 187 /* PropertyAccessExpression */:
                case 188 /* ElementAccessExpression */:
                    return 671089985 /* PropertyAccessExcludes */;
                default:
                    return 939525441 /* NodeExcludes */;
            }
        }
        ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
        /**
         * "Binds" JSDoc nodes in TypeScript code.
         * Since we will never create symbols for JSDoc, we just set parent pointers instead.
         */
        function setParentPointers(parent, child) {
            child.parent = parent;
            ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
        }
    })(ts || (ts = {}));
    /** @internal */
    var ts;
    (function (ts) {
        function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) {
            return getSymbolWalker;
            function getSymbolWalker(accept) {
                if (accept === void 0) {
                    accept = function () { return true; };
                }
                var visitedTypes = []; // Sparse array from id to type
                var visitedSymbols = []; // Sparse array from id to symbol
                return {
                    walkType: function (type) {
                        try {
                            visitType(type);
                            return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
                        }
                        finally {
                            ts.clear(visitedTypes);
                            ts.clear(visitedSymbols);
                        }
                    },
                    walkSymbol: function (symbol) {
                        try {
                            visitSymbol(symbol);
                            return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
                        }
                        finally {
                            ts.clear(visitedTypes);
                            ts.clear(visitedSymbols);
                        }
                    },
                };
                function visitType(type) {
                    if (!type) {
                        return;
                    }
                    if (visitedTypes[type.id]) {
                        return;
                    }
                    visitedTypes[type.id] = type;
                    // Reuse visitSymbol to visit the type's symbol,
                    //  but be sure to bail on recuring into the type if accept declines the symbol.
                    var shouldBail = visitSymbol(type.symbol);
                    if (shouldBail)
                        return;
                    // Visit the type's related types, if any
                    if (type.flags & 131072 /* Object */) {
                        var objectType = type;
                        var objectFlags = objectType.objectFlags;
                        if (objectFlags & 4 /* Reference */) {
                            visitTypeReference(type);
                        }
                        if (objectFlags & 32 /* Mapped */) {
                            visitMappedType(type);
                        }
                        if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
                            visitInterfaceType(type);
                        }
                        if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
                            visitObjectType(objectType);
                        }
                    }
                    if (type.flags & 65536 /* TypeParameter */) {
                        visitTypeParameter(type);
                    }
                    if (type.flags & 786432 /* UnionOrIntersection */) {
                        visitUnionOrIntersectionType(type);
                    }
                    if (type.flags & 1048576 /* Index */) {
                        visitIndexType(type);
                    }
                    if (type.flags & 2097152 /* IndexedAccess */) {
                        visitIndexedAccessType(type);
                    }
                }
                function visitTypeReference(type) {
                    visitType(type.target);
                    ts.forEach(type.typeArguments, visitType);
                }
                function visitTypeParameter(type) {
                    visitType(getConstraintOfTypeParameter(type));
                }
                function visitUnionOrIntersectionType(type) {
                    ts.forEach(type.types, visitType);
                }
                function visitIndexType(type) {
                    visitType(type.type);
                }
                function visitIndexedAccessType(type) {
                    visitType(type.objectType);
                    visitType(type.indexType);
                    visitType(type.constraint);
                }
                function visitMappedType(type) {
                    visitType(type.typeParameter);
                    visitType(type.constraintType);
                    visitType(type.templateType);
                    visitType(type.modifiersType);
                }
                function visitSignature(signature) {
                    var typePredicate = getTypePredicateOfSignature(signature);
                    if (typePredicate) {
                        visitType(typePredicate.type);
                    }
                    ts.forEach(signature.typeParameters, visitType);
                    for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
                        var parameter = _a[_i];
                        visitSymbol(parameter);
                    }
                    visitType(getRestTypeOfSignature(signature));
                    visitType(getReturnTypeOfSignature(signature));
                }
                function visitInterfaceType(interfaceT) {
                    visitObjectType(interfaceT);
                    ts.forEach(interfaceT.typeParameters, visitType);
                    ts.forEach(getBaseTypes(interfaceT), visitType);
                    visitType(interfaceT.thisType);
                }
                function visitObjectType(type) {
                    var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
                    visitType(stringIndexType);
                    var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
                    visitType(numberIndexType);
                    // The two checks above *should* have already resolved the type (if needed), so this should be cached
                    var resolved = resolveStructuredTypeMembers(type);
                    for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
                        var signature = _a[_i];
                        visitSignature(signature);
                    }
                    for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
                        var signature = _c[_b];
                        visitSignature(signature);
                    }
                    for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
                        var p = _e[_d];
                        visitSymbol(p);
                    }
                }
                function visitSymbol(symbol) {
                    if (!symbol) {
                        return false;
                    }
                    var symbolId = ts.getSymbolId(symbol);
                    if (visitedSymbols[symbolId]) {
                        return false;
                    }
                    visitedSymbols[symbolId] = symbol;
                    if (!accept(symbol)) {
                        return true;
                    }
                    var t = getTypeOfSymbol(symbol);
                    visitType(t); // Should handle members on classes and such
                    if (symbol.exports) {
                        symbol.exports.forEach(visitSymbol);
                    }
                    ts.forEach(symbol.declarations, function (d) {
                        // Type queries are too far resolved when we just visit the symbol's type
                        //  (their type resolved directly to the member deeply referenced)
                        // So to get the intervening symbols, we need to check if there's a type
                        // query node on any of the symbol's declarations and get symbols there
                        if (d.type && d.type.kind === 165 /* TypeQuery */) {
                            var query = d.type;
                            var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
                            visitSymbol(entity);
                        }
                    });
                    return false;
                }
            }
        }
        ts.createGetSymbolWalker = createGetSymbolWalker;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var ambientModuleSymbolRegex = /^".+"$/;
        var nextSymbolId = 1;
        var nextNodeId = 1;
        var nextMergeId = 1;
        var nextFlowId = 1;
        function getNodeId(node) {
            if (!node.id) {
                node.id = nextNodeId;
                nextNodeId++;
            }
            return node.id;
        }
        ts.getNodeId = getNodeId;
        function getSymbolId(symbol) {
            if (!symbol.id) {
                symbol.id = nextSymbolId;
                nextSymbolId++;
            }
            return symbol.id;
        }
        ts.getSymbolId = getSymbolId;
        function isInstantiatedModule(node, preserveConstEnums) {
            var moduleState = ts.getModuleInstanceState(node);
            return moduleState === 1 /* Instantiated */ ||
                (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
        }
        ts.isInstantiatedModule = isInstantiatedModule;
        function createTypeChecker(host, produceDiagnostics) {
            var getPackagesSet = ts.memoize(function () {
                var set = ts.createMap();
                host.getSourceFiles().forEach(function (sf) {
                    if (!sf.resolvedModules)
                        return;
                    ts.forEachEntry(sf.resolvedModules, function (r) {
                        if (r && r.packageId)
                            set.set(r.packageId.name, true);
                    });
                });
                return set;
            });
            // Cancellation that controls whether or not we can cancel in the middle of type checking.
            // In general cancelling is *not* safe for the type checker.  We might be in the middle of
            // computing something, and we will leave our internals in an inconsistent state.  Callers
            // who set the cancellation token should catch if a cancellation exception occurs, and
            // should throw away and create a new TypeChecker.
            //
            // Currently we only support setting the cancellation token when getting diagnostics.  This
            // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
            // they no longer need the information (for example, if the user started editing again).
            var cancellationToken;
            var requestedExternalEmitHelpers;
            var externalHelpersModule;
            // tslint:disable variable-name
            var Symbol = ts.objectAllocator.getSymbolConstructor();
            var Type = ts.objectAllocator.getTypeConstructor();
            var Signature = ts.objectAllocator.getSignatureConstructor();
            // tslint:enable variable-name
            var typeCount = 0;
            var symbolCount = 0;
            var enumCount = 0;
            var instantiationDepth = 0;
            var constraintDepth = 0;
            var emptySymbols = ts.createSymbolTable();
            var identityMapper = ts.identity;
            var compilerOptions = host.getCompilerOptions();
            var languageVersion = ts.getEmitScriptTarget(compilerOptions);
            var moduleKind = ts.getEmitModuleKind(compilerOptions);
            var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
            var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
            var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
            var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
            var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
            var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
            var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
            var emitResolver = createResolver();
            var nodeBuilder = createNodeBuilder();
            var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
            undefinedSymbol.declarations = [];
            var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
            var requireSymbol = createSymbol(4 /* Property */, "require");
            /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
            var apparentArgumentCount;
            // for public members that accept a Node or one of its subtypes, we must guard against
            // synthetic nodes created during transformations by calling `getParseTreeNode`.
            // for most of these, we perform the guard only on `checker` to avoid any possible
            // extra cost of calling `getParseTreeNode` when calling these functions from inside the
            // checker.
            var checker = {
                getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
                getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
                getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
                getTypeCount: function () { return typeCount; },
                isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
                isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
                isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
                getMergedSymbol: getMergedSymbol,
                getDiagnostics: getDiagnostics,
                getGlobalDiagnostics: getGlobalDiagnostics,
                getTypeOfSymbolAtLocation: function (symbol, location) {
                    location = ts.getParseTreeNode(location);
                    return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
                },
                getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
                    var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
                    if (parameter === undefined)
                        return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
                    return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
                },
                getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
                getPropertiesOfType: getPropertiesOfType,
                getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
                getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
                getIndexInfoOfType: getIndexInfoOfType,
                getSignaturesOfType: getSignaturesOfType,
                getIndexTypeOfType: getIndexTypeOfType,
                getBaseTypes: getBaseTypes,
                getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
                getWidenedType: getWidenedType,
                getTypeFromTypeNode: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
                    return node ? getTypeFromTypeNode(node) : errorType;
                },
                getParameterType: getTypeAtPosition,
                getPromisedTypeOfPromise: getPromisedTypeOfPromise,
                getReturnTypeOfSignature: getReturnTypeOfSignature,
                getNullableType: getNullableType,
                getNonNullableType: getNonNullableType,
                typeToTypeNode: nodeBuilder.typeToTypeNode,
                indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
                signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
                symbolToEntityName: nodeBuilder.symbolToEntityName,
                symbolToExpression: nodeBuilder.symbolToExpression,
                symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
                symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
                typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
                getSymbolsInScope: function (location, meaning) {
                    location = ts.getParseTreeNode(location);
                    return location ? getSymbolsInScope(location, meaning) : [];
                },
                getSymbolAtLocation: function (node) {
                    node = ts.getParseTreeNode(node);
                    return node ? getSymbolAtLocation(node) : undefined;
                },
                getShorthandAssignmentValueSymbol: function (node) {
                    node = ts.getParseTreeNode(node);
                    return node ? getShorthandAssignmentValueSymbol(node) : undefined;
                },
                getExportSpecifierLocalTargetSymbol: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
                    return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
                },
                getExportSymbolOfSymbol: function (symbol) {
                    return getMergedSymbol(symbol.exportSymbol || symbol);
                },
                getTypeAtLocation: function (node) {
                    node = ts.getParseTreeNode(node);
                    return node ? getTypeOfNode(node) : errorType;
                },
                getPropertySymbolOfDestructuringAssignment: function (locationIn) {
                    var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
                    return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
                },
                signatureToString: function (signature, enclosingDeclaration, flags, kind) {
                    return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
                },
                typeToString: function (type, enclosingDeclaration, flags) {
                    return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
                },
                symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
                    return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
                },
                typePredicateToString: function (predicate, enclosingDeclaration, flags) {
                    return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
                },
                writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
                    return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
                },
                writeType: function (type, enclosingDeclaration, flags, writer) {
                    return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
                },
                writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
                    return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
                },
                writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
                    return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
                },
                getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
                getRootSymbols: getRootSymbols,
                getContextualType: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
                    return node ? getContextualType(node) : undefined;
                },
                getContextualTypeForObjectLiteralElement: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
                    return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
                },
                getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
                    return node && getContextualTypeForArgumentAtIndex(node, argIndex);
                },
                getContextualTypeForJsxAttribute: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
                    return node && getContextualTypeForJsxAttribute(node);
                },
                isContextSensitive: isContextSensitive,
                getFullyQualifiedName: getFullyQualifiedName,
                getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
                    return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
                },
                getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
                    return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
                },
                getConstantValue: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
                    return node ? getConstantValue(node) : undefined;
                },
                isValidPropertyAccess: function (nodeIn, propertyName) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
                    return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
                },
                isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
                    return !!node && isValidPropertyAccessForCompletions(node, type, property);
                },
                getSignatureFromDeclaration: function (declarationIn) {
                    var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
                    return declaration ? getSignatureFromDeclaration(declaration) : undefined;
                },
                isImplementationOfOverload: function (node) {
                    var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
                    return parsed ? isImplementationOfOverload(parsed) : undefined;
                },
                getImmediateAliasedSymbol: function (symbol) {
                    ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
                    var links = getSymbolLinks(symbol);
                    if (!links.immediateTarget) {
                        var node = getDeclarationOfAliasSymbol(symbol);
                        if (!node)
                            return ts.Debug.fail();
                        links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
                    }
                    return links.immediateTarget;
                },
                getAliasedSymbol: resolveAlias,
                getEmitResolver: getEmitResolver,
                getExportsOfModule: getExportsOfModuleAsArray,
                getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
                getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier),
                getAmbientModules: getAmbientModules,
                getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement);
                    return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined;
                },
                getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
                isOptionalParameter: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
                    return node ? isOptionalParameter(node) : false;
                },
                tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
                tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
                tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
                    // we deliberately exclude augmentations
                    // since we are only interested in declarations of the module itself
                    return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
                },
                getApparentType: getApparentType,
                getUnionType: getUnionType,
                createAnonymousType: createAnonymousType,
                createSignature: createSignature,
                createSymbol: createSymbol,
                createIndexInfo: createIndexInfo,
                getAnyType: function () { return anyType; },
                getStringType: function () { return stringType; },
                getNumberType: function () { return numberType; },
                createPromiseType: createPromiseType,
                createArrayType: createArrayType,
                getBooleanType: function () { return booleanType; },
                getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
                getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
                getVoidType: function () { return voidType; },
                getUndefinedType: function () { return undefinedType; },
                getNullType: function () { return nullType; },
                getESSymbolType: function () { return esSymbolType; },
                getNeverType: function () { return neverType; },
                isSymbolAccessible: isSymbolAccessible,
                isArrayLikeType: isArrayLikeType,
                isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
                getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
                getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); },
                getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
                getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); },
                getBaseConstraintOfType: getBaseConstraintOfType,
                getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
                resolveName: function (name, location, meaning, excludeGlobals) {
                    return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
                },
                getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
                getAccessibleSymbolChain: getAccessibleSymbolChain,
                getTypePredicateOfSignature: getTypePredicateOfSignature,
                resolveExternalModuleSymbol: resolveExternalModuleSymbol,
                tryGetThisTypeAt: function (node) {
                    node = ts.getParseTreeNode(node);
                    return node && tryGetThisTypeAt(node);
                },
                getTypeArgumentConstraint: function (nodeIn) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
                    return node && getTypeArgumentConstraint(node);
                },
                getSuggestionDiagnostics: function (file, ct) {
                    if (ts.skipTypeChecking(file, compilerOptions)) {
                        return ts.emptyArray;
                    }
                    var diagnostics;
                    try {
                        // Record the cancellation token so it can be checked later on during checkSourceElement.
                        // Do this in a finally block so we can ensure that it gets reset back to nothing after
                        // this call is done.
                        cancellationToken = ct;
                        // Ensure file is type checked
                        checkSourceFile(file);
                        ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
                        diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName));
                        if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) {
                            addUnusedDiagnostics();
                        }
                        return diagnostics || ts.emptyArray;
                    }
                    finally {
                        cancellationToken = undefined;
                    }
                    function addUnusedDiagnostics() {
                        checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
                            if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) {
                                (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
                            }
                        });
                    }
                },
                runWithCancellationToken: function (token, callback) {
                    try {
                        cancellationToken = token;
                        return callback(checker);
                    }
                    finally {
                        cancellationToken = undefined;
                    }
                },
                getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
            };
            function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
                var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
                apparentArgumentCount = argumentCount;
                var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
                apparentArgumentCount = undefined;
                return res;
            }
            var tupleTypes = ts.createMap();
            var unionTypes = ts.createMap();
            var intersectionTypes = ts.createMap();
            var literalTypes = ts.createMap();
            var indexedAccessTypes = ts.createMap();
            var evolvingArrayTypes = [];
            var undefinedProperties = ts.createMap();
            var unknownSymbol = createSymbol(4 /* Property */, "unknown");
            var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
            var anyType = createIntrinsicType(1 /* Any */, "any");
            var autoType = createIntrinsicType(1 /* Any */, "any");
            var wildcardType = createIntrinsicType(1 /* Any */, "any");
            var errorType = createIntrinsicType(1 /* Any */, "error");
            var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
            var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined");
            var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined");
            var nullType = createIntrinsicType(16384 /* Null */, "null");
            var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null");
            var stringType = createIntrinsicType(4 /* String */, "string");
            var numberType = createIntrinsicType(8 /* Number */, "number");
            var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false");
            var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false");
            var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true");
            var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true");
            falseType.flags |= 33554432 /* FreshLiteral */;
            trueType.flags |= 33554432 /* FreshLiteral */;
            trueType.regularType = regularTrueType;
            regularTrueType.freshType = trueType;
            falseType.regularType = regularFalseType;
            regularFalseType.freshType = falseType;
            var booleanType = createBooleanType([regularFalseType, regularTrueType]);
            // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
            // (The union is cached, so simply doing the marking here is sufficient)
            createBooleanType([regularFalseType, trueType]);
            createBooleanType([falseType, regularTrueType]);
            createBooleanType([falseType, trueType]);
            var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol");
            var voidType = createIntrinsicType(4096 /* Void */, "void");
            var neverType = createIntrinsicType(32768 /* Never */, "never");
            var silentNeverType = createIntrinsicType(32768 /* Never */, "never");
            var implicitNeverType = createIntrinsicType(32768 /* Never */, "never");
            var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object");
            var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
            var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
            var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
            var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
            emptyTypeLiteralSymbol.members = ts.createSymbolTable();
            var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
            var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
            emptyGenericType.instantiations = ts.createMap();
            var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
            // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
            // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
            anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */;
            var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
            var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
            var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
            var markerSuperType = createType(65536 /* TypeParameter */);
            var markerSubType = createType(65536 /* TypeParameter */);
            markerSubType.constraint = markerSuperType;
            var markerOtherType = createType(65536 /* TypeParameter */);
            var noTypePredicate = createIdentifierTypePredicate("<<unresolved>>", 0, anyType);
            var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
            var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
            var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
            var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
            var resolvingSignaturesArray = [resolvingSignature];
            var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
            var globals = ts.createSymbolTable();
            var amalgamatedDuplicates;
            var reverseMappedCache = ts.createMap();
            var ambientModulesCache;
            /**
             * List of every ambient module with a "*" wildcard.
             * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
             * This is only used if there is no exact match.
             */
            var patternAmbientModules;
            var globalObjectType;
            var globalFunctionType;
            var globalArrayType;
            var globalReadonlyArrayType;
            var globalStringType;
            var globalNumberType;
            var globalBooleanType;
            var globalRegExpType;
            var globalThisType;
            var anyArrayType;
            var autoArrayType;
            var anyReadonlyArrayType;
            var deferredGlobalNonNullableTypeAlias;
            // The library files are only loaded when the feature is used.
            // This allows users to just specify library files they want to used through --lib
            // and they will not get an error from not having unrelated library files
            var deferredGlobalESSymbolConstructorSymbol;
            var deferredGlobalESSymbolType;
            var deferredGlobalTypedPropertyDescriptorType;
            var deferredGlobalPromiseType;
            var deferredGlobalPromiseConstructorSymbol;
            var deferredGlobalPromiseConstructorLikeType;
            var deferredGlobalIterableType;
            var deferredGlobalIteratorType;
            var deferredGlobalIterableIteratorType;
            var deferredGlobalAsyncIterableType;
            var deferredGlobalAsyncIteratorType;
            var deferredGlobalAsyncIterableIteratorType;
            var deferredGlobalTemplateStringsArrayType;
            var deferredGlobalImportMetaType;
            var deferredGlobalExtractSymbol;
            var deferredNodes;
            var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
            var flowLoopStart = 0;
            var flowLoopCount = 0;
            var sharedFlowCount = 0;
            var flowAnalysisDisabled = false;
            var emptyStringType = getLiteralType("");
            var zeroType = getLiteralType(0);
            var resolutionTargets = [];
            var resolutionResults = [];
            var resolutionPropertyNames = [];
            var suggestionCount = 0;
            var maximumSuggestionCount = 10;
            var mergedSymbols = [];
            var symbolLinks = [];
            var nodeLinks = [];
            var flowLoopCaches = [];
            var flowLoopNodes = [];
            var flowLoopKeys = [];
            var flowLoopTypes = [];
            var sharedFlowNodes = [];
            var sharedFlowTypes = [];
            var potentialThisCollisions = [];
            var potentialNewTargetCollisions = [];
            var awaitedTypeStack = [];
            var diagnostics = ts.createDiagnosticCollection();
            // Suggestion diagnostics must have a file. Keyed by source file name.
            var suggestionDiagnostics = ts.createMultiMap();
            var TypeFacts;
            (function (TypeFacts) {
                TypeFacts[TypeFacts["None"] = 0] = "None";
                TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
                TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
                TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean";
                TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol";
                TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject";
                TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction";
                TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject";
                TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString";
                TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber";
                TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean";
                TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol";
                TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject";
                TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction";
                TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject";
                TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined";
                TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull";
                TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull";
                TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined";
                TypeFacts[TypeFacts["NENull"] = 262144] = "NENull";
                TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull";
                TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy";
                TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy";
                TypeFacts[TypeFacts["All"] = 4194303] = "All";
                // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
                // The presence of a particular fact means that the given test is true for some (and possibly all) values
                // of that kind of type.
                TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts";
                TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts";
                TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts";
                TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts";
                TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts";
                TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts";
                TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts";
                TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts";
                TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts";
                TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts";
                TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts";
                TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts";
                TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts";
                TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts";
                TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts";
                TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts";
                TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts";
                TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts";
                TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts";
                TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts";
                TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts";
                TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts";
                TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts";
                TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts";
                TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts";
                TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts";
                TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts";
                TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts";
                TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts";
                TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts";
                TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts";
                TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts";
                TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts";
                TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts";
            })(TypeFacts || (TypeFacts = {}));
            var typeofEQFacts = ts.createMapFromTemplate({
                string: 1 /* TypeofEQString */,
                number: 2 /* TypeofEQNumber */,
                boolean: 4 /* TypeofEQBoolean */,
                symbol: 8 /* TypeofEQSymbol */,
                undefined: 16384 /* EQUndefined */,
                object: 16 /* TypeofEQObject */,
                function: 32 /* TypeofEQFunction */
            });
            var typeofNEFacts = ts.createMapFromTemplate({
                string: 128 /* TypeofNEString */,
                number: 256 /* TypeofNENumber */,
                boolean: 512 /* TypeofNEBoolean */,
                symbol: 1024 /* TypeofNESymbol */,
                undefined: 131072 /* NEUndefined */,
                object: 2048 /* TypeofNEObject */,
                function: 4096 /* TypeofNEFunction */
            });
            var typeofTypesByName = ts.createMapFromTemplate({
                string: stringType,
                number: numberType,
                boolean: booleanType,
                symbol: esSymbolType,
                undefined: undefinedType
            });
            var typeofType = createTypeofType();
            var _jsxNamespace;
            var _jsxFactoryEntity;
            var subtypeRelation = ts.createMap();
            var assignableRelation = ts.createMap();
            var definitelyAssignableRelation = ts.createMap();
            var comparableRelation = ts.createMap();
            var identityRelation = ts.createMap();
            var enumRelation = ts.createMap();
            var TypeSystemPropertyName;
            (function (TypeSystemPropertyName) {
                TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
                TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
                TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
                TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
                TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
                TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
                TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference";
            })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
            var CheckMode;
            (function (CheckMode) {
                CheckMode[CheckMode["Normal"] = 0] = "Normal";
                CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
                CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
                CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
            })(CheckMode || (CheckMode = {}));
            var CallbackCheck;
            (function (CallbackCheck) {
                CallbackCheck[CallbackCheck["None"] = 0] = "None";
                CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant";
                CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict";
            })(CallbackCheck || (CallbackCheck = {}));
            var MappedTypeModifiers;
            (function (MappedTypeModifiers) {
                MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
                MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
                MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
                MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
            })(MappedTypeModifiers || (MappedTypeModifiers = {}));
            var ExpandingFlags;
            (function (ExpandingFlags) {
                ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
                ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
                ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
                ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
            })(ExpandingFlags || (ExpandingFlags = {}));
            var MembersOrExportsResolutionKind;
            (function (MembersOrExportsResolutionKind) {
                MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
                MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
            })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
            var UnusedKind;
            (function (UnusedKind) {
                UnusedKind[UnusedKind["Local"] = 0] = "Local";
                UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
            })(UnusedKind || (UnusedKind = {}));
            var builtinGlobals = ts.createSymbolTable();
            builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
            var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
            initializeTypeChecker();
            return checker;
            function getJsxNamespace(location) {
                if (location) {
                    var file = ts.getSourceFileOfNode(location);
                    if (file) {
                        if (file.localJsxNamespace) {
                            return file.localJsxNamespace;
                        }
                        var jsxPragma = file.pragmas.get("jsx");
                        if (jsxPragma) {
                            var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217
                            file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
                            if (file.localJsxFactory) {
                                return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
                            }
                        }
                    }
                }
                if (!_jsxNamespace) {
                    _jsxNamespace = "React";
                    if (compilerOptions.jsxFactory) {
                        _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
                        if (_jsxFactoryEntity) {
                            _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText;
                        }
                    }
                    else if (compilerOptions.reactNamespace) {
                        _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
                    }
                }
                return _jsxNamespace;
            }
            function getEmitResolver(sourceFile, cancellationToken) {
                // Ensure we have all the type information in place for this file so that all the
                // emitter questions of this resolver will return the right information.
                getDiagnostics(sourceFile, cancellationToken);
                return emitResolver;
            }
            function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
                var diagnostic = location
                    ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
                    : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
                var existing = diagnostics.lookup(diagnostic);
                if (existing) {
                    return existing;
                }
                else {
                    diagnostics.add(diagnostic);
                    return diagnostic;
                }
            }
            function addRelatedInfo(diagnostic) {
                var relatedInformation = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    relatedInformation[_i - 1] = arguments[_i];
                }
                var _a;
                if (!diagnostic.relatedInformation) {
                    diagnostic.relatedInformation = [];
                }
                (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
                return diagnostic;
            }
            function error(location, message, arg0, arg1, arg2, arg3) {
                var diagnostic = location
                    ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
                    : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
                diagnostics.add(diagnostic);
                return diagnostic;
            }
            function addErrorOrSuggestion(isError, diagnostic) {
                if (isError) {
                    diagnostics.add(diagnostic);
                }
                else {
                    suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion }));
                }
            }
            function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
                addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message));
            }
            function createSymbol(flags, name, checkFlags) {
                symbolCount++;
                var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
                symbol.checkFlags = checkFlags || 0;
                return symbol;
            }
            function isTransientSymbol(symbol) {
                return (symbol.flags & 33554432 /* Transient */) !== 0;
            }
            function getExcludedSymbolFlags(flags) {
                var result = 0;
                if (flags & 2 /* BlockScopedVariable */)
                    result |= 67220415 /* BlockScopedVariableExcludes */;
                if (flags & 1 /* FunctionScopedVariable */)
                    result |= 67220414 /* FunctionScopedVariableExcludes */;
                if (flags & 4 /* Property */)
                    result |= 0 /* PropertyExcludes */;
                if (flags & 8 /* EnumMember */)
                    result |= 68008959 /* EnumMemberExcludes */;
                if (flags & 16 /* Function */)
                    result |= 67219887 /* FunctionExcludes */;
                if (flags & 32 /* Class */)
                    result |= 68008383 /* ClassExcludes */;
                if (flags & 64 /* Interface */)
                    result |= 67897736 /* InterfaceExcludes */;
                if (flags & 256 /* RegularEnum */)
                    result |= 68008191 /* RegularEnumExcludes */;
                if (flags & 128 /* ConstEnum */)
                    result |= 68008831 /* ConstEnumExcludes */;
                if (flags & 512 /* ValueModule */)
                    result |= 110735 /* ValueModuleExcludes */;
                if (flags & 8192 /* Method */)
                    result |= 67212223 /* MethodExcludes */;
                if (flags & 32768 /* GetAccessor */)
                    result |= 67154879 /* GetAccessorExcludes */;
                if (flags & 65536 /* SetAccessor */)
                    result |= 67187647 /* SetAccessorExcludes */;
                if (flags & 262144 /* TypeParameter */)
                    result |= 67635688 /* TypeParameterExcludes */;
                if (flags & 524288 /* TypeAlias */)
                    result |= 67897832 /* TypeAliasExcludes */;
                if (flags & 2097152 /* Alias */)
                    result |= 2097152 /* AliasExcludes */;
                return result;
            }
            function recordMergedSymbol(target, source) {
                if (!source.mergeId) {
                    source.mergeId = nextMergeId;
                    nextMergeId++;
                }
                mergedSymbols[source.mergeId] = target;
            }
            function cloneSymbol(symbol) {
                var result = createSymbol(symbol.flags, symbol.escapedName);
                result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
                result.parent = symbol.parent;
                if (symbol.valueDeclaration)
                    result.valueDeclaration = symbol.valueDeclaration;
                if (symbol.constEnumOnlyModule)
                    result.constEnumOnlyModule = true;
                if (symbol.members)
                    result.members = ts.cloneMap(symbol.members);
                if (symbol.exports)
                    result.exports = ts.cloneMap(symbol.exports);
                recordMergedSymbol(result, symbol);
                return result;
            }
            /**
             * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
             * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
             */
            function mergeSymbol(target, source) {
                if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
                    (source.flags | target.flags) & 67108864 /* Assignment */) {
                    ts.Debug.assert(source !== target);
                    if (!(target.flags & 33554432 /* Transient */)) {
                        target = cloneSymbol(target);
                    }
                    // Javascript static-property-assignment declarations always merge, even though they are also values
                    if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
                        // reset flag when merging instantiated module into value module that has only const enums
                        target.constEnumOnlyModule = false;
                    }
                    target.flags |= source.flags;
                    if (source.valueDeclaration &&
                        (!target.valueDeclaration ||
                            ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) ||
                            ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) {
                        // other kinds of value declarations take precedence over modules and assignment declarations
                        target.valueDeclaration = source.valueDeclaration;
                    }
                    ts.addRange(target.declarations, source.declarations);
                    if (source.members) {
                        if (!target.members)
                            target.members = ts.createSymbolTable();
                        mergeSymbolTable(target.members, source.members);
                    }
                    if (source.exports) {
                        if (!target.exports)
                            target.exports = ts.createSymbolTable();
                        mergeSymbolTable(target.exports, source.exports);
                    }
                    recordMergedSymbol(target, source);
                }
                else if (target.flags & 1024 /* NamespaceModule */) {
                    error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
                }
                else {
                    var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
                    var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
                    var message = isEitherEnum
                        ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
                        : isEitherBlockScoped
                            ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
                            : ts.Diagnostics.Duplicate_identifier_0;
                    var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
                    var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
                    // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
                    if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) {
                        var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1;
                        var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1;
                        var cacheKey = firstFile_1.path + "|" + secondFile.path;
                        var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() };
                        var symbolName_1 = symbolToString(source);
                        var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped };
                        var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped };
                        ts.forEach(source.declarations, function (node) {
                            var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
                            var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1;
                            targetList.instances.push(errorNode);
                        });
                        ts.forEach(target.declarations, function (node) {
                            var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
                            var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1;
                            targetList.instances.push(errorNode);
                        });
                        existing.firstFileInstances.set(symbolName_1, firstInstanceList_1);
                        existing.secondFileInstances.set(symbolName_1, secondInstanceList_1);
                        amalgamatedDuplicates.set(cacheKey, existing);
                        return target;
                    }
                    var symbolName_2 = symbolToString(source);
                    addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target);
                    addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source);
                }
                return target;
            }
            function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
                ts.forEach(target.declarations, function (node) {
                    var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
                    addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]);
                });
            }
            function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) {
                var err = lookupOrIssueError(errorNode, message, symbolName);
                if (relatedNode && ts.length(err.relatedInformation) < 5) {
                    addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
                }
            }
            function combineSymbolTables(first, second) {
                if (!ts.hasEntries(first))
                    return second;
                if (!ts.hasEntries(second))
                    return first;
                var combined = ts.createSymbolTable();
                mergeSymbolTable(combined, first);
                mergeSymbolTable(combined, second);
                return combined;
            }
            function mergeSymbolTable(target, source) {
                source.forEach(function (sourceSymbol, id) {
                    target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol);
                });
            }
            function mergeModuleAugmentation(moduleName) {
                var moduleAugmentation = moduleName.parent;
                if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
                    // this is a combined symbol for multiple augmentations within the same file.
                    // its symbol already has accumulated information for all declarations
                    // so we need to add it just once - do the work only for first declaration
                    ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
                    return;
                }
                if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
                    mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
                }
                else {
                    // find a module that about to be augmented
                    // do not validate names of augmentations that are defined in ambient context
                    var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */)
                        ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
                        : undefined;
                    var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
                    if (!mainModule) {
                        return;
                    }
                    // obtain item referenced by 'export='
                    mainModule = resolveExternalModuleSymbol(mainModule);
                    if (mainModule.flags & 1920 /* Namespace */) {
                        mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol);
                    }
                    else {
                        // moduleName will be a StringLiteral since this is not `declare global`.
                        error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
                    }
                }
            }
            function addToSymbolTable(target, source, message) {
                source.forEach(function (sourceSymbol, id) {
                    var targetSymbol = target.get(id);
                    if (targetSymbol) {
                        // Error on redeclarations
                        ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
                    }
                    else {
                        target.set(id, sourceSymbol);
                    }
                });
                function addDeclarationDiagnostic(id, message) {
                    return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
                }
            }
            function getSymbolLinks(symbol) {
                if (symbol.flags & 33554432 /* Transient */)
                    return symbol;
                var id = getSymbolId(symbol);
                return symbolLinks[id] || (symbolLinks[id] = {});
            }
            function getNodeLinks(node) {
                var nodeId = getNodeId(node);
                return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
            }
            function isGlobalSourceFile(node) {
                return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
            }
            function getSymbol(symbols, name, meaning) {
                if (meaning) {
                    var symbol = symbols.get(name);
                    if (symbol) {
                        ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
                        if (symbol.flags & meaning) {
                            return symbol;
                        }
                        if (symbol.flags & 2097152 /* Alias */) {
                            var target = resolveAlias(symbol);
                            // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
                            if (target === unknownSymbol || target.flags & meaning) {
                                return symbol;
                            }
                        }
                    }
                }
                // return undefined if we can't find a symbol.
            }
            /**
             * Get symbols that represent parameter-property-declaration as parameter and as property declaration
             * @param parameter a parameterDeclaration node
             * @param parameterName a name of the parameter to get the symbols for.
             * @return a tuple of two symbols
             */
            function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
                var constructorDeclaration = parameter.parent;
                var classDeclaration = parameter.parent.parent;
                var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */);
                var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */);
                if (parameterSymbol && propertySymbol) {
                    return [parameterSymbol, propertySymbol];
                }
                return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
            }
            function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
                var declarationFile = ts.getSourceFileOfNode(declaration);
                var useFile = ts.getSourceFileOfNode(usage);
                if (declarationFile !== useFile) {
                    if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
                        (!compilerOptions.outFile && !compilerOptions.out) ||
                        isInTypeQuery(usage) ||
                        declaration.flags & 4194304 /* Ambient */) {
                        // nodes are in different files and order cannot be determined
                        return true;
                    }
                    // declaration is after usage
                    // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
                    if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
                        return true;
                    }
                    var sourceFiles = host.getSourceFiles();
                    return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
                }
                if (declaration.pos <= usage.pos) {
                    // declaration is before usage
                    if (declaration.kind === 184 /* BindingElement */) {
                        // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
                        var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */);
                        if (errorBindingElement) {
                            return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
                                declaration.pos < errorBindingElement.pos;
                        }
                        // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
                        return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage);
                    }
                    else if (declaration.kind === 235 /* VariableDeclaration */) {
                        // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
                        return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
                    }
                    else if (ts.isClassDeclaration(declaration)) {
                        // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
                        return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
                    }
                    return true;
                }
                // declaration is after usage, but it can still be legal if usage is deferred:
                // 1. inside an export specifier
                // 2. inside a function
                // 3. inside an instance property initializer, a reference to a non-instance property
                // 4. inside a static property initializer, a reference to a static method in the same class
                // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
                // or if usage is in a type context:
                // 1. inside a type query (typeof in type position)
                // 2. inside a jsdoc comment
                if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) {
                    // export specifiers do not use the variable, they only make it available for use
                    return true;
                }
                // When resolving symbols for exports, the `usage` location passed in can be the export site directly
                if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) {
                    return true;
                }
                var container = ts.getEnclosingBlockScopeContainer(declaration);
                return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container);
                function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
                    var container = ts.getEnclosingBlockScopeContainer(declaration);
                    switch (declaration.parent.parent.kind) {
                        case 217 /* VariableStatement */:
                        case 223 /* ForStatement */:
                        case 225 /* ForOfStatement */:
                            // variable statement/for/for-of statement case,
                            // use site should not be inside variable declaration (initializer of declaration or binding element)
                            if (isSameScopeDescendentOf(usage, declaration, container)) {
                                return true;
                            }
                            break;
                    }
                    // ForIn/ForOf case - use site should not be used in expression part
                    var grandparent = declaration.parent.parent;
                    return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container);
                }
                function isUsedInFunctionOrInstanceProperty(usage, declaration, container) {
                    return !!ts.findAncestor(usage, function (current) {
                        if (current === container) {
                            return "quit";
                        }
                        if (ts.isFunctionLike(current)) {
                            return true;
                        }
                        var initializerOfProperty = current.parent &&
                            current.parent.kind === 152 /* PropertyDeclaration */ &&
                            current.parent.initializer === current;
                        if (initializerOfProperty) {
                            if (ts.hasModifier(current.parent, 32 /* Static */)) {
                                if (declaration.kind === 154 /* MethodDeclaration */) {
                                    return true;
                                }
                            }
                            else {
                                var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
                                if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
                                    return true;
                                }
                            }
                        }
                        return false;
                    });
                }
            }
            /**
             * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
             * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
             * the given name can be found.
             *
             * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
             */
            function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
                if (excludeGlobals === void 0) {
                    excludeGlobals = false;
                }
                return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
            }
            function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
                var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
                var result;
                var lastLocation;
                var lastSelfReferenceLocation;
                var propertyWithInvalidInitializer;
                var errorLocation = location;
                var grandparent;
                var isInExternalModule = false;
                loop: while (location) {
                    // Locals of a source file are not in scope (because they get merged into the global symbol table)
                    if (location.locals && !isGlobalSourceFile(location)) {
                        if (result = lookup(location.locals, name, meaning)) {
                            var useResult = true;
                            if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
                                // symbol lookup restrictions for function-like declarations
                                // - Type parameters of a function are in scope in the entire function declaration, including the parameter
                                //   list and return type. However, local types are only in scope in the function body.
                                // - parameters are only in the scope of function body
                                // This restriction does not apply to JSDoc comment types because they are parented
                                // at a higher level than type parameters would normally be
                                if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) {
                                    useResult = result.flags & 262144 /* TypeParameter */
                                        // type parameters are visible in parameter list, return type and type parameter list
                                        ? lastLocation === location.type ||
                                            lastLocation.kind === 149 /* Parameter */ ||
                                            lastLocation.kind === 148 /* TypeParameter */
                                        // local types not visible outside the function body
                                        : false;
                                }
                                if (meaning & 67220415 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) {
                                    // parameters are visible only inside function body, parameter list and return type
                                    // technically for parameter list case here we might mix parameters and variables declared in function,
                                    // however it is detected separately when checking initializers of parameters
                                    // to make sure that they reference no variables declared after them.
                                    useResult =
                                        lastLocation.kind === 149 /* Parameter */ ||
                                            (lastLocation === location.type &&
                                                !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
                                }
                            }
                            else if (location.kind === 173 /* ConditionalType */) {
                                // A type parameter declared using 'infer T' in a conditional type is visible only in
                                // the true branch of the conditional type.
                                useResult = lastLocation === location.trueType;
                            }
                            if (useResult) {
                                break loop;
                            }
                            else {
                                result = undefined;
                            }
                        }
                    }
                    switch (location.kind) {
                        case 277 /* SourceFile */:
                            if (!ts.isExternalOrCommonJsModule(location))
                                break;
                            isInExternalModule = true;
                        // falls through
                        case 242 /* ModuleDeclaration */:
                            var moduleExports = getSymbolOfNode(location).exports;
                            if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) {
                                // It's an external module. First see if the module has an export default and if the local
                                // name of that export default matches.
                                if (result = moduleExports.get("default" /* Default */)) {
                                    var localSymbol = ts.getLocalSymbolForExportDefault(result);
                                    if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
                                        break loop;
                                    }
                                    result = undefined;
                                }
                                // Because of module/namespace merging, a module's exports are in scope,
                                // yet we never want to treat an export specifier as putting a member in scope.
                                // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
                                // Two things to note about this:
                                //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
                                //        on an export specifier is that it might find the export specifier itself, and try to
                                //        resolve it as an alias. This will cause the checker to consider the export specifier
                                //        a circular alias reference when it might not be.
                                //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
                                //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
                                //        which is not the desired behavior.
                                var moduleExport = moduleExports.get(name);
                                if (moduleExport &&
                                    moduleExport.flags === 2097152 /* Alias */ &&
                                    ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) {
                                    break;
                                }
                            }
                            // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
                            if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
                                if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
                                    result = undefined;
                                }
                                else {
                                    break loop;
                                }
                            }
                            break;
                        case 241 /* EnumDeclaration */:
                            if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
                                break loop;
                            }
                            break;
                        case 152 /* PropertyDeclaration */:
                        case 151 /* PropertySignature */:
                            // TypeScript 1.0 spec (April 2014): 8.4.1
                            // Initializer expressions for instance member variables are evaluated in the scope
                            // of the class constructor body but are not permitted to reference parameters or
                            // local variables of the constructor. This effectively means that entities from outer scopes
                            // by the same name as a constructor parameter or local variable are inaccessible
                            // in initializer expressions for instance member variables.
                            if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) {
                                var ctor = findConstructorDeclaration(location.parent);
                                if (ctor && ctor.locals) {
                                    if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) {
                                        // Remember the property node, it will be used later to report appropriate error
                                        propertyWithInvalidInitializer = location;
                                    }
                                }
                            }
                            break;
                        case 238 /* ClassDeclaration */:
                        case 207 /* ClassExpression */:
                        case 239 /* InterfaceDeclaration */:
                            // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
                            // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
                            // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
                            if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) {
                                if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
                                    // ignore type parameters not declared in this container
                                    result = undefined;
                                    break;
                                }
                                if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
                                    // TypeScript 1.0 spec (April 2014): 3.4.1
                                    // The scope of a type parameter extends over the entire declaration with which the type
                                    // parameter list is associated, with the exception of static member declarations in classes.
                                    error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
                                    return undefined;
                                }
                                break loop;
                            }
                            if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) {
                                var className = location.name;
                                if (className && name === className.escapedText) {
                                    result = location.symbol;
                                    break loop;
                                }
                            }
                            break;
                        case 209 /* ExpressionWithTypeArguments */:
                            // The type parameters of a class are not in scope in the base class expression.
                            if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) {
                                var container = location.parent.parent;
                                if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) {
                                    if (nameNotFoundMessage) {
                                        error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
                                    }
                                    return undefined;
                                }
                            }
                            break;
                        // It is not legal to reference a class's own type parameters from a computed property name that
                        // belongs to the class. For example:
                        //
                        //   function foo<T>() { return '' }
                        //   class C<T> { // <-- Class's own type parameter T
                        //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
                        //   }
                        //
                        case 147 /* ComputedPropertyName */:
                            grandparent = location.parent.parent;
                            if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) {
                                // A reference to this grandparent's type parameters would be an error
                                if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) {
                                    error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
                                    return undefined;
                                }
                            }
                            break;
                        case 154 /* MethodDeclaration */:
                        case 153 /* MethodSignature */:
                        case 155 /* Constructor */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                        case 237 /* FunctionDeclaration */:
                        case 195 /* ArrowFunction */:
                            if (meaning & 3 /* Variable */ && name === "arguments") {
                                result = argumentsSymbol;
                                break loop;
                            }
                            break;
                        case 194 /* FunctionExpression */:
                            if (meaning & 3 /* Variable */ && name === "arguments") {
                                result = argumentsSymbol;
                                break loop;
                            }
                            if (meaning & 16 /* Function */) {
                                var functionName = location.name;
                                if (functionName && name === functionName.escapedText) {
                                    result = location.symbol;
                                    break loop;
                                }
                            }
                            break;
                        case 150 /* Decorator */:
                            // Decorators are resolved at the class declaration. Resolving at the parameter
                            // or member would result in looking up locals in the method.
                            //
                            //   function y() {}
                            //   class C {
                            //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
                            //   }
                            //
                            if (location.parent && location.parent.kind === 149 /* Parameter */) {
                                location = location.parent;
                            }
                            //
                            //   function y() {}
                            //   class C {
                            //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
                            //   }
                            //
                            if (location.parent && ts.isClassElement(location.parent)) {
                                location = location.parent;
                            }
                            break;
                        case 302 /* JSDocTypedefTag */:
                        case 295 /* JSDocCallbackTag */:
                            // js type aliases do not resolve names from their host, so skip past it
                            location = ts.getJSDocHost(location);
                            break;
                    }
                    if (isSelfReferenceLocation(location)) {
                        lastSelfReferenceLocation = location;
                    }
                    lastLocation = location;
                    location = location.parent;
                }
                // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
                // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
                // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
                if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
                    result.isReferenced |= meaning;
                }
                if (!result) {
                    if (lastLocation) {
                        ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */);
                        if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
                            return lastLocation.symbol;
                        }
                    }
                    if (!excludeGlobals) {
                        result = lookup(globals, name, meaning);
                    }
                }
                if (!result) {
                    if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
                        if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
                            return requireSymbol;
                        }
                    }
                }
                if (!result) {
                    if (nameNotFoundMessage) {
                        if (!errorLocation ||
                            !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
                                !checkAndReportErrorForExtendingInterface(errorLocation) &&
                                !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
                                !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
                                !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
                            var suggestion = void 0;
                            if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
                                suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
                                if (suggestion) {
                                    var suggestionName = symbolToString(suggestion);
                                    var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
                                    if (suggestion.valueDeclaration) {
                                        addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
                                    }
                                }
                            }
                            if (!suggestion) {
                                error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
                            }
                            suggestionCount++;
                        }
                    }
                    return undefined;
                }
                // Perform extra checks only if error reporting was requested
                if (nameNotFoundMessage) {
                    if (propertyWithInvalidInitializer) {
                        // We have a match, but the reference occurred within a property initializer and the identifier also binds
                        // to a local variable in the constructor where the code will be emitted.
                        var propertyName = propertyWithInvalidInitializer.name;
                        error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
                        return undefined;
                    }
                    // Only check for block-scoped variable if we have an error location and are looking for the
                    // name with variable meaning
                    //      For example,
                    //          declare module foo {
                    //              interface bar {}
                    //          }
                    //      const foo/*1*/: foo/*2*/.bar;
                    // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
                    // block-scoped variable and namespace module. However, only when we
                    // try to resolve name in /*1*/ which is used in variable position,
                    // we want to check for block-scoped
                    if (errorLocation &&
                        (meaning & 2 /* BlockScopedVariable */ ||
                            ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) {
                        var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
                        if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
                            checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
                        }
                    }
                    // If we're in an external module, we can't reference value symbols created from UMD export declarations
                    if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) {
                        var decls = result.declarations;
                        if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) {
                            error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217
                        }
                    }
                }
                return result;
            }
            function isSelfReferenceLocation(node) {
                switch (node.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 242 /* ModuleDeclaration */: // For `namespace N { N; }`
                        return true;
                    default:
                        return false;
                }
            }
            function diagnosticName(nameArg) {
                return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
            }
            function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
                for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                    var decl = _a[_i];
                    if (decl.kind === 148 /* TypeParameter */) {
                        var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
                        if (parent === container) {
                            return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
                        }
                    }
                }
                return false;
            }
            function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
                if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
                    return false;
                }
                var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
                var location = container;
                while (location) {
                    if (ts.isClassLike(location.parent)) {
                        var classSymbol = getSymbolOfNode(location.parent);
                        if (!classSymbol) {
                            break;
                        }
                        // Check to see if a static member exists.
                        var constructorType = getTypeOfSymbol(classSymbol);
                        if (getPropertyOfType(constructorType, name)) {
                            error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
                            return true;
                        }
                        // No static member is present.
                        // Check if we're in an instance method and look for a relevant instance member.
                        if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
                            var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
                            if (getPropertyOfType(instanceType, name)) {
                                error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
                                return true;
                            }
                        }
                    }
                    location = location.parent;
                }
                return false;
            }
            function checkAndReportErrorForExtendingInterface(errorLocation) {
                var expression = getEntityNameForExtendingInterface(errorLocation);
                if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
                    error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
                    return true;
                }
                return false;
            }
            /**
             * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
             * but returns undefined if that expression is not an EntityNameExpression.
             */
            function getEntityNameForExtendingInterface(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                    case 187 /* PropertyAccessExpression */:
                        return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
                    case 209 /* ExpressionWithTypeArguments */:
                        if (ts.isEntityNameExpression(node.expression)) {
                            return node.expression;
                        }
                    // falls through
                    default:
                        return undefined;
                }
            }
            function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
                var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0);
                if (meaning === namespaceMeaning) {
                    var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
                    var parent = errorLocation.parent;
                    if (symbol) {
                        if (ts.isQualifiedName(parent)) {
                            ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
                            var propName = parent.right.escapedText;
                            var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
                            if (propType) {
                                error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName));
                                return true;
                            }
                        }
                        error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
                        return true;
                    }
                }
                return false;
            }
            function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
                if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
                    if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
                        error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
                        return true;
                    }
                    var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
                    if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
                        var message = (name === "Promise" || name === "Symbol")
                            ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
                            : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
                        error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
                        return true;
                    }
                }
                return false;
            }
            function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
                if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
                    var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
                    if (symbol) {
                        error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
                        return true;
                    }
                }
                else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) {
                    var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
                    if (symbol) {
                        error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
                        return true;
                    }
                }
                return false;
            }
            function checkResolvedBlockScopedVariable(result, errorLocation) {
                ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
                // Block-scoped variables cannot be used before their definition
                var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); });
                if (declaration === undefined)
                    return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined");
                if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
                    var diagnosticMessage = void 0;
                    var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
                    if (result.flags & 2 /* BlockScopedVariable */) {
                        diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
                    }
                    else if (result.flags & 32 /* Class */) {
                        diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
                    }
                    else if (result.flags & 256 /* RegularEnum */) {
                        diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
                    }
                    else {
                        ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
                        if (compilerOptions.preserveConstEnums) {
                            diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
                        }
                    }
                    if (diagnosticMessage) {
                        addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
                    }
                }
            }
            /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
             * If at any point current node is equal to 'parent' node - return true.
             * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
             */
            function isSameScopeDescendentOf(initial, parent, stopAt) {
                return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
            }
            function getAnyImportSyntax(node) {
                switch (node.kind) {
                    case 246 /* ImportEqualsDeclaration */:
                        return node;
                    case 248 /* ImportClause */:
                        return node.parent;
                    case 249 /* NamespaceImport */:
                        return node.parent.parent;
                    case 251 /* ImportSpecifier */:
                        return node.parent.parent.parent;
                    default:
                        return undefined;
                }
            }
            function getDeclarationOfAliasSymbol(symbol) {
                return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration);
            }
            function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
                if (node.moduleReference.kind === 257 /* ExternalModuleReference */) {
                    return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node)));
                }
                return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
            }
            function resolveExportByName(moduleSymbol, name, dontResolveAlias) {
                var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
                return exportValue
                    ? getPropertyOfType(getTypeOfSymbol(exportValue), name)
                    : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias);
            }
            function isSyntacticDefault(node) {
                return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
            }
            function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
                if (!allowSyntheticDefaultImports) {
                    return false;
                }
                // Declaration files (and ambient modules)
                if (!file || file.isDeclarationFile) {
                    // Definitely cannot have a synthetic default if they have a syntactic default member specified
                    var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
                    if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
                        return false;
                    }
                    // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
                    // So we check a bit more,
                    if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) {
                        // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
                        // it definitely is a module and does not have a synthetic default
                        return false;
                    }
                    // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
                    // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
                    // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
                    return true;
                }
                // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
                if (!ts.isSourceFileJS(file)) {
                    return hasExportAssignmentSymbol(moduleSymbol);
                }
                // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker
                return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias);
            }
            function getTargetOfImportClause(node, dontResolveAlias) {
                var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
                if (moduleSymbol) {
                    var exportDefaultSymbol = void 0;
                    if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
                        exportDefaultSymbol = moduleSymbol;
                    }
                    else {
                        exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias);
                    }
                    var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
                    var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
                    if (!exportDefaultSymbol && !hasSyntheticDefault) {
                        error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
                    }
                    else if (hasSyntheticDefault) {
                        // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
                        return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
                    }
                    return exportDefaultSymbol;
                }
            }
            function getTargetOfNamespaceImport(node, dontResolveAlias) {
                var moduleSpecifier = node.parent.parent.moduleSpecifier;
                return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias);
            }
            // This function creates a synthetic symbol that combines the value side of one symbol with the
            // type/namespace side of another symbol. Consider this example:
            //
            //   declare module graphics {
            //       interface Point {
            //           x: number;
            //           y: number;
            //       }
            //   }
            //   declare var graphics: {
            //       Point: new (x: number, y: number) => graphics.Point;
            //   }
            //   declare module "graphics" {
            //       export = graphics;
            //   }
            //
            // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
            // property with the type/namespace side interface 'Point'.
            function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
                if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
                    return unknownSymbol;
                }
                if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) {
                    return valueSymbol;
                }
                var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
                result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
                result.parent = valueSymbol.parent || typeSymbol.parent;
                if (valueSymbol.valueDeclaration)
                    result.valueDeclaration = valueSymbol.valueDeclaration;
                if (typeSymbol.members)
                    result.members = typeSymbol.members;
                if (valueSymbol.exports)
                    result.exports = valueSymbol.exports;
                return result;
            }
            function getExportOfModule(symbol, name, dontResolveAlias) {
                if (symbol.flags & 1536 /* Module */) {
                    return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias);
                }
            }
            function getPropertyOfVariable(symbol, name) {
                if (symbol.flags & 3 /* Variable */) {
                    var typeAnnotation = symbol.valueDeclaration.type;
                    if (typeAnnotation) {
                        return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
                    }
                }
            }
            function getExternalModuleMember(node, specifier, dontResolveAlias) {
                if (dontResolveAlias === void 0) {
                    dontResolveAlias = false;
                }
                var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
                var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias);
                if (targetSymbol) {
                    var name = specifier.propertyName || specifier.name;
                    if (name.escapedText) {
                        if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
                            return moduleSymbol;
                        }
                        var symbolFromVariable = void 0;
                        // First check if module was specified with "export=". If so, get the member from the resolved type
                        if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
                            symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
                        }
                        else {
                            symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
                        }
                        // if symbolFromVariable is export - get its final target
                        symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
                        var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias);
                        // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default
                        if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) {
                            symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
                        }
                        var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
                            combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
                            symbolFromModule || symbolFromVariable;
                        if (!symbol) {
                            var moduleName = getFullyQualifiedName(moduleSymbol);
                            var declarationName = ts.declarationNameToString(name);
                            var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
                            if (suggestion !== undefined) {
                                var suggestionName = symbolToString(suggestion);
                                var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
                                if (suggestion.valueDeclaration) {
                                    addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
                                }
                            }
                            else {
                                error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
                            }
                        }
                        return symbol;
                    }
                }
            }
            function getTargetOfImportSpecifier(node, dontResolveAlias) {
                return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
            }
            function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
                return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
            }
            function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
                return node.parent.parent.moduleSpecifier ?
                    getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
                    resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
            }
            function getTargetOfExportAssignment(node, dontResolveAlias) {
                var expression = (ts.isExportAssignment(node) ? node.expression : node.right);
                if (ts.isClassExpression(expression)) {
                    return checkExpression(expression).symbol;
                }
                var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
                if (aliasLike) {
                    return aliasLike;
                }
                checkExpression(expression);
                return getNodeLinks(expression).resolvedSymbol;
            }
            function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
                if (dontRecursivelyResolve === void 0) {
                    dontRecursivelyResolve = false;
                }
                switch (node.kind) {
                    case 246 /* ImportEqualsDeclaration */:
                        return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
                    case 248 /* ImportClause */:
                        return getTargetOfImportClause(node, dontRecursivelyResolve);
                    case 249 /* NamespaceImport */:
                        return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
                    case 251 /* ImportSpecifier */:
                        return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
                    case 255 /* ExportSpecifier */:
                        return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
                    case 252 /* ExportAssignment */:
                    case 202 /* BinaryExpression */:
                        return getTargetOfExportAssignment(node, dontRecursivelyResolve);
                    case 245 /* NamespaceExportDeclaration */:
                        return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
                    default:
                        return ts.Debug.fail();
                }
            }
            /**
             * Indicates that a symbol is an alias that does not merge with a local declaration.
             * OR Is a JSContainer which may merge an alias with a local declaration
             */
            function isNonLocalAlias(symbol, excludes) {
                if (excludes === void 0) {
                    excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */;
                }
                if (!symbol)
                    return false;
                return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
            }
            function resolveSymbol(symbol, dontResolveAlias) {
                return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
            }
            function resolveAlias(symbol) {
                ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
                var links = getSymbolLinks(symbol);
                if (!links.target) {
                    links.target = resolvingSymbol;
                    var node = getDeclarationOfAliasSymbol(symbol);
                    if (!node)
                        return ts.Debug.fail();
                    var target = getTargetOfAliasDeclaration(node);
                    if (links.target === resolvingSymbol) {
                        links.target = target || unknownSymbol;
                    }
                    else {
                        error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
                    }
                }
                else if (links.target === resolvingSymbol) {
                    links.target = unknownSymbol;
                }
                return links.target;
            }
            function markExportAsReferenced(node) {
                var symbol = getSymbolOfNode(node);
                var target = resolveAlias(symbol);
                if (target) {
                    var markAlias = target === unknownSymbol ||
                        ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target));
                    if (markAlias) {
                        markAliasSymbolAsReferenced(symbol);
                    }
                }
            }
            // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
            // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
            // the alias as an expression (which recursively takes us back here if the target references another alias).
            function markAliasSymbolAsReferenced(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.referenced) {
                    links.referenced = true;
                    var node = getDeclarationOfAliasSymbol(symbol);
                    if (!node)
                        return ts.Debug.fail();
                    if (node.kind === 252 /* ExportAssignment */) {
                        // export default <symbol>
                        checkExpressionCached(node.expression);
                    }
                    else if (node.kind === 255 /* ExportSpecifier */) {
                        // export { <symbol> } or export { <symbol> as foo }
                        checkExpressionCached(node.propertyName || node.name);
                    }
                    else if (ts.isInternalModuleImportEqualsDeclaration(node)) {
                        // import foo = <symbol>
                        checkExpressionCached(node.moduleReference);
                    }
                }
            }
            // This function is only for imports with entity names
            function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
                // There are three things we might try to look for. In the following examples,
                // the search term is enclosed in |...|:
                //
                //     import a = |b|; // Namespace
                //     import a = |b.c|; // Value, type, namespace
                //     import a = |b.c|.d; // Namespace
                if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
                    entityName = entityName.parent;
                }
                // Check for case 1 and 3 in the above example
                if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) {
                    return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
                }
                else {
                    // Case 2 in above example
                    // entityName.kind could be a QualifiedName or a Missing identifier
                    ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */);
                    return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
                }
            }
            function getFullyQualifiedName(symbol) {
                return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol);
            }
            /**
             * Resolves a qualified name and any involved aliases.
             */
            function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
                if (ts.nodeIsMissing(name)) {
                    return undefined;
                }
                var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0);
                var symbol;
                if (name.kind === 71 /* Identifier */) {
                    var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText);
                    var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
                    symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true);
                    if (!symbol) {
                        return symbolFromJSPrototype;
                    }
                }
                else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) {
                    var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression;
                    var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name;
                    var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
                    if (!namespace || ts.nodeIsMissing(right)) {
                        return undefined;
                    }
                    else if (namespace === unknownSymbol) {
                        return namespace;
                    }
                    if (ts.isInJSFile(name)) {
                        if (namespace.valueDeclaration &&
                            ts.isVariableDeclaration(namespace.valueDeclaration) &&
                            namespace.valueDeclaration.initializer &&
                            isCommonJsRequire(namespace.valueDeclaration.initializer)) {
                            var moduleName = namespace.valueDeclaration.initializer.arguments[0];
                            var moduleSym = resolveExternalModuleName(moduleName, moduleName);
                            if (moduleSym) {
                                var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
                                if (resolvedModuleSymbol) {
                                    namespace = resolvedModuleSymbol;
                                }
                            }
                        }
                    }
                    symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning);
                    if (!symbol) {
                        if (!ignoreErrors) {
                            error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
                        }
                        return undefined;
                    }
                }
                else {
                    throw ts.Debug.assertNever(name, "Unknown entity name kind.");
                }
                ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
                return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
            }
            /**
             * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
             * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
             * name resolution won't work either.
             * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
             */
            function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
                if (isJSDocTypeReference(name.parent)) {
                    var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
                    if (secondaryLocation) {
                        return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
                    }
                }
            }
            function getAssignmentDeclarationLocation(node) {
                var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
                if (typeAlias) {
                    return;
                }
                var host = ts.getJSDocHost(node);
                if (ts.isExpressionStatement(host) &&
                    ts.isBinaryExpression(host.expression) &&
                    ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
                    // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
                    var symbol = getSymbolOfNode(host.expression.left);
                    if (symbol) {
                        return getDeclarationOfJSPrototypeContainer(symbol);
                    }
                }
                if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
                    ts.isBinaryExpression(host.parent.parent) &&
                    ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
                    // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
                    var symbol = getSymbolOfNode(host.parent.parent.left);
                    if (symbol) {
                        return getDeclarationOfJSPrototypeContainer(symbol);
                    }
                }
                var sig = ts.getHostSignatureFromJSDocHost(host);
                if (sig) {
                    var symbol = getSymbolOfNode(sig);
                    return symbol && symbol.valueDeclaration;
                }
            }
            function getDeclarationOfJSPrototypeContainer(symbol) {
                var decl = symbol.parent.valueDeclaration;
                var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
                    ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
                        undefined;
                return initializer || decl;
            }
            function resolveExternalModuleName(location, moduleReferenceExpression) {
                return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
            }
            function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
                if (isForAugmentation === void 0) {
                    isForAugmentation = false;
                }
                return ts.isStringLiteralLike(moduleReferenceExpression)
                    ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
                    : undefined;
            }
            function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
                if (isForAugmentation === void 0) {
                    isForAugmentation = false;
                }
                if (moduleReference === undefined) {
                    return;
                }
                if (ts.startsWith(moduleReference, "@types/")) {
                    var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
                    var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
                    error(errorNode, diag, withoutAtTypePrefix, moduleReference);
                }
                var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
                if (ambientModule) {
                    return ambientModule;
                }
                var currentSourceFile = ts.getSourceFileOfNode(location);
                var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
                var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
                var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
                if (sourceFile) {
                    if (sourceFile.symbol) {
                        if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) {
                            errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
                        }
                        // merged symbol is module declaration symbol combined with all augmentations
                        return getMergedSymbol(sourceFile.symbol);
                    }
                    if (moduleNotFoundError) {
                        // report errors only if it was requested
                        error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
                    }
                    return undefined;
                }
                if (patternAmbientModules) {
                    var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
                    if (pattern) {
                        return getMergedSymbol(pattern.symbol);
                    }
                }
                // May be an untyped module. If so, ignore resolutionDiagnostic.
                if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
                    if (isForAugmentation) {
                        var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
                        error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
                    }
                    else {
                        errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
                    }
                    // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
                    return undefined;
                }
                if (moduleNotFoundError) {
                    // For relative paths, see if this was possibly a projectReference redirect
                    if (ts.pathIsRelative(moduleReference)) {
                        var sourceFile_1 = ts.getSourceFileOfNode(location);
                        var redirects = sourceFile_1.redirectedReferences;
                        if (redirects) {
                            var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
                            for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
                                var ext = _a[_i];
                                var probePath = normalizedTargetPath + ext;
                                if (redirects.indexOf(probePath) >= 0) {
                                    error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
                                    return undefined;
                                }
                            }
                        }
                    }
                    if (resolutionDiagnostic) {
                        error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
                    }
                    else {
                        var tsExtension = ts.tryExtractTSExtension(moduleReference);
                        if (tsExtension) {
                            var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
                            error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
                        }
                        else if (!compilerOptions.resolveJsonModule &&
                            ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
                            ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
                            ts.hasJsonModuleEmitEnabled(compilerOptions)) {
                            error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
                        }
                        else {
                            error(errorNode, moduleNotFoundError, moduleReference);
                        }
                    }
                }
                return undefined;
            }
            function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
                var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
                var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
                    ? typesPackageExists(packageId.name)
                        ? ts.chainDiagnosticMessages(
                        /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name))
                        : ts.chainDiagnosticMessages(
                        /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
                    : undefined;
                errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName));
            }
            function typesPackageExists(packageName) {
                return getPackagesSet().has(ts.getTypesPackageName(packageName));
            }
            function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
                return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol;
            }
            function getCommonJsExportEquals(exported, moduleSymbol) {
                if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) {
                    return exported;
                }
                var merged = cloneSymbol(exported);
                if (merged.exports === undefined) {
                    merged.flags = merged.flags | 512 /* ValueModule */;
                    merged.exports = ts.createSymbolTable();
                }
                moduleSymbol.exports.forEach(function (s, name) {
                    if (name === "export=" /* ExportEquals */)
                        return;
                    merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
                });
                return merged;
            }
            // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
            // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
            // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
            function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
                var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
                if (!dontResolveAlias && symbol) {
                    if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) {
                        error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol));
                        return symbol;
                    }
                    if (compilerOptions.esModuleInterop) {
                        var referenceParent = referencingLocation.parent;
                        if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
                            ts.isImportCall(referenceParent)) {
                            var type = getTypeOfSymbol(symbol);
                            var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
                            if (!sigs || !sigs.length) {
                                sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
                            }
                            if (sigs && sigs.length) {
                                var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
                                // Create a new symbol which has the module's type less the call and construct signatures
                                var result = createSymbol(symbol.flags, symbol.escapedName);
                                result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
                                result.parent = symbol.parent;
                                result.target = symbol;
                                result.originatingImport = referenceParent;
                                if (symbol.valueDeclaration)
                                    result.valueDeclaration = symbol.valueDeclaration;
                                if (symbol.constEnumOnlyModule)
                                    result.constEnumOnlyModule = true;
                                if (symbol.members)
                                    result.members = ts.cloneMap(symbol.members);
                                if (symbol.exports)
                                    result.exports = ts.cloneMap(symbol.exports);
                                var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
                                result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
                                return result;
                            }
                        }
                    }
                }
                return symbol;
            }
            function hasExportAssignmentSymbol(moduleSymbol) {
                return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
            }
            function getExportsOfModuleAsArray(moduleSymbol) {
                return symbolsToArray(getExportsOfModule(moduleSymbol));
            }
            function getExportsAndPropertiesOfModule(moduleSymbol) {
                var exports = getExportsOfModuleAsArray(moduleSymbol);
                var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
                if (exportEquals !== moduleSymbol) {
                    ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
                }
                return exports;
            }
            function tryGetMemberInModuleExports(memberName, moduleSymbol) {
                var symbolTable = getExportsOfModule(moduleSymbol);
                if (symbolTable) {
                    return symbolTable.get(memberName);
                }
            }
            function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
                var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
                if (symbol) {
                    return symbol;
                }
                var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
                if (exportEquals === moduleSymbol) {
                    return undefined;
                }
                var type = getTypeOfSymbol(exportEquals);
                return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName);
            }
            function getExportsOfSymbol(symbol) {
                return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
                    symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
                        symbol.exports || emptySymbols;
            }
            function getExportsOfModule(moduleSymbol) {
                var links = getSymbolLinks(moduleSymbol);
                return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
            }
            /**
             * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
             * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
             */
            function extendExportSymbols(target, source, lookupTable, exportNode) {
                if (!source)
                    return;
                source.forEach(function (sourceSymbol, id) {
                    if (id === "default" /* Default */)
                        return;
                    var targetSymbol = target.get(id);
                    if (!targetSymbol) {
                        target.set(id, sourceSymbol);
                        if (lookupTable && exportNode) {
                            lookupTable.set(id, {
                                specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
                            });
                        }
                    }
                    else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
                        var collisionTracker = lookupTable.get(id);
                        if (!collisionTracker.exportsWithDuplicate) {
                            collisionTracker.exportsWithDuplicate = [exportNode];
                        }
                        else {
                            collisionTracker.exportsWithDuplicate.push(exportNode);
                        }
                    }
                });
            }
            function getExportsOfModuleWorker(moduleSymbol) {
                var visitedSymbols = [];
                // A module defined by an 'export=' consists of one export that needs to be resolved
                moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
                return visit(moduleSymbol) || emptySymbols;
                // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
                // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
                function visit(symbol) {
                    if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
                        return;
                    }
                    var symbols = ts.cloneMap(symbol.exports);
                    // All export * declarations are collected in an __export symbol by the binder
                    var exportStars = symbol.exports.get("__export" /* ExportStar */);
                    if (exportStars) {
                        var nestedSymbols = ts.createSymbolTable();
                        var lookupTable_1 = ts.createMap();
                        for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
                            var node = _a[_i];
                            var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
                            var exportedSymbols = visit(resolvedModule);
                            extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
                        }
                        lookupTable_1.forEach(function (_a, id) {
                            var exportsWithDuplicate = _a.exportsWithDuplicate;
                            // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
                            if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
                                return;
                            }
                            for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
                                var node = exportsWithDuplicate_1[_i];
                                diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id)));
                            }
                        });
                        extendExportSymbols(symbols, nestedSymbols);
                    }
                    return symbols;
                }
            }
            function getMergedSymbol(symbol) {
                var merged;
                return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
            }
            function getSymbolOfNode(node) {
                return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
            }
            function getParentOfSymbol(symbol) {
                return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
            }
            /**
             * Attempts to find the symbol corresponding to the container a symbol is in - usually this
             * is just its' `.parent`, but for locals, this value is `undefined`
             */
            function getContainersOfSymbol(symbol, enclosingDeclaration) {
                var container = getParentOfSymbol(symbol);
                if (container) {
                    var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
                    if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
                        return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope
                    }
                    return ts.append(additionalContainers, container);
                }
                var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; });
                if (!ts.length(candidates)) {
                    return undefined;
                }
                return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
                function fileSymbolIfFileSymbolExportEqualsContainer(d) {
                    var fileSymbol = getExternalModuleContainer(d);
                    var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
                    return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined;
                }
            }
            function getAliasForSymbolInContainer(container, symbol) {
                if (container === getParentOfSymbol(symbol)) {
                    // fast path, `symbol` is either already the alias or isn't aliased
                    return symbol;
                }
                var exports = getExportsOfSymbol(container);
                var quick = exports.get(symbol.escapedName);
                if (quick && symbolRefersToTarget(quick)) {
                    return quick;
                }
                return ts.forEachEntry(exports, function (exported) {
                    if (symbolRefersToTarget(exported)) {
                        return exported;
                    }
                });
                function symbolRefersToTarget(s) {
                    if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) {
                        return s;
                    }
                }
            }
            function getExportSymbolOfValueSymbolIfExported(symbol) {
                return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
            }
            function symbolIsValue(symbol) {
                return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */);
            }
            function findConstructorDeclaration(node) {
                var members = node.members;
                for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
                    var member = members_2[_i];
                    if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) {
                        return member;
                    }
                }
            }
            function createType(flags) {
                var result = new Type(checker, flags);
                typeCount++;
                result.id = typeCount;
                return result;
            }
            function createIntrinsicType(kind, intrinsicName) {
                var type = createType(kind);
                type.intrinsicName = intrinsicName;
                return type;
            }
            function createBooleanType(trueFalseTypes) {
                var type = getUnionType(trueFalseTypes);
                type.flags |= 16 /* Boolean */;
                type.intrinsicName = "boolean";
                return type;
            }
            function createObjectType(objectFlags, symbol) {
                var type = createType(131072 /* Object */);
                type.objectFlags = objectFlags;
                type.symbol = symbol;
                type.members = undefined;
                type.properties = undefined;
                type.callSignatures = undefined;
                type.constructSignatures = undefined;
                type.stringIndexInfo = undefined;
                type.numberIndexInfo = undefined;
                return type;
            }
            function createTypeofType() {
                return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
            }
            // A reserved member name starts with two underscores, but the third character cannot be an underscore
            // or the @ symbol. A third underscore indicates an escaped form of an identifer that started
            // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
            // Symbol instance.
            function isReservedMemberName(name) {
                return name.charCodeAt(0) === 95 /* _ */ &&
                    name.charCodeAt(1) === 95 /* _ */ &&
                    name.charCodeAt(2) !== 95 /* _ */ &&
                    name.charCodeAt(2) !== 64 /* at */;
            }
            function getNamedMembers(members) {
                var result;
                members.forEach(function (symbol, id) {
                    if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
                        (result || (result = [])).push(symbol);
                    }
                });
                return result || ts.emptyArray;
            }
            function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
                type.members = members;
                type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
                type.callSignatures = callSignatures;
                type.constructSignatures = constructSignatures;
                type.stringIndexInfo = stringIndexInfo;
                type.numberIndexInfo = numberIndexInfo;
                return type;
            }
            function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
                return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
            }
            function forEachSymbolTableInScope(enclosingDeclaration, callback) {
                var result;
                for (var location = enclosingDeclaration; location; location = location.parent) {
                    // Locals of a source file are not in scope (because they get merged into the global symbol table)
                    if (location.locals && !isGlobalSourceFile(location)) {
                        if (result = callback(location.locals)) {
                            return result;
                        }
                    }
                    switch (location.kind) {
                        case 277 /* SourceFile */:
                            if (!ts.isExternalOrCommonJsModule(location)) {
                                break;
                            }
                        // falls through
                        case 242 /* ModuleDeclaration */:
                            if (result = callback(getSymbolOfNode(location).exports)) {
                                return result;
                            }
                            break;
                    }
                }
                return callback(globals);
            }
            function getQualifiedLeftMeaning(rightMeaning) {
                // If we are looking in value space, the parent meaning is value, other wise it is namespace
                return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */;
            }
            function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
                if (visitedSymbolTablesMap === void 0) {
                    visitedSymbolTablesMap = ts.createMap();
                }
                if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
                    return undefined;
                }
                var id = "" + getSymbolId(symbol);
                var visitedSymbolTables = visitedSymbolTablesMap.get(id);
                if (!visitedSymbolTables) {
                    visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
                }
                return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
                /**
                 * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already)
                 */
                function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
                    if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
                        return undefined;
                    }
                    var result = trySymbolTable(symbols, ignoreQualification);
                    visitedSymbolTables.pop();
                    return result;
                }
                function canQualifySymbol(symbolFromSymbolTable, meaning) {
                    // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
                    return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
                        // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
                        !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
                }
                function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
                    return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) &&
                        // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
                        // and if symbolFromSymbolTable or alias resolution matches the symbol,
                        // check the symbol can be qualified, it is only then this symbol is accessible
                        !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
                        (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning));
                }
                function trySymbolTable(symbols, ignoreQualification) {
                    // If symbol is directly available by its name in the symbol table
                    if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
                        return [symbol];
                    }
                    // Check if symbol is any of the alias
                    return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
                        if (symbolFromSymbolTable.flags & 2097152 /* Alias */
                            && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
                            && symbolFromSymbolTable.escapedName !== "default" /* Default */
                            && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
                            // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
                            && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
                            // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
                            // See similar comment in `resolveName` for details
                            && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) {
                            var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
                            if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
                                return [symbolFromSymbolTable];
                            }
                            // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
                            // but only if the symbolFromSymbolTable can be qualified
                            var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
                            var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
                            if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
                                return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
                            }
                        }
                        if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
                            if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
                                return [symbol];
                            }
                        }
                    });
                }
            }
            function needsQualification(symbol, enclosingDeclaration, meaning) {
                var qualify = false;
                forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
                    // If symbol of this name is not available in the symbol table we are ok
                    var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
                    if (!symbolFromSymbolTable) {
                        // Continue to the next symbol table
                        return false;
                    }
                    // If the symbol with this name is present it should refer to the symbol
                    if (symbolFromSymbolTable === symbol) {
                        // No need to qualify
                        return true;
                    }
                    // Qualify if the symbol from symbol table has same meaning as expected
                    symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
                    if (symbolFromSymbolTable.flags & meaning) {
                        qualify = true;
                        return true;
                    }
                    // Continue to the next symbol table
                    return false;
                });
                return qualify;
            }
            function isPropertyOrMethodDeclarationSymbol(symbol) {
                if (symbol.declarations && symbol.declarations.length) {
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var declaration = _a[_i];
                        switch (declaration.kind) {
                            case 152 /* PropertyDeclaration */:
                            case 154 /* MethodDeclaration */:
                            case 156 /* GetAccessor */:
                            case 157 /* SetAccessor */:
                                continue;
                            default:
                                return false;
                        }
                    }
                    return true;
                }
                return false;
            }
            function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
                var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
                return access.accessibility === 0 /* Accessible */;
            }
            function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
                var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
                return access.accessibility === 0 /* Accessible */;
            }
            function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
                if (!ts.length(symbols))
                    return;
                var hadAccessibleChain;
                for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
                    var symbol = _a[_i];
                    // Symbol is accessible if it by itself is accessible
                    var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
                    if (accessibleSymbolChain) {
                        hadAccessibleChain = symbol;
                        var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
                        if (hasAccessibleDeclarations) {
                            return hasAccessibleDeclarations;
                        }
                    }
                    else {
                        if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
                            // Any meaning of a module symbol is always accessible via an `import` type
                            return {
                                accessibility: 0 /* Accessible */
                            };
                        }
                    }
                    // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
                    // It could be a qualified symbol and hence verify the path
                    // e.g.:
                    // module m {
                    //     export class c {
                    //     }
                    // }
                    // const x: typeof m.c
                    // In the above example when we start with checking if typeof m.c symbol is accessible,
                    // we are going to see if c can be accessed in scope directly.
                    // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
                    // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
                    var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
                    // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
                    // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
                    // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal.
                    var firstDecl = ts.first(symbol.declarations);
                    if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
                        if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
                            containers = [getSymbolOfNode(firstDecl.parent)];
                        }
                    }
                    var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
                    if (parentResult) {
                        return parentResult;
                    }
                }
                if (hadAccessibleChain) {
                    return {
                        accessibility: 1 /* NotAccessible */,
                        errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
                        errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
                    };
                }
            }
            /**
             * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
             *
             * @param symbol a Symbol to check if accessible
             * @param enclosingDeclaration a Node containing reference to the symbol
             * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
             * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
             */
            function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
                if (symbol && enclosingDeclaration) {
                    var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
                    if (result) {
                        return result;
                    }
                    // This could be a symbol that is not exported in the external module
                    // or it could be a symbol from different external module that is not aliased and hence cannot be named
                    var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
                    if (symbolExternalModule) {
                        var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
                        if (symbolExternalModule !== enclosingExternalModule) {
                            // name from different external module that is not visible
                            return {
                                accessibility: 2 /* CannotBeNamed */,
                                errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
                                errorModuleName: symbolToString(symbolExternalModule)
                            };
                        }
                    }
                    // Just a local name that is not accessible
                    return {
                        accessibility: 1 /* NotAccessible */,
                        errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
                    };
                }
                return { accessibility: 0 /* Accessible */ };
            }
            function getExternalModuleContainer(declaration) {
                var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
                return node && getSymbolOfNode(node);
            }
            function hasExternalModuleSymbol(declaration) {
                return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
            }
            function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
                return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
            }
            function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
                var aliasesToMakeVisible;
                if (!ts.every(symbol.declarations, getIsDeclarationVisible)) {
                    return undefined;
                }
                return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
                function getIsDeclarationVisible(declaration) {
                    if (!isDeclarationVisible(declaration)) {
                        // Mark the unexported alias as visible if its parent is visible
                        // because these kind of aliases can be used to name types in declaration file
                        var anyImportSyntax = getAnyImportSyntax(declaration);
                        if (anyImportSyntax &&
                            !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
                            isDeclarationVisible(anyImportSyntax.parent)) {
                            return addVisibleAlias(declaration, anyImportSyntax);
                        }
                        else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
                            !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
                            isDeclarationVisible(declaration.parent.parent.parent)) {
                            return addVisibleAlias(declaration, declaration.parent.parent);
                        }
                        else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
                            && !ts.hasModifier(declaration, 1 /* Export */)
                            && isDeclarationVisible(declaration.parent)) {
                            return addVisibleAlias(declaration, declaration);
                        }
                        // Declaration is not visible
                        return false;
                    }
                    return true;
                }
                function addVisibleAlias(declaration, aliasingStatement) {
                    // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
                    // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
                    // since we will do the emitting later in trackSymbol.
                    if (shouldComputeAliasToMakeVisible) {
                        getNodeLinks(declaration).isVisible = true;
                        aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
                    }
                    return true;
                }
            }
            function isEntityNameVisible(entityName, enclosingDeclaration) {
                // get symbol of the first identifier of the entityName
                var meaning;
                if (entityName.parent.kind === 165 /* TypeQuery */ ||
                    ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
                    entityName.parent.kind === 147 /* ComputedPropertyName */) {
                    // Typeof value
                    meaning = 67220415 /* Value */ | 1048576 /* ExportValue */;
                }
                else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ ||
                    entityName.parent.kind === 246 /* ImportEqualsDeclaration */) {
                    // Left identifier from type reference or TypeAlias
                    // Entity name of the import declaration
                    meaning = 1920 /* Namespace */;
                }
                else {
                    // Type Reference or TypeAlias entity = Identifier
                    meaning = 67897832 /* Type */;
                }
                var firstIdentifier = getFirstIdentifier(entityName);
                var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
                // Verify if the symbol is accessible
                return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
                    accessibility: 1 /* NotAccessible */,
                    errorSymbolName: ts.getTextOfNode(firstIdentifier),
                    errorNode: firstIdentifier
                };
            }
            function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
                if (flags === void 0) {
                    flags = 4 /* AllowAnyNodeKind */;
                }
                var nodeFlags = 3112960 /* IgnoreErrors */;
                if (flags & 2 /* UseOnlyExternalAliasing */) {
                    nodeFlags |= 128 /* UseOnlyExternalAliasing */;
                }
                if (flags & 1 /* WriteTypeParametersOrArguments */) {
                    nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
                }
                if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
                    nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
                }
                var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
                return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
                function symbolToStringWorker(writer) {
                    var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
                    var printer = ts.createPrinter({ removeComments: true });
                    var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
                    printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
                    return writer;
                }
            }
            function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
                if (flags === void 0) {
                    flags = 0 /* None */;
                }
                return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
                function signatureToStringWorker(writer) {
                    var sigOutput;
                    if (flags & 262144 /* WriteArrowStyleSignature */) {
                        sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */;
                    }
                    else {
                        sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */;
                    }
                    var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
                    var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
                    var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
                    printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217
                    return writer;
                }
            }
            function typeToString(type, enclosingDeclaration, flags, writer) {
                if (flags === void 0) {
                    flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
                }
                if (writer === void 0) {
                    writer = ts.createTextWriter("");
                }
                var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
                var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
                if (typeNode === undefined)
                    return ts.Debug.fail("should always get typenode");
                var options = { removeComments: true };
                var printer = ts.createPrinter(options);
                var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
                printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
                var result = writer.getText();
                var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2;
                if (maxLength && result && result.length >= maxLength) {
                    return result.substr(0, maxLength - "...".length) + "...";
                }
                return result;
            }
            function toNodeBuilderFlags(flags) {
                if (flags === void 0) {
                    flags = 0 /* None */;
                }
                return flags & 9469291 /* NodeBuilderFlagsMask */;
            }
            function createNodeBuilder() {
                return {
                    typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
                    },
                    indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
                    },
                    signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
                    },
                    symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
                    },
                    symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
                    },
                    symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
                    },
                    symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
                    },
                    typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
                        return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
                    },
                };
                function withContext(enclosingDeclaration, flags, tracker, cb) {
                    ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
                    var context = {
                        enclosingDeclaration: enclosingDeclaration,
                        flags: flags || 0 /* None */,
                        tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop },
                        encounteredError: false,
                        visitedSymbols: undefined,
                        inferTypeParameters: undefined,
                        approximateLength: 0
                    };
                    var resultingNode = cb(context);
                    return context.encounteredError ? undefined : resultingNode;
                }
                function checkTruncationLength(context) {
                    if (context.truncating)
                        return context.truncating;
                    return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength;
                }
                function typeToTypeNodeHelper(type, context) {
                    if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
                        cancellationToken.throwIfCancellationRequested();
                    }
                    var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
                    context.flags &= ~8388608 /* InTypeAlias */;
                    if (!type) {
                        context.encounteredError = true;
                        return undefined; // TODO: GH#18217
                    }
                    if (type.flags & 1 /* Any */) {
                        context.approximateLength += 3;
                        return ts.createKeywordTypeNode(119 /* AnyKeyword */);
                    }
                    if (type.flags & 2 /* Unknown */) {
                        return ts.createKeywordTypeNode(142 /* UnknownKeyword */);
                    }
                    if (type.flags & 4 /* String */) {
                        context.approximateLength += 6;
                        return ts.createKeywordTypeNode(137 /* StringKeyword */);
                    }
                    if (type.flags & 8 /* Number */) {
                        context.approximateLength += 6;
                        return ts.createKeywordTypeNode(134 /* NumberKeyword */);
                    }
                    if (type.flags & 16 /* Boolean */) {
                        context.approximateLength += 7;
                        return ts.createKeywordTypeNode(122 /* BooleanKeyword */);
                    }
                    if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) {
                        var parentSymbol = getParentOfSymbol(type.symbol);
                        var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false);
                        var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol));
                        context.approximateLength += ts.symbolName(type.symbol).length;
                        return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined);
                    }
                    if (type.flags & 544 /* EnumLike */) {
                        var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false);
                        context.approximateLength += ts.symbolName(type.symbol).length;
                        return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
                    }
                    if (type.flags & 64 /* StringLiteral */) {
                        context.approximateLength += (type.value.length + 2);
                        return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */));
                    }
                    if (type.flags & 128 /* NumberLiteral */) {
                        context.approximateLength += (("" + type.value).length);
                        return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
                    }
                    if (type.flags & 256 /* BooleanLiteral */) {
                        context.approximateLength += type.intrinsicName.length;
                        return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
                    }
                    if (type.flags & 2048 /* UniqueESSymbol */) {
                        if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
                            if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
                                context.approximateLength += 6;
                                return symbolToTypeNode(type.symbol, context, 67220415 /* Value */);
                            }
                            if (context.tracker.reportInaccessibleUniqueSymbolError) {
                                context.tracker.reportInaccessibleUniqueSymbolError();
                            }
                        }
                        context.approximateLength += 13;
                        return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */));
                    }
                    if (type.flags & 4096 /* Void */) {
                        context.approximateLength += 4;
                        return ts.createKeywordTypeNode(105 /* VoidKeyword */);
                    }
                    if (type.flags & 8192 /* Undefined */) {
                        context.approximateLength += 9;
                        return ts.createKeywordTypeNode(140 /* UndefinedKeyword */);
                    }
                    if (type.flags & 16384 /* Null */) {
                        context.approximateLength += 4;
                        return ts.createKeywordTypeNode(95 /* NullKeyword */);
                    }
                    if (type.flags & 32768 /* Never */) {
                        context.approximateLength += 5;
                        return ts.createKeywordTypeNode(131 /* NeverKeyword */);
                    }
                    if (type.flags & 1024 /* ESSymbol */) {
                        context.approximateLength += 6;
                        return ts.createKeywordTypeNode(138 /* SymbolKeyword */);
                    }
                    if (type.flags & 16777216 /* NonPrimitive */) {
                        context.approximateLength += 6;
                        return ts.createKeywordTypeNode(135 /* ObjectKeyword */);
                    }
                    if (type.flags & 65536 /* TypeParameter */ && type.isThisType) {
                        if (context.flags & 4194304 /* InObjectTypeLiteral */) {
                            if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
                                context.encounteredError = true;
                            }
                            if (context.tracker.reportInaccessibleThisError) {
                                context.tracker.reportInaccessibleThisError();
                            }
                        }
                        context.approximateLength += 4;
                        return ts.createThis();
                    }
                    var objectFlags = ts.getObjectFlags(type);
                    if (objectFlags & 4 /* Reference */) {
                        ts.Debug.assert(!!(type.flags & 131072 /* Object */));
                        return typeReferenceToTypeNode(type);
                    }
                    if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
                        if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
                            context.approximateLength += (ts.symbolName(type.symbol).length + 6);
                            return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
                        }
                        if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
                            type.flags & 65536 /* TypeParameter */ &&
                            ts.length(type.symbol.declarations) &&
                            ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
                            typeParameterShadowsNameInScope(type, context) &&
                            !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
                            var name = type.symbol.declarations[0].name;
                            context.approximateLength += ts.idText(name).length;
                            return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined);
                        }
                        // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
                        return type.symbol
                            ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */)
                            : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
                    }
                    if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
                        var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
                        if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
                            return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
                        return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes);
                    }
                    if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) {
                        var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types;
                        var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
                        if (typeNodes && typeNodes.length > 0) {
                            var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes);
                            return unionOrIntersectionTypeNode;
                        }
                        else {
                            if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
                                context.encounteredError = true;
                            }
                            return undefined; // TODO: GH#18217
                        }
                    }
                    if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
                        ts.Debug.assert(!!(type.flags & 131072 /* Object */));
                        // The type is an object literal type.
                        return createAnonymousTypeNode(type);
                    }
                    if (type.flags & 1048576 /* Index */) {
                        var indexedType = type.type;
                        context.approximateLength += 6;
                        var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
                        return ts.createTypeOperatorNode(indexTypeNode);
                    }
                    if (type.flags & 2097152 /* IndexedAccess */) {
                        var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
                        var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
                        context.approximateLength += 2;
                        return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
                    }
                    if (type.flags & 4194304 /* Conditional */) {
                        var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
                        var saveInferTypeParameters = context.inferTypeParameters;
                        context.inferTypeParameters = type.root.inferTypeParameters;
                        var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
                        context.inferTypeParameters = saveInferTypeParameters;
                        var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
                        var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
                        context.approximateLength += 15;
                        return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
                    }
                    if (type.flags & 8388608 /* Substitution */) {
                        return typeToTypeNodeHelper(type.typeVariable, context);
                    }
                    return ts.Debug.fail("Should be unreachable.");
                    function createMappedTypeNodeFromType(type) {
                        ts.Debug.assert(!!(type.flags & 131072 /* Object */));
                        var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
                        var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
                        var appropriateConstraintTypeNode;
                        if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
                            // We have a { [P in keyof T]: X }
                            // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
                            appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
                        }
                        else {
                            appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
                        }
                        var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
                        var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
                        var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
                        context.approximateLength += 10;
                        return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
                    }
                    function createAnonymousTypeNode(type) {
                        var symbol = type.symbol;
                        var id;
                        if (symbol) {
                            var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
                            id = (isConstructorObject ? "+" : "") + getSymbolId(symbol);
                            if (isJSConstructor(symbol.valueDeclaration)) {
                                // Instance and static types share the same symbol; only add 'typeof' for the static side.
                                var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */;
                                return symbolToTypeNode(symbol, context, isInstanceType);
                            }
                            // Always use 'typeof T' for type of class, enum, and module objects
                            else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
                                symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
                                shouldWriteTypeOfFunctionSymbol()) {
                                return symbolToTypeNode(symbol, context, 67220415 /* Value */);
                            }
                            else if (context.visitedSymbols && context.visitedSymbols.has(id)) {
                                // If type is an anonymous type literal in a type alias declaration, use type alias name
                                var typeAlias = getTypeAliasForTypeLiteral(type);
                                if (typeAlias) {
                                    // The specified symbol flags need to be reinterpreted as type flags
                                    return symbolToTypeNode(typeAlias, context, 67897832 /* Type */);
                                }
                                else {
                                    context.approximateLength += 3;
                                    return ts.createKeywordTypeNode(119 /* AnyKeyword */);
                                }
                            }
                            else {
                                // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
                                // of types allows us to catch circular references to instantiations of the same anonymous type
                                if (!context.visitedSymbols) {
                                    context.visitedSymbols = ts.createMap();
                                }
                                context.visitedSymbols.set(id, true);
                                var result = createTypeNodeFromObjectType(type);
                                context.visitedSymbols.delete(id);
                                return result;
                            }
                        }
                        else {
                            // Anonymous types without a symbol are never circular.
                            return createTypeNodeFromObjectType(type);
                        }
                        function shouldWriteTypeOfFunctionSymbol() {
                            var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
                                ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
                            var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
                                (symbol.parent || // is exported function symbol
                                    ts.forEach(symbol.declarations, function (declaration) {
                                        return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */;
                                    }));
                            if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
                                // typeof is allowed only for static/non local functions
                                return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively
                                    (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed
                            }
                        }
                    }
                    function createTypeNodeFromObjectType(type) {
                        if (isGenericMappedType(type)) {
                            return createMappedTypeNodeFromType(type);
                        }
                        var resolved = resolveStructuredTypeMembers(type);
                        if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
                            if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
                                context.approximateLength += 2;
                                return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
                            }
                            if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
                                var signature = resolved.callSignatures[0];
                                var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context);
                                return signatureNode;
                            }
                            if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
                                var signature = resolved.constructSignatures[0];
                                var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context);
                                return signatureNode;
                            }
                        }
                        var savedFlags = context.flags;
                        context.flags |= 4194304 /* InObjectTypeLiteral */;
                        var members = createTypeNodesFromResolvedType(resolved);
                        context.flags = savedFlags;
                        var typeLiteralNode = ts.createTypeLiteralNode(members);
                        context.approximateLength += 2;
                        return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
                    }
                    function typeReferenceToTypeNode(type) {
                        var typeArguments = type.typeArguments || ts.emptyArray;
                        if (type.target === globalArrayType) {
                            if (context.flags & 2 /* WriteArrayAsGenericType */) {
                                var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
                                return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
                            }
                            var elementType = typeToTypeNodeHelper(typeArguments[0], context);
                            return ts.createArrayTypeNode(elementType);
                        }
                        else if (type.target.objectFlags & 8 /* Tuple */) {
                            if (typeArguments.length > 0) {
                                var arity = getTypeReferenceArity(type);
                                var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
                                var hasRestElement = type.target.hasRestElement;
                                if (tupleConstituentNodes) {
                                    for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
                                        tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
                                            ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
                                            ts.createOptionalTypeNode(tupleConstituentNodes[i]);
                                    }
                                    return ts.createTupleTypeNode(tupleConstituentNodes);
                                }
                            }
                            if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
                                return ts.createTupleTypeNode([]);
                            }
                            context.encounteredError = true;
                            return undefined; // TODO: GH#18217
                        }
                        else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
                            type.symbol.valueDeclaration &&
                            ts.isClassLike(type.symbol.valueDeclaration) &&
                            !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
                            return createAnonymousTypeNode(type);
                        }
                        else {
                            var outerTypeParameters = type.target.outerTypeParameters;
                            var i = 0;
                            var resultType = void 0;
                            if (outerTypeParameters) {
                                var length_1 = outerTypeParameters.length;
                                while (i < length_1) {
                                    // Find group of type arguments for type parameters with the same declaring container.
                                    var start = i;
                                    var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
                                    do {
                                        i++;
                                    } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
                                    // When type parameters are their own type arguments for the whole group (i.e. we have
                                    // the default outer type arguments), we don't show the group.
                                    if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
                                        var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
                                        var flags_2 = context.flags;
                                        context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
                                        var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice);
                                        context.flags = flags_2;
                                        resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
                                    }
                                }
                            }
                            var typeArgumentNodes = void 0;
                            if (typeArguments.length > 0) {
                                var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
                                typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
                            }
                            var flags = context.flags;
                            context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
                            var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes);
                            context.flags = flags;
                            return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
                        }
                    }
                    function appendReferenceToType(root, ref) {
                        if (ts.isImportTypeNode(root)) {
                            // first shift type arguments
                            var innerParams = root.typeArguments;
                            if (root.qualifier) {
                                (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
                            }
                            root.typeArguments = ref.typeArguments;
                            // then move qualifiers
                            var ids = getAccessStack(ref);
                            for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
                                var id = ids_1[_i];
                                root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
                            }
                            return root;
                        }
                        else {
                            // first shift type arguments
                            var innerParams = root.typeArguments;
                            (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
                            root.typeArguments = ref.typeArguments;
                            // then move qualifiers
                            var ids = getAccessStack(ref);
                            for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
                                var id = ids_2[_a];
                                root.typeName = ts.createQualifiedName(root.typeName, id);
                            }
                            return root;
                        }
                    }
                    function getAccessStack(ref) {
                        var state = ref.typeName;
                        var ids = [];
                        while (!ts.isIdentifier(state)) {
                            ids.unshift(state.right);
                            state = state.left;
                        }
                        ids.unshift(state);
                        return ids;
                    }
                    function createTypeNodesFromResolvedType(resolvedType) {
                        if (checkTruncationLength(context)) {
                            return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
                        }
                        var typeElements = [];
                        for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
                            var signature = _a[_i];
                            typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context));
                        }
                        for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
                            var signature = _c[_b];
                            typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context));
                        }
                        if (resolvedType.stringIndexInfo) {
                            var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ?
                                createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) :
                                resolvedType.stringIndexInfo;
                            typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context));
                        }
                        if (resolvedType.numberIndexInfo) {
                            typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
                        }
                        var properties = resolvedType.properties;
                        if (!properties) {
                            return typeElements;
                        }
                        var i = 0;
                        for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
                            var propertySymbol = properties_1[_d];
                            i++;
                            if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
                                if (propertySymbol.flags & 4194304 /* Prototype */) {
                                    continue;
                                }
                                if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
                                    context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
                                }
                            }
                            if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
                                typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
                                addPropertyToElementList(properties[properties.length - 1], context, typeElements);
                                break;
                            }
                            addPropertyToElementList(propertySymbol, context, typeElements);
                        }
                        return typeElements.length ? typeElements : undefined;
                    }
                }
                function addPropertyToElementList(propertySymbol, context, typeElements) {
                    var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ?
                        anyType : getTypeOfSymbol(propertySymbol);
                    var saveEnclosingDeclaration = context.enclosingDeclaration;
                    context.enclosingDeclaration = undefined;
                    if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) {
                        var decl = ts.first(propertySymbol.declarations);
                        if (hasLateBindableName(decl)) {
                            trackComputedName(decl.name, saveEnclosingDeclaration, context);
                        }
                    }
                    var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true);
                    context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
                    context.enclosingDeclaration = saveEnclosingDeclaration;
                    var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined;
                    if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
                        var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
                        for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
                            var signature = signatures_1[_i];
                            var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context);
                            methodDeclaration.name = propertyName;
                            methodDeclaration.questionToken = optionalToken;
                            if (propertySymbol.valueDeclaration) {
                                // Copy comments to node for declaration emit
                                ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration);
                            }
                            typeElements.push(methodDeclaration);
                        }
                    }
                    else {
                        var savedFlags = context.flags;
                        context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0;
                        var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */);
                        context.flags = savedFlags;
                        var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined;
                        if (modifiers) {
                            context.approximateLength += 9;
                        }
                        var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, 
                        /*initializer*/ undefined);
                        if (propertySymbol.valueDeclaration) {
                            // Copy comments to node for declaration emit
                            ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration);
                        }
                        typeElements.push(propertySignature);
                    }
                }
                function mapToTypeNodes(types, context, isBareList) {
                    if (ts.some(types)) {
                        if (checkTruncationLength(context)) {
                            if (!isBareList) {
                                return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
                            }
                            else if (types.length > 2) {
                                return [
                                    typeToTypeNodeHelper(types[0], context),
                                    ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
                                    typeToTypeNodeHelper(types[types.length - 1], context)
                                ];
                            }
                        }
                        var result = [];
                        var i = 0;
                        for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
                            var type = types_1[_i];
                            i++;
                            if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
                                result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
                                var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
                                if (typeNode_1) {
                                    result.push(typeNode_1);
                                }
                                break;
                            }
                            context.approximateLength += 2; // Account for whitespace + separator
                            var typeNode = typeToTypeNodeHelper(type, context);
                            if (typeNode) {
                                result.push(typeNode);
                            }
                        }
                        return result;
                    }
                }
                function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
                    var name = ts.getNameFromIndexInfo(indexInfo) || "x";
                    var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 137 /* StringKeyword */ : 134 /* NumberKeyword */);
                    var indexingParameter = ts.createParameter(
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, 
                    /*dotDotDotToken*/ undefined, name, 
                    /*questionToken*/ undefined, indexerTypeNode, 
                    /*initializer*/ undefined);
                    var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
                    if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
                        context.encounteredError = true;
                    }
                    context.approximateLength += (name.length + 4);
                    return ts.createIndexSignature(
                    /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
                }
                function signatureToSignatureDeclarationHelper(signature, kind, context) {
                    var typeParameters;
                    var typeArguments;
                    if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
                        typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
                    }
                    else {
                        typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
                    }
                    var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); });
                    if (signature.thisParameter) {
                        var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
                        parameters.unshift(thisParameter);
                    }
                    var returnTypeNode;
                    var typePredicate = getTypePredicateOfSignature(signature);
                    if (typePredicate) {
                        var parameterName = typePredicate.kind === 1 /* Identifier */ ?
                            ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
                            ts.createThisTypeNode();
                        var typeNode = typeToTypeNodeHelper(typePredicate.type, context);
                        returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode);
                    }
                    else {
                        var returnType = getReturnTypeOfSignature(signature);
                        returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context);
                    }
                    if (context.flags & 256 /* SuppressAnyReturnType */) {
                        if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) {
                            returnTypeNode = undefined;
                        }
                    }
                    else if (!returnTypeNode) {
                        returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */);
                    }
                    context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
                    return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
                }
                function typeParameterShadowsNameInScope(type, context) {
                    return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
                }
                function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
                    var savedContextFlags = context.flags;
                    context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
                    var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
                        type.symbol.declarations[0] &&
                        ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
                        typeParameterShadowsNameInScope(type, context);
                    var name = shouldUseGeneratedName
                        ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */)
                        : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true);
                    var defaultParameter = getDefaultFromTypeParameter(type);
                    var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
                    context.flags = savedContextFlags;
                    return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
                }
                function typeParameterToDeclaration(type, context, constraint) {
                    if (constraint === void 0) {
                        constraint = getConstraintOfTypeParameter(type);
                    }
                    var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
                    return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
                }
                function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
                    var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */);
                    if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
                        parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */);
                    }
                    var parameterType = getTypeOfSymbol(parameterSymbol);
                    if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
                        parameterType = getOptionalType(parameterType);
                    }
                    var parameterTypeNode = typeToTypeNodeHelper(parameterType, context);
                    var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
                    var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */;
                    var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined;
                    var name = parameterDeclaration
                        ? parameterDeclaration.name ?
                            parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
                                parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
                                    cloneBindingName(parameterDeclaration.name) :
                            ts.symbolName(parameterSymbol)
                        : ts.symbolName(parameterSymbol);
                    var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */;
                    var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined;
                    var parameterNode = ts.createParameter(
                    /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
                    /*initializer*/ undefined);
                    context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
                    return parameterNode;
                    function cloneBindingName(node) {
                        return elideInitializerAndSetEmitFlags(node);
                        function elideInitializerAndSetEmitFlags(node) {
                            if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
                                trackComputedName(node, context.enclosingDeclaration, context);
                            }
                            var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
                            var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
                            if (clone.kind === 184 /* BindingElement */) {
                                clone.initializer = undefined;
                            }
                            return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
                        }
                    }
                }
                function trackComputedName(node, enclosingDeclaration, context) {
                    if (!context.tracker.trackSymbol)
                        return;
                    // get symbol of the first identifier of the entityName
                    var firstIdentifier = getFirstIdentifier(node.expression);
                    var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
                    if (name) {
                        context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */);
                    }
                }
                function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
                    context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
                    // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
                    var chain;
                    var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
                    if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) {
                        chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
                        ts.Debug.assert(chain && chain.length > 0);
                    }
                    else {
                        chain = [symbol];
                    }
                    return chain;
                    /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
                    function getSymbolChain(symbol, meaning, endOfChain) {
                        var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
                        if (!accessibleSymbolChain ||
                            needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
                            // Go up and add our parent.
                            var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
                            if (ts.length(parents)) {
                                for (var _i = 0, _a = parents; _i < _a.length; _i++) {
                                    var parent = _a[_i];
                                    var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
                                    if (parentChain) {
                                        accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
                                        break;
                                    }
                                }
                            }
                        }
                        if (accessibleSymbolChain) {
                            return accessibleSymbolChain;
                        }
                        if (
                        // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
                        endOfChain ||
                            // If a parent symbol is an anonymous type, don't write it.
                            !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
                            // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
                            if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
                                return;
                            }
                            return [symbol];
                        }
                    }
                }
                function typeParametersToTypeParameterDeclarations(symbol, context) {
                    var typeParameterNodes;
                    var targetSymbol = getTargetSymbol(symbol);
                    if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
                        typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
                    }
                    return typeParameterNodes;
                }
                function lookupTypeParameterNodes(chain, index, context) {
                    ts.Debug.assert(chain && 0 <= index && index < chain.length);
                    var symbol = chain[index];
                    var typeParameterNodes;
                    if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
                        var parentSymbol = symbol;
                        var nextSymbol = chain[index + 1];
                        if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) {
                            var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
                            typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context);
                        }
                        else {
                            typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
                        }
                    }
                    return typeParameterNodes;
                }
                /**
                 * Given A[B][C][D], finds A[B]
                 */
                function getTopmostIndexedAccessType(top) {
                    if (ts.isIndexedAccessTypeNode(top.objectType)) {
                        return getTopmostIndexedAccessType(top.objectType);
                    }
                    return top;
                }
                function getSpecifierForModuleSymbol(symbol, context) {
                    var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */);
                    if (file && file.moduleName !== undefined) {
                        // Use the amd name if it is available
                        return file.moduleName;
                    }
                    if (!file) {
                        if (context.tracker.trackReferencedAmbientModule) {
                            var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
                            if (ts.length(ambientDecls)) {
                                for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
                                    var decl = ambientDecls_1[_i];
                                    context.tracker.trackReferencedAmbientModule(decl, symbol);
                                }
                            }
                        }
                        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
                            return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
                        }
                    }
                    if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
                        // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
                        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
                            return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
                        }
                        return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full
                    }
                    var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
                    var links = getSymbolLinks(symbol);
                    var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
                    if (!specifier) {
                        var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
                        // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
                        // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
                        // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
                        // specifier preference
                        var moduleResolverHost = context.tracker.moduleResolverHost;
                        var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
                        specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap));
                        links.specifierCache = links.specifierCache || ts.createMap();
                        links.specifierCache.set(contextFile.path, specifier);
                    }
                    return specifier;
                }
                function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
                    var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
                    var isTypeOf = meaning === 67220415 /* Value */;
                    if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
                        // module is root, must use `ImportTypeNode`
                        var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
                        var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
                        var specifier = getSpecifierForModuleSymbol(chain[0], context);
                        var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
                        if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
                            context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
                        context.approximateLength += specifier.length + 10; // specifier + import("")
                        if (!nonRootParts || ts.isEntityName(nonRootParts)) {
                            if (nonRootParts) {
                                var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
                                lastId.typeArguments = undefined;
                            }
                            return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
                        }
                        else {
                            var splitNode = getTopmostIndexedAccessType(nonRootParts);
                            var qualifier = splitNode.objectType.typeName;
                            return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
                        }
                    }
                    var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
                    if (ts.isIndexedAccessTypeNode(entityName)) {
                        return entityName; // Indexed accesses can never be `typeof`
                    }
                    if (isTypeOf) {
                        return ts.createTypeQueryNode(entityName);
                    }
                    else {
                        var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
                        var lastTypeArgs = lastId.typeArguments;
                        lastId.typeArguments = undefined;
                        return ts.createTypeReferenceNode(entityName, lastTypeArgs);
                    }
                    function createAccessFromSymbolChain(chain, index, stopper) {
                        var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
                        var symbol = chain[index];
                        if (index === 0) {
                            context.flags |= 16777216 /* InInitialEntityName */;
                        }
                        var symbolName = getNameOfSymbolAsWritten(symbol, context);
                        context.approximateLength += symbolName.length + 1;
                        if (index === 0) {
                            context.flags ^= 16777216 /* InInitialEntityName */;
                        }
                        var parent = chain[index - 1];
                        if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) {
                            // Should use an indexed access
                            var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
                            if (ts.isIndexedAccessTypeNode(LHS)) {
                                return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
                            }
                            else {
                                return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
                            }
                        }
                        var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
                        identifier.symbol = symbol;
                        if (index > stopper) {
                            var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
                            if (!ts.isEntityName(LHS)) {
                                return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
                            }
                            return ts.createQualifiedName(LHS, identifier);
                        }
                        return identifier;
                    }
                }
                function symbolToName(symbol, context, meaning, expectsIdentifier) {
                    var chain = lookupSymbolChain(symbol, context, meaning);
                    if (expectsIdentifier && chain.length !== 1
                        && !context.encounteredError
                        && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
                        context.encounteredError = true;
                    }
                    return createEntityNameFromSymbolChain(chain, chain.length - 1);
                    function createEntityNameFromSymbolChain(chain, index) {
                        var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
                        var symbol = chain[index];
                        if (index === 0) {
                            context.flags |= 16777216 /* InInitialEntityName */;
                        }
                        var symbolName = getNameOfSymbolAsWritten(symbol, context);
                        if (index === 0) {
                            context.flags ^= 16777216 /* InInitialEntityName */;
                        }
                        var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
                        identifier.symbol = symbol;
                        return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
                    }
                }
                function symbolToExpression(symbol, context, meaning) {
                    var chain = lookupSymbolChain(symbol, context, meaning);
                    return createExpressionFromSymbolChain(chain, chain.length - 1);
                    function createExpressionFromSymbolChain(chain, index) {
                        var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
                        var symbol = chain[index];
                        if (index === 0) {
                            context.flags |= 16777216 /* InInitialEntityName */;
                        }
                        var symbolName = getNameOfSymbolAsWritten(symbol, context);
                        if (index === 0) {
                            context.flags ^= 16777216 /* InInitialEntityName */;
                        }
                        var firstChar = symbolName.charCodeAt(0);
                        var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion);
                        if (index === 0 || canUsePropertyAccess) {
                            var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
                            identifier.symbol = symbol;
                            return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
                        }
                        else {
                            if (firstChar === 91 /* openBracket */) {
                                symbolName = symbolName.substring(1, symbolName.length - 1);
                                firstChar = symbolName.charCodeAt(0);
                            }
                            var expression = void 0;
                            if (ts.isSingleOrDoubleQuote(firstChar)) {
                                expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
                                expression.singleQuote = firstChar === 39 /* singleQuote */;
                            }
                            else if (("" + +symbolName) === symbolName) {
                                expression = ts.createLiteral(+symbolName);
                            }
                            if (!expression) {
                                expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
                                expression.symbol = symbol;
                            }
                            return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
                        }
                    }
                }
            }
            function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
                if (flags === void 0) {
                    flags = 16384 /* UseAliasDefinedOutsideCurrentScope */;
                }
                return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
                function typePredicateToStringWorker(writer) {
                    var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */));
                    var printer = ts.createPrinter({ removeComments: true });
                    var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
                    printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
                    return writer;
                }
            }
            function formatUnionTypes(types) {
                var result = [];
                var flags = 0;
                for (var i = 0; i < types.length; i++) {
                    var t = types[i];
                    flags |= t.flags;
                    if (!(t.flags & 24576 /* Nullable */)) {
                        if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) {
                            var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
                            if (baseType.flags & 262144 /* Union */) {
                                var count = baseType.types.length;
                                if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
                                    result.push(baseType);
                                    i += count - 1;
                                    continue;
                                }
                            }
                        }
                        result.push(t);
                    }
                }
                if (flags & 16384 /* Null */)
                    result.push(nullType);
                if (flags & 8192 /* Undefined */)
                    result.push(undefinedType);
                return result || types;
            }
            function visibilityToString(flags) {
                if (flags === 8 /* Private */) {
                    return "private";
                }
                if (flags === 16 /* Protected */) {
                    return "protected";
                }
                return "public";
            }
            function getTypeAliasForTypeLiteral(type) {
                if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
                    var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; });
                    if (node.kind === 240 /* TypeAliasDeclaration */) {
                        return getSymbolOfNode(node);
                    }
                }
                return undefined;
            }
            function isTopLevelInExternalModuleAugmentation(node) {
                return node && node.parent &&
                    node.parent.kind === 243 /* ModuleBlock */ &&
                    ts.isExternalModuleAugmentation(node.parent.parent);
            }
            function isDefaultBindingContext(location) {
                return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location);
            }
            /**
             * Gets a human-readable name for a symbol.
             * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
             *
             * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
             * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
             */
            function getNameOfSymbolAsWritten(symbol, context) {
                if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
                    // If it's not the first part of an entity name, it must print as `default`
                    (!(context.flags & 16777216 /* InInitialEntityName */) ||
                        // if the symbol is synthesized, it will only be referenced externally it must print as `default`
                        !symbol.declarations ||
                        // if not in the same binding context (source file, module declaration), it must print as `default`
                        (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
                    return "default";
                }
                if (symbol.declarations && symbol.declarations.length) {
                    var declaration = symbol.declarations[0];
                    var name = ts.getNameOfDeclaration(declaration);
                    if (name) {
                        return ts.declarationNameToString(name);
                    }
                    if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) {
                        return ts.declarationNameToString(declaration.parent.name);
                    }
                    switch (declaration.kind) {
                        case 207 /* ClassExpression */:
                        case 194 /* FunctionExpression */:
                        case 195 /* ArrowFunction */:
                            if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
                                context.encounteredError = true;
                            }
                            return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
                    }
                }
                var nameType = symbol.nameType;
                if (nameType) {
                    if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) {
                        return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\"";
                    }
                    if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) {
                        return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
                    }
                }
                return ts.symbolName(symbol);
            }
            function isDeclarationVisible(node) {
                if (node) {
                    var links = getNodeLinks(node);
                    if (links.isVisible === undefined) {
                        links.isVisible = !!determineIfDeclarationIsVisible();
                    }
                    return links.isVisible;
                }
                return false;
                function determineIfDeclarationIsVisible() {
                    switch (node.kind) {
                        case 295 /* JSDocCallbackTag */:
                        case 302 /* JSDocTypedefTag */:
                            // Top-level jsdoc type aliases are considered exported
                            // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
                            return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
                        case 184 /* BindingElement */:
                            return isDeclarationVisible(node.parent.parent);
                        case 235 /* VariableDeclaration */:
                            if (ts.isBindingPattern(node.name) &&
                                !node.name.elements.length) {
                                // If the binding pattern is empty, this variable declaration is not visible
                                return false;
                            }
                        // falls through
                        case 242 /* ModuleDeclaration */:
                        case 238 /* ClassDeclaration */:
                        case 239 /* InterfaceDeclaration */:
                        case 240 /* TypeAliasDeclaration */:
                        case 237 /* FunctionDeclaration */:
                        case 241 /* EnumDeclaration */:
                        case 246 /* ImportEqualsDeclaration */:
                            // external module augmentation is always visible
                            if (ts.isExternalModuleAugmentation(node)) {
                                return true;
                            }
                            var parent = getDeclarationContainer(node);
                            // If the node is not exported or it is not ambient module element (except import declaration)
                            if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
                                !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
                                return isGlobalSourceFile(parent);
                            }
                            // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
                            return isDeclarationVisible(parent);
                        case 152 /* PropertyDeclaration */:
                        case 151 /* PropertySignature */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                        case 154 /* MethodDeclaration */:
                        case 153 /* MethodSignature */:
                            if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
                                // Private/protected properties/methods are not visible
                                return false;
                            }
                        // Public properties/methods are visible if its parents are visible, so:
                        // falls through
                        case 155 /* Constructor */:
                        case 159 /* ConstructSignature */:
                        case 158 /* CallSignature */:
                        case 160 /* IndexSignature */:
                        case 149 /* Parameter */:
                        case 243 /* ModuleBlock */:
                        case 163 /* FunctionType */:
                        case 164 /* ConstructorType */:
                        case 166 /* TypeLiteral */:
                        case 162 /* TypeReference */:
                        case 167 /* ArrayType */:
                        case 168 /* TupleType */:
                        case 171 /* UnionType */:
                        case 172 /* IntersectionType */:
                        case 175 /* ParenthesizedType */:
                            return isDeclarationVisible(node.parent);
                        // Default binding, import specifier and namespace import is visible
                        // only on demand so by default it is not visible
                        case 248 /* ImportClause */:
                        case 249 /* NamespaceImport */:
                        case 251 /* ImportSpecifier */:
                            return false;
                        // Type parameters are always visible
                        case 148 /* TypeParameter */:
                        // Source file and namespace export are always visible
                        case 277 /* SourceFile */:
                        case 245 /* NamespaceExportDeclaration */:
                            return true;
                        // Export assignments do not create name bindings outside the module
                        case 252 /* ExportAssignment */:
                            return false;
                        default:
                            return false;
                    }
                }
            }
            function collectLinkedAliases(node, setVisibility) {
                var exportSymbol;
                if (node.parent && node.parent.kind === 252 /* ExportAssignment */) {
                    exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
                }
                else if (node.parent.kind === 255 /* ExportSpecifier */) {
                    exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
                }
                var result;
                if (exportSymbol) {
                    buildVisibleNodeList(exportSymbol.declarations);
                }
                return result;
                function buildVisibleNodeList(declarations) {
                    ts.forEach(declarations, function (declaration) {
                        var resultNode = getAnyImportSyntax(declaration) || declaration;
                        if (setVisibility) {
                            getNodeLinks(declaration).isVisible = true;
                        }
                        else {
                            result = result || [];
                            ts.pushIfUnique(result, resultNode);
                        }
                        if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
                            // Add the referenced top container visible
                            var internalModuleReference = declaration.moduleReference;
                            var firstIdentifier = getFirstIdentifier(internalModuleReference);
                            var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
                            if (importSymbol) {
                                buildVisibleNodeList(importSymbol.declarations);
                            }
                        }
                    });
                }
            }
            /**
             * Push an entry on the type resolution stack. If an entry with the given target and the given property name
             * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
             * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
             * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
             * In order to see if the same query has already been done before, the target object and the propertyName both
             * must match the one passed in.
             *
             * @param target The symbol, type, or signature whose type is being queried
             * @param propertyName The property name that should be used to query the target for its type
             */
            function pushTypeResolution(target, propertyName) {
                var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
                if (resolutionCycleStartIndex >= 0) {
                    // A cycle was found
                    var length_2 = resolutionTargets.length;
                    for (var i = resolutionCycleStartIndex; i < length_2; i++) {
                        resolutionResults[i] = false;
                    }
                    return false;
                }
                resolutionTargets.push(target);
                resolutionResults.push(/*items*/ true);
                resolutionPropertyNames.push(propertyName);
                return true;
            }
            function findResolutionCycleStartIndex(target, propertyName) {
                for (var i = resolutionTargets.length - 1; i >= 0; i--) {
                    if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
                        return -1;
                    }
                    if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
                        return i;
                    }
                }
                return -1;
            }
            function hasType(target, propertyName) {
                switch (propertyName) {
                    case 0 /* Type */:
                        return !!getSymbolLinks(target).type;
                    case 5 /* EnumTagType */:
                        return !!(getNodeLinks(target).resolvedEnumType);
                    case 2 /* DeclaredType */:
                        return !!getSymbolLinks(target).declaredType;
                    case 1 /* ResolvedBaseConstructorType */:
                        return !!target.resolvedBaseConstructorType;
                    case 3 /* ResolvedReturnType */:
                        return !!target.resolvedReturnType;
                    case 4 /* ImmediateBaseConstraint */:
                        return !!target.immediateBaseConstraint;
                    case 6 /* JSDocTypeReference */:
                        return !!getSymbolLinks(target).resolvedJSDocType;
                }
                return ts.Debug.assertNever(propertyName);
            }
            // Pop an entry from the type resolution stack and return its associated result value. The result value will
            // be true if no circularities were detected, or false if a circularity was found.
            function popTypeResolution() {
                resolutionTargets.pop();
                resolutionPropertyNames.pop();
                return resolutionResults.pop();
            }
            function getDeclarationContainer(node) {
                return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
                    switch (node.kind) {
                        case 235 /* VariableDeclaration */:
                        case 236 /* VariableDeclarationList */:
                        case 251 /* ImportSpecifier */:
                        case 250 /* NamedImports */:
                        case 249 /* NamespaceImport */:
                        case 248 /* ImportClause */:
                            return false;
                        default:
                            return true;
                    }
                }).parent;
            }
            function getTypeOfPrototypeProperty(prototype) {
                // TypeScript 1.0 spec (April 2014): 8.4
                // Every class automatically contains a static property member named 'prototype',
                // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
                // It is an error to explicitly declare a static property member with the name 'prototype'.
                var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
                return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
            }
            // Return the type of the given property in the given type, or undefined if no such property exists
            function getTypeOfPropertyOfType(type, name) {
                var prop = getPropertyOfType(type, name);
                return prop ? getTypeOfSymbol(prop) : undefined;
            }
            function isTypeAny(type) {
                return type && (type.flags & 1 /* Any */) !== 0;
            }
            // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
            // assigned by contextual typing.
            function getTypeForBindingElementParent(node) {
                var symbol = getSymbolOfNode(node);
                return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
            }
            function isComputedNonLiteralName(name) {
                return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression);
            }
            function getRestType(source, properties, symbol) {
                source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); });
                if (source.flags & 32768 /* Never */) {
                    return emptyObjectType;
                }
                if (source.flags & 262144 /* Union */) {
                    return mapType(source, function (t) { return getRestType(t, properties, symbol); });
                }
                var members = ts.createSymbolTable();
                var names = ts.createUnderscoreEscapedMap();
                for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) {
                    var name = properties_2[_i];
                    names.set(ts.getTextOfPropertyName(name), true);
                }
                for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) {
                    var prop = _b[_a];
                    if (!names.has(prop.escapedName)
                        && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
                        && isSpreadableProperty(prop)) {
                        members.set(prop.escapedName, getNonReadonlySymbol(prop));
                    }
                }
                var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
                var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
                return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
            }
            /** Return the inferred type for a binding element */
            function getTypeForBindingElement(declaration) {
                var pattern = declaration.parent;
                var parentType = getTypeForBindingElementParent(pattern.parent);
                // If parent has the unknown (error) type, then so does this binding element
                if (parentType === errorType) {
                    return errorType;
                }
                // If no type was specified or inferred for parent,
                // infer from the initializer of the binding element if one is present.
                // Otherwise, go with the undefined type of the parent.
                if (!parentType) {
                    return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
                }
                if (isTypeAny(parentType)) {
                    return parentType;
                }
                var type;
                if (pattern.kind === 182 /* ObjectBindingPattern */) {
                    if (declaration.dotDotDotToken) {
                        if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
                            error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
                            return errorType;
                        }
                        var literalMembers = [];
                        for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
                            var element = _a[_i];
                            if (!element.dotDotDotToken) {
                                literalMembers.push(element.propertyName || element.name);
                            }
                        }
                        type = getRestType(parentType, literalMembers, declaration.symbol);
                    }
                    else {
                        // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
                        var name = declaration.propertyName || declaration.name;
                        var isLate = isLateBindableName(name);
                        var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression);
                        if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) {
                            var exprType = checkExpression(name.expression);
                            if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) {
                                if (noImplicitAny) {
                                    error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType));
                                }
                                return anyType;
                            }
                            var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */);
                            if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
                                if (getIndexTypeOfType(parentType, 1 /* Number */)) {
                                    error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
                                }
                                else {
                                    error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType));
                                }
                            }
                            return indexerType || anyType;
                        }
                        // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
                        // or otherwise the type of the string index signature.
                        var nameType = isLate ? checkComputedPropertyName(name) : undefined;
                        var text = isLate ? getLateBoundNameFromType(nameType) :
                            isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) :
                                ts.getTextOfPropertyName(name);
                        // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
                        if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
                            parentType = getNonNullableType(parentType);
                        }
                        if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) {
                            if (noImplicitAny) {
                                error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType));
                            }
                            return anyType;
                        }
                        var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name);
                        type = declaredType && getFlowTypeOfReference(declaration, declaredType) ||
                            isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
                            getIndexTypeOfType(parentType, 0 /* String */);
                        if (!type) {
                            error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name));
                            return errorType;
                        }
                    }
                }
                else {
                    // This elementType will be used if the specific property corresponding to this index is not
                    // present (aka the tuple element property). This call also checks that the parentType is in
                    // fact an iterable or array (depending on target language).
                    var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false);
                    var index = pattern.elements.indexOf(declaration);
                    if (declaration.dotDotDotToken) {
                        // If the parent is a tuple type, the rest element has an array type with a union of the
                        // remaining tuple element types. Otherwise, the rest element has an array type with same
                        // element type as the parent type.
                        type = isTupleType(parentType) ?
                            getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) :
                            createArrayType(elementType);
                    }
                    else {
                        // Use specific property type when parent is a tuple or numeric index type when parent is an array
                        var index_1 = pattern.elements.indexOf(declaration);
                        type = isTupleLikeType(parentType) ?
                            getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) :
                            elementType;
                        if (!type) {
                            if (isTupleType(parentType)) {
                                error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length);
                            }
                            else {
                                error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1);
                            }
                            return errorType;
                        }
                    }
                }
                // In strict null checking mode, if a default value of a non-undefined type is specified, remove
                // undefined from the final type.
                if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) {
                    type = getTypeWithFacts(type, 131072 /* NEUndefined */);
                }
                return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ?
                    getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) :
                    type;
            }
            function getTypeForDeclarationFromJSDocComment(declaration) {
                var jsdocType = ts.getJSDocType(declaration);
                if (jsdocType) {
                    return getTypeFromTypeNode(jsdocType);
                }
                return undefined;
            }
            function isNullOrUndefined(node) {
                var expr = ts.skipParentheses(node);
                return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
            }
            function isEmptyArrayLiteral(node) {
                var expr = ts.skipParentheses(node);
                return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0;
            }
            function addOptionality(type, optional) {
                if (optional === void 0) {
                    optional = true;
                }
                return strictNullChecks && optional ? getOptionalType(type) : type;
            }
            // Return the inferred type for a variable, parameter, or property declaration
            function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
                // A variable declared in a for..in statement is of type string, or of type keyof T when the
                // right hand expression is of a type parameter type.
                if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) {
                    var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression));
                    return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType;
                }
                if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) {
                    // checkRightHandSideOfForOf will return undefined if the for-of expression type was
                    // missing properties/signatures required to get its iteratedType (like
                    // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
                    // or it may have led to an error inside getElementTypeOfIterable.
                    var forOfStatement = declaration.parent.parent;
                    return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType;
                }
                if (ts.isBindingPattern(declaration.parent)) {
                    return getTypeForBindingElement(declaration);
                }
                var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
                    || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
                // Use type from type annotation if one is present
                var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
                if (declaredType) {
                    return addOptionality(declaredType, isOptional);
                }
                if ((noImplicitAny || ts.isInJSFile(declaration)) &&
                    declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
                    !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) {
                    // If --noImplicitAny is on or the declaration is in a Javascript file,
                    // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
                    // initializer or a 'null' or 'undefined' initializer.
                    if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
                        return autoType;
                    }
                    // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
                    // literal initializer.
                    if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
                        return autoArrayType;
                    }
                }
                if (declaration.kind === 149 /* Parameter */) {
                    var func = declaration.parent;
                    // For a parameter of a set accessor, use the type of the get accessor if one is present
                    if (func.kind === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
                        var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */);
                        if (getter) {
                            var getterSignature = getSignatureFromDeclaration(getter);
                            var thisParameter = getAccessorThisParameter(func);
                            if (thisParameter && declaration === thisParameter) {
                                // Use the type from the *getter*
                                ts.Debug.assert(!thisParameter.type);
                                return getTypeOfSymbol(getterSignature.thisParameter);
                            }
                            return getReturnTypeOfSignature(getterSignature);
                        }
                    }
                    if (ts.isInJSFile(declaration)) {
                        var typeTag = ts.getJSDocType(func);
                        if (typeTag && ts.isFunctionTypeNode(typeTag)) {
                            return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
                        }
                    }
                    // Use contextual parameter type if one is available
                    var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
                    if (type) {
                        return addOptionality(type, isOptional);
                    }
                }
                else if (ts.isInJSFile(declaration)) {
                    var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
                    if (containerObjectType) {
                        return containerObjectType;
                    }
                }
                // Use the type of the initializer expression if one is present
                if (declaration.initializer) {
                    var type = checkDeclarationInitializer(declaration);
                    return addOptionality(type, isOptional);
                }
                if (ts.isJsxAttribute(declaration)) {
                    // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
                    // I.e <Elem attr /> is sugar for <Elem attr={true} />
                    return trueType;
                }
                // If the declaration specifies a binding pattern, use the type implied by the binding pattern
                if (ts.isBindingPattern(declaration.name)) {
                    return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
                }
                // No type specified and nothing can be inferred
                return undefined;
            }
            function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) {
                // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
                var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
                if (container) {
                    var tag = ts.getJSDocTypeTag(container);
                    if (tag && tag.typeExpression) {
                        return getTypeFromTypeNode(tag.typeExpression);
                    }
                    var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
                    return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
                }
                var definedInConstructor = false;
                var definedInMethod = false;
                var jsdocType;
                var types;
                for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                    var declaration = _a[_i];
                    var expression = ts.isBinaryExpression(declaration) ? declaration :
                        ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
                            undefined;
                    if (!expression) {
                        return errorType;
                    }
                    var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression);
                    if (kind === 4 /* ThisProperty */) {
                        if (isDeclarationInConstructor(expression)) {
                            definedInConstructor = true;
                        }
                        else {
                            definedInMethod = true;
                        }
                    }
                    jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration);
                    if (!jsdocType) {
                        (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
                    }
                }
                var type = jsdocType;
                if (!type) {
                    var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
                    // use only the constructor types unless they were only assigned null | undefined (including widening variants)
                    if (definedInMethod) {
                        var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
                        if (propType) {
                            (constructorTypes || (constructorTypes = [])).push(propType);
                            definedInConstructor = true;
                        }
                    }
                    var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217
                    type = getUnionType(sourceTypes, 2 /* Subtype */);
                }
                var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
                if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) {
                    if (noImplicitAny) {
                        reportImplicitAnyError(symbol.valueDeclaration, anyType);
                    }
                    return anyType;
                }
                return widened;
            }
            function getJSContainerObjectType(decl, symbol, init) {
                if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
                    return undefined;
                }
                var exports = ts.createSymbolTable();
                while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
                    var s_1 = getSymbolOfNode(decl);
                    if (s_1 && ts.hasEntries(s_1.exports)) {
                        mergeSymbolTable(exports, s_1.exports);
                    }
                    decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
                }
                var s = getSymbolOfNode(decl);
                if (s && ts.hasEntries(s.exports)) {
                    mergeSymbolTable(exports, s.exports);
                }
                var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
                type.objectFlags |= 16384 /* JSLiteral */;
                return type;
            }
            function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) {
                var typeNode = ts.getJSDocType(expression.parent);
                if (typeNode) {
                    var type = getWidenedType(getTypeFromTypeNode(typeNode));
                    if (!declaredType) {
                        return type;
                    }
                    else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
                        errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type);
                    }
                }
                return declaredType;
            }
            /** If we don't have an explicit JSDoc type, get the type from the initializer. */
            function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
                var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
                if (type.flags & 131072 /* Object */ &&
                    kind === 2 /* ModuleExports */ &&
                    symbol.escapedName === "export=" /* ExportEquals */) {
                    var exportedType_1 = resolveStructuredTypeMembers(type);
                    var members_3 = ts.createSymbolTable();
                    ts.copyEntries(exportedType_1.members, members_3);
                    if (resolvedSymbol && !resolvedSymbol.exports) {
                        resolvedSymbol.exports = ts.createSymbolTable();
                    }
                    (resolvedSymbol || symbol).exports.forEach(function (s, name) {
                        if (members_3.has(name)) {
                            var exportedMember = exportedType_1.members.get(name);
                            var union = createSymbol(s.flags | exportedMember.flags, name);
                            union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
                            members_3.set(name, union);
                        }
                        else {
                            members_3.set(name, s);
                        }
                    });
                    var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo);
                    result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
                    return result;
                }
                if (isEmptyArrayLiteralType(type)) {
                    if (noImplicitAny) {
                        reportImplicitAnyError(expression, anyArrayType);
                    }
                    return anyArrayType;
                }
                return type;
            }
            function isDeclarationInConstructor(expression) {
                var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
                // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
                // Function expressions that are assigned to the prototype count as methods.
                return thisContainer.kind === 155 /* Constructor */ ||
                    thisContainer.kind === 237 /* FunctionDeclaration */ ||
                    (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
            }
            function getConstructorDefinedThisAssignmentTypes(types, declarations) {
                ts.Debug.assert(types.length === declarations.length);
                return types.filter(function (_, i) {
                    var declaration = declarations[i];
                    var expression = ts.isBinaryExpression(declaration) ? declaration :
                        ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
                    return expression && isDeclarationInConstructor(expression);
                });
            }
            /** check for definition in base class if any declaration is in a class */
            function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
                var parentDeclaration = ts.forEach(property.declarations, function (d) {
                    var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
                    return ts.isClassLike(parent) && parent;
                });
                if (parentDeclaration) {
                    var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
                    var baseClassType = classType && getBaseTypes(classType)[0];
                    if (baseClassType) {
                        return getTypeOfPropertyOfType(baseClassType, property.escapedName);
                    }
                }
            }
            // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
            // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
            // pattern. Otherwise, it is the type any.
            function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
                if (element.initializer) {
                    return addOptionality(checkDeclarationInitializer(element));
                }
                if (ts.isBindingPattern(element.name)) {
                    return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
                }
                if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) {
                    reportImplicitAnyError(element, anyType);
                }
                return anyType;
            }
            // Return the type implied by an object binding pattern
            function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
                var members = ts.createSymbolTable();
                var stringIndexInfo;
                var objectFlags = 128 /* ObjectLiteral */;
                ts.forEach(pattern.elements, function (e) {
                    var name = e.propertyName || e.name;
                    if (isComputedNonLiteralName(name)) {
                        // do not include computed properties in the implied type
                        objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
                        return;
                    }
                    if (e.dotDotDotToken) {
                        stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
                        return;
                    }
                    var text = ts.getTextOfPropertyName(name);
                    var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
                    var symbol = createSymbol(flags, text);
                    symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
                    symbol.bindingElement = e;
                    members.set(symbol.escapedName, symbol);
                });
                var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
                result.flags |= 268435456 /* ContainsObjectLiteral */;
                result.objectFlags |= objectFlags;
                if (includePatternInType) {
                    result.pattern = pattern;
                }
                return result;
            }
            // Return the type implied by an array binding pattern
            function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
                var elements = pattern.elements;
                var lastElement = ts.lastOrUndefined(elements);
                var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken);
                if (elements.length === 0 || elements.length === 1 && hasRestElement) {
                    return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
                }
                var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
                var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
                var result = createTupleType(elementTypes, minLength, hasRestElement);
                if (includePatternInType) {
                    result = cloneTypeReference(result);
                    result.pattern = pattern;
                }
                return result;
            }
            // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
            // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
            // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
            // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
            // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
            // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
            // the parameter.
            function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
                if (includePatternInType === void 0) {
                    includePatternInType = false;
                }
                if (reportErrors === void 0) {
                    reportErrors = false;
                }
                return pattern.kind === 182 /* ObjectBindingPattern */
                    ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
                    : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
            }
            // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
            // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
            // is a bit more involved. For example:
            //
            //   var [x, s = ""] = [1, "one"];
            //
            // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
            // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
            // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
            function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
                return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
            }
            function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
                if (type) {
                    if (reportErrors) {
                        reportErrorsFromWidening(declaration, type);
                    }
                    // always widen a 'unique symbol' type if the type was created for a different declaration.
                    if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
                        type = esSymbolType;
                    }
                    return getWidenedType(type);
                }
                // Rest parameters default to type any[], other parameters default to type any
                type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
                // Report implicit any errors unless this is a private property within an ambient declaration
                if (reportErrors && noImplicitAny) {
                    if (!declarationBelongsToPrivateAmbientMember(declaration)) {
                        reportImplicitAnyError(declaration, type);
                    }
                }
                return type;
            }
            function declarationBelongsToPrivateAmbientMember(declaration) {
                var root = ts.getRootDeclaration(declaration);
                var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root;
                return isPrivateWithinAmbient(memberDeclaration);
            }
            function tryGetTypeFromEffectiveTypeNode(declaration) {
                var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
                if (typeNode) {
                    return getTypeFromTypeNode(typeNode);
                }
            }
            function getTypeOfVariableOrParameterOrProperty(symbol) {
                var links = getSymbolLinks(symbol);
                return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
            }
            function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
                // Handle prototype property
                if (symbol.flags & 4194304 /* Prototype */) {
                    return getTypeOfPrototypeProperty(symbol);
                }
                // CommonsJS require and module both have type any.
                if (symbol === requireSymbol) {
                    return anyType;
                }
                if (symbol.flags & 134217728 /* ModuleExports */) {
                    var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
                    var members = ts.createSymbolTable();
                    members.set("exports", fileSymbol);
                    return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
                }
                // Handle catch clause variables
                var declaration = symbol.valueDeclaration;
                if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
                    return anyType;
                }
                // Handle export default expressions
                if (ts.isSourceFile(declaration)) {
                    var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile);
                    if (!jsonSourceFile.statements.length) {
                        return emptyObjectType;
                    }
                    var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression));
                    if (type_1.flags & 131072 /* Object */) {
                        return getRegularTypeOfObjectLiteral(type_1);
                    }
                    return type_1;
                }
                if (declaration.kind === 252 /* ExportAssignment */) {
                    return checkExpression(declaration.expression);
                }
                // Handle variable, parameter or property
                if (!pushTypeResolution(symbol, 0 /* Type */)) {
                    return errorType;
                }
                var type;
                if (ts.isInJSFile(declaration) &&
                    (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
                    type = getWidenedTypeFromAssignmentDeclaration(symbol);
                }
                else if (ts.isJSDocPropertyLikeTag(declaration)
                    || ts.isPropertyAccessExpression(declaration)
                    || ts.isIdentifier(declaration)
                    || ts.isClassDeclaration(declaration)
                    || ts.isFunctionDeclaration(declaration)
                    || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
                    || ts.isMethodSignature(declaration)) {
                    // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
                    if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
                        return getTypeOfFuncClassEnumModule(symbol);
                    }
                    type = ts.isBinaryExpression(declaration.parent) ?
                        getWidenedTypeFromAssignmentDeclaration(symbol) :
                        tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
                }
                else if (ts.isPropertyAssignment(declaration)) {
                    type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
                }
                else if (ts.isJsxAttribute(declaration)) {
                    type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
                }
                else if (ts.isShorthandPropertyAssignment(declaration)) {
                    type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
                }
                else if (ts.isObjectLiteralMethod(declaration)) {
                    type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
                }
                else if (ts.isParameter(declaration)
                    || ts.isPropertyDeclaration(declaration)
                    || ts.isPropertySignature(declaration)
                    || ts.isVariableDeclaration(declaration)
                    || ts.isBindingElement(declaration)) {
                    type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
                }
                else {
                    return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol));
                }
                if (!popTypeResolution()) {
                    type = reportCircularityError(symbol);
                }
                return type;
            }
            function getAnnotatedAccessorTypeNode(accessor) {
                if (accessor) {
                    if (accessor.kind === 156 /* GetAccessor */) {
                        var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
                        return getterTypeAnnotation;
                    }
                    else {
                        var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
                        return setterTypeAnnotation;
                    }
                }
                return undefined;
            }
            function getAnnotatedAccessorType(accessor) {
                var node = getAnnotatedAccessorTypeNode(accessor);
                return node && getTypeFromTypeNode(node);
            }
            function getAnnotatedAccessorThisParameter(accessor) {
                var parameter = getAccessorThisParameter(accessor);
                return parameter && parameter.symbol;
            }
            function getThisTypeOfDeclaration(declaration) {
                return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
            }
            function getTypeOfAccessors(symbol) {
                var links = getSymbolLinks(symbol);
                return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
            }
            function getTypeOfAccessorsWorker(symbol) {
                var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */);
                var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */);
                if (getter && ts.isInJSFile(getter)) {
                    var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
                    if (jsDocType) {
                        return jsDocType;
                    }
                }
                if (!pushTypeResolution(symbol, 0 /* Type */)) {
                    return errorType;
                }
                var type;
                // First try to see if the user specified a return type on the get-accessor.
                var getterReturnType = getAnnotatedAccessorType(getter);
                if (getterReturnType) {
                    type = getterReturnType;
                }
                else {
                    // If the user didn't specify a return type, try to use the set-accessor's parameter type.
                    var setterParameterType = getAnnotatedAccessorType(setter);
                    if (setterParameterType) {
                        type = setterParameterType;
                    }
                    else {
                        // If there are no specified types, try to infer it from the body of the get accessor if it exists.
                        if (getter && getter.body) {
                            type = getReturnTypeFromBody(getter);
                        }
                        // Otherwise, fall back to 'any'.
                        else {
                            if (noImplicitAny) {
                                if (setter) {
                                    error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
                                }
                                else {
                                    ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function");
                                    error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
                                }
                            }
                            type = anyType;
                        }
                    }
                }
                if (!popTypeResolution()) {
                    type = anyType;
                    if (noImplicitAny) {
                        var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */);
                        error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol));
                    }
                }
                return type;
            }
            function getBaseTypeVariableOfClass(symbol) {
                var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
                return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined;
            }
            function getTypeOfFuncClassEnumModule(symbol) {
                var links = getSymbolLinks(symbol);
                var originalLinks = links;
                if (!links.type) {
                    var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration);
                    if (jsDeclaration) {
                        var jsSymbol = getSymbolOfNode(jsDeclaration);
                        if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) {
                            symbol = cloneSymbol(symbol);
                            // note:we overwrite links because we just cloned the symbol
                            links = symbol;
                            if (ts.hasEntries(jsSymbol.exports)) {
                                symbol.exports = symbol.exports || ts.createSymbolTable();
                                mergeSymbolTable(symbol.exports, jsSymbol.exports);
                            }
                            if (ts.hasEntries(jsSymbol.members)) {
                                symbol.members = symbol.members || ts.createSymbolTable();
                                mergeSymbolTable(symbol.members, jsSymbol.members);
                            }
                        }
                    }
                    originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
                }
                return links.type;
            }
            function getTypeOfFuncClassEnumModuleWorker(symbol) {
                var declaration = symbol.valueDeclaration;
                if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
                    return anyType;
                }
                else if (declaration.kind === 202 /* BinaryExpression */ ||
                    declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) {
                    return getWidenedTypeFromAssignmentDeclaration(symbol);
                }
                else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
                    var resolvedModule = resolveExternalModuleSymbol(symbol);
                    if (resolvedModule !== symbol) {
                        if (!pushTypeResolution(symbol, 0 /* Type */)) {
                            return errorType;
                        }
                        var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
                        var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
                        if (!popTypeResolution()) {
                            return reportCircularityError(symbol);
                        }
                        return type_2;
                    }
                }
                var type = createObjectType(16 /* Anonymous */, symbol);
                if (symbol.flags & 32 /* Class */) {
                    var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
                    return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
                }
                else {
                    return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
                }
            }
            function getTypeOfEnumMember(symbol) {
                var links = getSymbolLinks(symbol);
                return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
            }
            function getTypeOfAlias(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.type) {
                    var targetSymbol = resolveAlias(symbol);
                    // It only makes sense to get the type of a value symbol. If the result of resolving
                    // the alias is not a value, then it has no type. To get the type associated with a
                    // type symbol, call getDeclaredTypeOfSymbol.
                    // This check is important because without it, a call to getTypeOfSymbol could end
                    // up recursively calling getTypeOfAlias, causing a stack overflow.
                    links.type = targetSymbol.flags & 67220415 /* Value */
                        ? getTypeOfSymbol(targetSymbol)
                        : errorType;
                }
                return links.type;
            }
            function getTypeOfInstantiatedSymbol(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.type) {
                    if (!pushTypeResolution(symbol, 0 /* Type */)) {
                        return links.type = errorType;
                    }
                    var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
                    if (!popTypeResolution()) {
                        type = reportCircularityError(symbol);
                    }
                    links.type = type;
                }
                return links.type;
            }
            function reportCircularityError(symbol) {
                // Check if variable has type annotation that circularly references the variable itself
                if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
                    error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
                    return errorType;
                }
                // Otherwise variable has initializer that circularly references the variable itself
                if (noImplicitAny) {
                    error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
                }
                return anyType;
            }
            function getTypeOfSymbol(symbol) {
                if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
                    return getTypeOfInstantiatedSymbol(symbol);
                }
                if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) {
                    return getTypeOfReverseMappedSymbol(symbol);
                }
                if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
                    return getTypeOfVariableOrParameterOrProperty(symbol);
                }
                if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
                    return getTypeOfFuncClassEnumModule(symbol);
                }
                if (symbol.flags & 8 /* EnumMember */) {
                    return getTypeOfEnumMember(symbol);
                }
                if (symbol.flags & 98304 /* Accessor */) {
                    return getTypeOfAccessors(symbol);
                }
                if (symbol.flags & 2097152 /* Alias */) {
                    return getTypeOfAlias(symbol);
                }
                return errorType;
            }
            function isReferenceToType(type, target) {
                return type !== undefined
                    && target !== undefined
                    && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
                    && type.target === target;
            }
            function getTargetType(type) {
                return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
            }
            // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
            function hasBaseType(type, checkBase) {
                return check(type);
                function check(type) {
                    if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
                        var target = getTargetType(type);
                        return target === checkBase || ts.some(getBaseTypes(target), check);
                    }
                    else if (type.flags & 524288 /* Intersection */) {
                        return ts.some(type.types, check);
                    }
                    return false;
                }
            }
            // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
            // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
            // in-place and returns the same array.
            function appendTypeParameters(typeParameters, declarations) {
                for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
                    var declaration = declarations_2[_i];
                    typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
                }
                return typeParameters;
            }
            // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
            function getOuterTypeParameters(node, includeThisTypes) {
                while (true) {
                    node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
                    if (!node) {
                        return undefined;
                    }
                    switch (node.kind) {
                        case 238 /* ClassDeclaration */:
                        case 207 /* ClassExpression */:
                        case 239 /* InterfaceDeclaration */:
                        case 158 /* CallSignature */:
                        case 159 /* ConstructSignature */:
                        case 153 /* MethodSignature */:
                        case 163 /* FunctionType */:
                        case 164 /* ConstructorType */:
                        case 287 /* JSDocFunctionType */:
                        case 237 /* FunctionDeclaration */:
                        case 154 /* MethodDeclaration */:
                        case 194 /* FunctionExpression */:
                        case 195 /* ArrowFunction */:
                        case 240 /* TypeAliasDeclaration */:
                        case 301 /* JSDocTemplateTag */:
                        case 302 /* JSDocTypedefTag */:
                        case 295 /* JSDocCallbackTag */:
                        case 179 /* MappedType */:
                        case 173 /* ConditionalType */:
                            var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
                            if (node.kind === 179 /* MappedType */) {
                                return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
                            }
                            else if (node.kind === 173 /* ConditionalType */) {
                                return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
                            }
                            var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
                            var thisType = includeThisTypes &&
                                (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) &&
                                getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
                            return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
                    }
                }
            }
            // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
            function getOuterTypeParametersOfClassOrInterface(symbol) {
                var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */);
                return getOuterTypeParameters(declaration);
            }
            // The local type parameters are the combined set of type parameters from all declarations of the class,
            // interface, or type alias.
            function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
                var result;
                for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                    var node = _a[_i];
                    if (node.kind === 239 /* InterfaceDeclaration */ ||
                        node.kind === 238 /* ClassDeclaration */ ||
                        node.kind === 207 /* ClassExpression */ ||
                        ts.isTypeAlias(node)) {
                        var declaration = node;
                        result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
                    }
                }
                return result;
            }
            // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
            // its locally declared type parameters.
            function getTypeParametersOfClassOrInterface(symbol) {
                return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
            }
            // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
            // rest parameter of type any[].
            function isMixinConstructorType(type) {
                var signatures = getSignaturesOfType(type, 1 /* Construct */);
                if (signatures.length === 1) {
                    var s = signatures[0];
                    return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType;
                }
                return false;
            }
            function isConstructorType(type) {
                if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) {
                    return true;
                }
                if (type.flags & 2162688 /* TypeVariable */) {
                    var constraint = getBaseConstraintOfType(type);
                    return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint);
                }
                return isJSConstructorType(type);
            }
            function getBaseTypeNodeOfClass(type) {
                return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
            }
            function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
                var typeArgCount = ts.length(typeArgumentNodes);
                var isJavascript = ts.isInJSFile(location);
                if (isJSConstructorType(type) && !typeArgCount) {
                    return getSignaturesOfType(type, 0 /* Call */);
                }
                return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
            }
            function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
                var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
                var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
                return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
            }
            /**
             * The base constructor of a class can resolve to
             * * undefinedType if the class has no extends clause,
             * * unknownType if an error occurred during resolution of the extends expression,
             * * nullType if the extends expression is the null value,
             * * anyType if the extends expression has type any, or
             * * an object type with at least one construct signature.
             */
            function getBaseConstructorTypeOfClass(type) {
                if (!type.resolvedBaseConstructorType) {
                    var decl = type.symbol.valueDeclaration;
                    var extended = ts.getEffectiveBaseTypeNode(decl);
                    var baseTypeNode = getBaseTypeNodeOfClass(type);
                    if (!baseTypeNode) {
                        return type.resolvedBaseConstructorType = undefinedType;
                    }
                    if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
                        return errorType;
                    }
                    var baseConstructorType = checkExpression(baseTypeNode.expression);
                    if (extended && baseTypeNode !== extended) {
                        ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
                        checkExpression(extended.expression);
                    }
                    if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) {
                        // Resolving the members of a class requires us to resolve the base class of that class.
                        // We force resolution here such that we catch circularities now.
                        resolveStructuredTypeMembers(baseConstructorType);
                    }
                    if (!popTypeResolution()) {
                        error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
                        return type.resolvedBaseConstructorType = errorType;
                    }
                    if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
                        error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
                        return type.resolvedBaseConstructorType = errorType;
                    }
                    type.resolvedBaseConstructorType = baseConstructorType;
                }
                return type.resolvedBaseConstructorType;
            }
            function getBaseTypes(type) {
                if (!type.resolvedBaseTypes) {
                    if (type.objectFlags & 8 /* Tuple */) {
                        type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
                    }
                    else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
                        if (type.symbol.flags & 32 /* Class */) {
                            resolveBaseTypesOfClass(type);
                        }
                        if (type.symbol.flags & 64 /* Interface */) {
                            resolveBaseTypesOfInterface(type);
                        }
                    }
                    else {
                        ts.Debug.fail("type must be class or interface");
                    }
                }
                return type.resolvedBaseTypes;
            }
            function resolveBaseTypesOfClass(type) {
                type.resolvedBaseTypes = ts.resolvingEmptyArray;
                var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
                if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) {
                    return type.resolvedBaseTypes = ts.emptyArray;
                }
                var baseTypeNode = getBaseTypeNodeOfClass(type);
                var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode);
                var baseType;
                var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
                if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
                    areAllOuterTypeParametersApplied(originalBaseType)) {
                    // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the
                    // class and all return the instance type of the class. There is no need for further checks and we can apply the
                    // type arguments in the same manner as a type reference to get the same error reporting experience.
                    baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs);
                }
                else if (baseConstructorType.flags & 1 /* Any */) {
                    baseType = baseConstructorType;
                }
                else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) {
                    baseType = getJSClassType(baseConstructorType.symbol) || anyType;
                }
                else {
                    // The class derives from a "class-like" constructor function, check that we have at least one construct signature
                    // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
                    // we check that all instantiated signatures return the same type.
                    var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
                    if (!constructors.length) {
                        error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
                        return type.resolvedBaseTypes = ts.emptyArray;
                    }
                    baseType = getReturnTypeOfSignature(constructors[0]);
                }
                if (baseType === errorType) {
                    return type.resolvedBaseTypes = ts.emptyArray;
                }
                if (!isValidBaseType(baseType)) {
                    error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
                    return type.resolvedBaseTypes = ts.emptyArray;
                }
                if (type === baseType || hasBaseType(baseType, type)) {
                    error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
                    return type.resolvedBaseTypes = ts.emptyArray;
                }
                if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
                    // Circular reference, likely through instantiation of default parameters
                    // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
                    // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
                    // partial instantiation of the members without the base types fully resolved
                    type.members = undefined;
                }
                return type.resolvedBaseTypes = [baseType];
            }
            function areAllOuterTypeParametersApplied(type) {
                // An unapplied type parameter has its symbol still the same as the matching argument symbol.
                // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
                var outerTypeParameters = type.outerTypeParameters;
                if (outerTypeParameters) {
                    var last_1 = outerTypeParameters.length - 1;
                    var typeArguments = type.typeArguments;
                    return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
                }
                return true;
            }
            // A valid base type is `any`, any non-generic object type or intersection of non-generic
            // object types.
            function isValidBaseType(type) {
                return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) ||
                    !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType);
            }
            function resolveBaseTypesOfInterface(type) {
                type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
                for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
                    var declaration = _a[_i];
                    if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
                        for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
                            var node = _c[_b];
                            var baseType = getTypeFromTypeNode(node);
                            if (baseType !== errorType) {
                                if (isValidBaseType(baseType)) {
                                    if (type !== baseType && !hasBaseType(baseType, type)) {
                                        if (type.resolvedBaseTypes === ts.emptyArray) {
                                            type.resolvedBaseTypes = [baseType];
                                        }
                                        else {
                                            type.resolvedBaseTypes.push(baseType);
                                        }
                                    }
                                    else {
                                        error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
                                    }
                                }
                                else {
                                    error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface);
                                }
                            }
                        }
                    }
                }
            }
            /**
             * Returns true if the interface given by the symbol is free of "this" references.
             *
             * Specifically, the result is true if the interface itself contains no references
             * to "this" in its body, if all base types are interfaces,
             * and if none of the base interfaces have a "this" type.
             */
            function isThislessInterface(symbol) {
                for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                    var declaration = _a[_i];
                    if (declaration.kind === 239 /* InterfaceDeclaration */) {
                        if (declaration.flags & 64 /* ContainsThis */) {
                            return false;
                        }
                        var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
                        if (baseTypeNodes) {
                            for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
                                var node = baseTypeNodes_1[_b];
                                if (ts.isEntityNameExpression(node.expression)) {
                                    var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true);
                                    if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
            function getDeclaredTypeOfClassOrInterface(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.declaredType) {
                    var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
                    var type = links.declaredType = createObjectType(kind, symbol);
                    var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
                    var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
                    // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
                    // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
                    // property types inferred from initializers and method return types inferred from return statements are very hard
                    // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
                    // "this" references.
                    if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
                        type.objectFlags |= 4 /* Reference */;
                        type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
                        type.outerTypeParameters = outerTypeParameters;
                        type.localTypeParameters = localTypeParameters;
                        type.instantiations = ts.createMap();
                        type.instantiations.set(getTypeListId(type.typeParameters), type);
                        type.target = type;
                        type.typeArguments = type.typeParameters;
                        type.thisType = createType(65536 /* TypeParameter */);
                        type.thisType.isThisType = true;
                        type.thisType.symbol = symbol;
                        type.thisType.constraint = type;
                    }
                }
                return links.declaredType;
            }
            function getDeclaredTypeOfTypeAlias(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.declaredType) {
                    // Note that we use the links object as the target here because the symbol object is used as the unique
                    // identity for resolution of the 'type' property in SymbolLinks.
                    if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
                        return errorType;
                    }
                    var declaration = ts.find(symbol.declarations, function (d) {
                        return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */;
                    });
                    var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
                    // If typeNode is missing, we will error in checkJSDocTypedefTag.
                    var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
                    if (popTypeResolution()) {
                        var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
                        if (typeParameters) {
                            // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
                            // an instantiation of the type alias with the type parameters supplied as type arguments.
                            links.typeParameters = typeParameters;
                            links.instantiations = ts.createMap();
                            links.instantiations.set(getTypeListId(typeParameters), type);
                        }
                    }
                    else {
                        type = errorType;
                        error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
                    }
                    links.declaredType = type;
                }
                return links.declaredType;
            }
            function isStringConcatExpression(expr) {
                if (expr.kind === 9 /* StringLiteral */) {
                    return true;
                }
                else if (expr.kind === 202 /* BinaryExpression */) {
                    return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
                }
                return false;
            }
            function isLiteralEnumMember(member) {
                var expr = member.initializer;
                if (!expr) {
                    return !(member.flags & 4194304 /* Ambient */);
                }
                switch (expr.kind) {
                    case 9 /* StringLiteral */:
                    case 8 /* NumericLiteral */:
                        return true;
                    case 200 /* PrefixUnaryExpression */:
                        return expr.operator === 38 /* MinusToken */ &&
                            expr.operand.kind === 8 /* NumericLiteral */;
                    case 71 /* Identifier */:
                        return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
                    case 202 /* BinaryExpression */:
                        return isStringConcatExpression(expr);
                    default:
                        return false;
                }
            }
            function getEnumKind(symbol) {
                var links = getSymbolLinks(symbol);
                if (links.enumKind !== undefined) {
                    return links.enumKind;
                }
                var hasNonLiteralMember = false;
                for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                    var declaration = _a[_i];
                    if (declaration.kind === 241 /* EnumDeclaration */) {
                        for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
                            var member = _c[_b];
                            if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) {
                                return links.enumKind = 1 /* Literal */;
                            }
                            if (!isLiteralEnumMember(member)) {
                                hasNonLiteralMember = true;
                            }
                        }
                    }
                }
                return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
            }
            function getBaseTypeOfEnumLiteralType(type) {
                return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
            }
            function getDeclaredTypeOfEnum(symbol) {
                var links = getSymbolLinks(symbol);
                if (links.declaredType) {
                    return links.declaredType;
                }
                if (getEnumKind(symbol) === 1 /* Literal */) {
                    enumCount++;
                    var memberTypeList = [];
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var declaration = _a[_i];
                        if (declaration.kind === 241 /* EnumDeclaration */) {
                            for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
                                var member = _c[_b];
                                var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217
                                getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
                                memberTypeList.push(getRegularTypeOfLiteralType(memberType));
                            }
                        }
                    }
                    if (memberTypeList.length) {
                        var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
                        if (enumType_1.flags & 262144 /* Union */) {
                            enumType_1.flags |= 512 /* EnumLiteral */;
                            enumType_1.symbol = symbol;
                        }
                        return links.declaredType = enumType_1;
                    }
                }
                var enumType = createType(32 /* Enum */);
                enumType.symbol = symbol;
                return links.declaredType = enumType;
            }
            function getDeclaredTypeOfEnumMember(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.declaredType) {
                    var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
                    if (!links.declaredType) {
                        links.declaredType = enumType;
                    }
                }
                return links.declaredType;
            }
            function getDeclaredTypeOfTypeParameter(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.declaredType) {
                    var type = createType(65536 /* TypeParameter */);
                    type.symbol = symbol;
                    links.declaredType = type;
                }
                return links.declaredType;
            }
            function getDeclaredTypeOfAlias(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.declaredType) {
                    links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol));
                }
                return links.declaredType;
            }
            function getDeclaredTypeOfSymbol(symbol) {
                return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
            }
            function tryGetDeclaredTypeOfSymbol(symbol) {
                if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
                    return getDeclaredTypeOfClassOrInterface(symbol);
                }
                if (symbol.flags & 524288 /* TypeAlias */) {
                    return getDeclaredTypeOfTypeAlias(symbol);
                }
                if (symbol.flags & 262144 /* TypeParameter */) {
                    return getDeclaredTypeOfTypeParameter(symbol);
                }
                if (symbol.flags & 384 /* Enum */) {
                    return getDeclaredTypeOfEnum(symbol);
                }
                if (symbol.flags & 8 /* EnumMember */) {
                    return getDeclaredTypeOfEnumMember(symbol);
                }
                if (symbol.flags & 2097152 /* Alias */) {
                    return getDeclaredTypeOfAlias(symbol);
                }
                return undefined;
            }
            /**
             * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
             * literal type, an array with an element type that is free of this references, or a type reference that is
             * free of this references.
             */
            function isThislessType(node) {
                switch (node.kind) {
                    case 119 /* AnyKeyword */:
                    case 142 /* UnknownKeyword */:
                    case 137 /* StringKeyword */:
                    case 134 /* NumberKeyword */:
                    case 122 /* BooleanKeyword */:
                    case 138 /* SymbolKeyword */:
                    case 135 /* ObjectKeyword */:
                    case 105 /* VoidKeyword */:
                    case 140 /* UndefinedKeyword */:
                    case 95 /* NullKeyword */:
                    case 131 /* NeverKeyword */:
                    case 180 /* LiteralType */:
                        return true;
                    case 167 /* ArrayType */:
                        return isThislessType(node.elementType);
                    case 162 /* TypeReference */:
                        return !node.typeArguments || node.typeArguments.every(isThislessType);
                }
                return false;
            }
            /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */
            function isThislessTypeParameter(node) {
                var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
                return !constraint || isThislessType(constraint);
            }
            /**
             * A variable-like declaration is free of this references if it has a type annotation
             * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
             */
            function isThislessVariableLikeDeclaration(node) {
                var typeNode = ts.getEffectiveTypeAnnotationNode(node);
                return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
            }
            /**
             * A function-like declaration is considered free of `this` references if it has a return type
             * annotation that is free of this references and if each parameter is thisless and if
             * each type parameter (if present) is thisless.
             */
            function isThislessFunctionLikeDeclaration(node) {
                var returnType = ts.getEffectiveReturnTypeNode(node);
                var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
                return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
                    node.parameters.every(isThislessVariableLikeDeclaration) &&
                    typeParameters.every(isThislessTypeParameter);
            }
            /**
             * Returns true if the class or interface member given by the symbol is free of "this" references. The
             * function may return false for symbols that are actually free of "this" references because it is not
             * feasible to perform a complete analysis in all cases. In particular, property members with types
             * inferred from their initializers and function members with inferred return types are conservatively
             * assumed not to be free of "this" references.
             */
            function isThisless(symbol) {
                if (symbol.declarations && symbol.declarations.length === 1) {
                    var declaration = symbol.declarations[0];
                    if (declaration) {
                        switch (declaration.kind) {
                            case 152 /* PropertyDeclaration */:
                            case 151 /* PropertySignature */:
                                return isThislessVariableLikeDeclaration(declaration);
                            case 154 /* MethodDeclaration */:
                            case 153 /* MethodSignature */:
                            case 155 /* Constructor */:
                                return isThislessFunctionLikeDeclaration(declaration);
                        }
                    }
                }
                return false;
            }
            // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
            // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
            function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
                var result = ts.createSymbolTable();
                for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
                    var symbol = symbols_2[_i];
                    result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
                }
                return result;
            }
            function addInheritedMembers(symbols, baseSymbols) {
                for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
                    var s = baseSymbols_1[_i];
                    if (!symbols.has(s.escapedName)) {
                        symbols.set(s.escapedName, s);
                    }
                }
            }
            function resolveDeclaredMembers(type) {
                if (!type.declaredProperties) {
                    var symbol = type.symbol;
                    var members = getMembersOfSymbol(symbol);
                    type.declaredProperties = getNamedMembers(members);
                    // Start with signatures at empty array in case of recursive types
                    type.declaredCallSignatures = ts.emptyArray;
                    type.declaredConstructSignatures = ts.emptyArray;
                    type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
                    type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
                    type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
                    type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
                }
                return type;
            }
            /**
             * Indicates whether a type can be used as a late-bound name.
             */
            function isTypeUsableAsLateBoundName(type) {
                return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */);
            }
            /**
             * Indicates whether a declaration name is definitely late-bindable.
             * A declaration name is only late-bindable if:
             * - It is a `ComputedPropertyName`.
             * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
             * `ElementAccessExpression` consisting only of these same three types of nodes.
             * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
             */
            function isLateBindableName(node) {
                return ts.isComputedPropertyName(node)
                    && ts.isEntityNameExpression(node.expression)
                    && isTypeUsableAsLateBoundName(checkComputedPropertyName(node));
            }
            function isLateBoundName(name) {
                return name.charCodeAt(0) === 95 /* _ */ &&
                    name.charCodeAt(1) === 95 /* _ */ &&
                    name.charCodeAt(2) === 64 /* at */;
            }
            /**
             * Indicates whether a declaration has a late-bindable dynamic name.
             */
            function hasLateBindableName(node) {
                var name = ts.getNameOfDeclaration(node);
                return !!name && isLateBindableName(name);
            }
            /**
             * Indicates whether a declaration has a dynamic name that cannot be late-bound.
             */
            function hasNonBindableDynamicName(node) {
                return ts.hasDynamicName(node) && !hasLateBindableName(node);
            }
            /**
             * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
             */
            function isNonBindableDynamicName(node) {
                return ts.isDynamicName(node) && !isLateBindableName(node);
            }
            /**
             * Gets the symbolic name for a late-bound member from its type.
             */
            function getLateBoundNameFromType(type) {
                if (type.flags & 2048 /* UniqueESSymbol */) {
                    return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
                }
                if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) {
                    return ts.escapeLeadingUnderscores("" + type.value);
                }
                return ts.Debug.fail();
            }
            /**
             * Adds a declaration to a late-bound dynamic member. This performs the same function for
             * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
             * members.
             */
            function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
                ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol.");
                symbol.flags |= symbolFlags;
                getSymbolLinks(member.symbol).lateSymbol = symbol;
                if (!symbol.declarations) {
                    symbol.declarations = [member];
                }
                else {
                    symbol.declarations.push(member);
                }
                if (symbolFlags & 67220415 /* Value */) {
                    if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
                        symbol.valueDeclaration = member;
                    }
                }
            }
            /**
             * Performs late-binding of a dynamic member. This performs the same function for
             * late-bound members that `declareSymbol` in binder.ts performs for early-bound
             * members.
             *
             * If a symbol is a dynamic name from a computed property, we perform an additional "late"
             * binding phase to attempt to resolve the name for the symbol from the type of the computed
             * property's expression. If the type of the expression is a string-literal, numeric-literal,
             * or unique symbol type, we can use that type as the name of the symbol.
             *
             * For example, given:
             *
             *   const x = Symbol();
             *
             *   interface I {
             *     [x]: number;
             *   }
             *
             * The binder gives the property `[x]: number` a special symbol with the name "__computed".
             * In the late-binding phase we can type-check the expression `x` and see that it has a
             * unique symbol type which we can then use as the name of the member. This allows users
             * to define custom symbols that can be used in the members of an object type.
             *
             * @param parent The containing symbol for the member.
             * @param earlySymbols The early-bound symbols of the parent.
             * @param lateSymbols The late-bound symbols of the parent.
             * @param decl The member to bind.
             */
            function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
                ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
                var links = getNodeLinks(decl);
                if (!links.resolvedSymbol) {
                    // In the event we attempt to resolve the late-bound name of this member recursively,
                    // fall back to the early-bound name of this member.
                    links.resolvedSymbol = decl.symbol;
                    var type = checkComputedPropertyName(decl.name);
                    if (isTypeUsableAsLateBoundName(type)) {
                        var memberName = getLateBoundNameFromType(type);
                        var symbolFlags = decl.symbol.flags;
                        // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
                        var lateSymbol = lateSymbols.get(memberName);
                        if (!lateSymbol)
                            lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */));
                        // Report an error if a late-bound member has the same name as an early-bound member,
                        // or if we have another early-bound symbol declaration with the same name and
                        // conflicting flags.
                        var earlySymbol = earlySymbols && earlySymbols.get(memberName);
                        if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
                            // If we have an existing early-bound member, combine its declarations so that we can
                            // report an error at each declaration.
                            var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
                            var name_2 = ts.declarationNameToString(decl.name);
                            ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); });
                            error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2);
                            lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */);
                        }
                        lateSymbol.nameType = type;
                        addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
                        if (lateSymbol.parent) {
                            ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
                        }
                        else {
                            lateSymbol.parent = parent;
                        }
                        return links.resolvedSymbol = lateSymbol;
                    }
                }
                return links.resolvedSymbol;
            }
            function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
                var links = getSymbolLinks(symbol);
                if (!links[resolutionKind]) {
                    var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
                    var earlySymbols = !isStatic ? symbol.members :
                        symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
                            symbol.exports;
                    // In the event we recursively resolve the members/exports of the symbol, we
                    // set the initial value of resolvedMembers/resolvedExports to the early-bound
                    // members/exports of the symbol.
                    links[resolutionKind] = earlySymbols || emptySymbols;
                    // fill in any as-yet-unresolved late-bound members.
                    var lateSymbols = ts.createSymbolTable();
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        var members = ts.getMembersOfDeclaration(decl);
                        if (members) {
                            for (var _b = 0, members_4 = members; _b < members_4.length; _b++) {
                                var member = members_4[_b];
                                if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
                                    lateBindMember(symbol, earlySymbols, lateSymbols, member);
                                }
                            }
                        }
                    }
                    links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
                }
                return links[resolutionKind];
            }
            /**
             * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
             *
             * For a description of late-binding, see `lateBindMember`.
             */
            function getMembersOfSymbol(symbol) {
                return symbol.flags & 6240 /* LateBindingContainer */
                    ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
                    : symbol.members || emptySymbols;
            }
            /**
             * If a symbol is the dynamic name of the member of an object type, get the late-bound
             * symbol of the member.
             *
             * For a description of late-binding, see `lateBindMember`.
             */
            function getLateBoundSymbol(symbol) {
                if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
                    var links = getSymbolLinks(symbol);
                    if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
                        // force late binding of members/exports. This will set the late-bound symbol
                        if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
                            getExportsOfSymbol(symbol.parent);
                        }
                        else {
                            getMembersOfSymbol(symbol.parent);
                        }
                    }
                    return links.lateSymbol || (links.lateSymbol = symbol);
                }
                return symbol;
            }
            function getTypeWithThisArgument(type, thisArgument, needApparentType) {
                if (ts.getObjectFlags(type) & 4 /* Reference */) {
                    var target = type.target;
                    var typeArguments = type.typeArguments;
                    if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
                        var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
                        return needApparentType ? getApparentType(ref) : ref;
                    }
                }
                else if (type.flags & 524288 /* Intersection */) {
                    return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
                }
                return needApparentType ? getApparentType(type) : type;
            }
            function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
                var mapper;
                var members;
                var callSignatures;
                var constructSignatures;
                var stringIndexInfo;
                var numberIndexInfo;
                if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
                    mapper = identityMapper;
                    members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
                    callSignatures = source.declaredCallSignatures;
                    constructSignatures = source.declaredConstructSignatures;
                    stringIndexInfo = source.declaredStringIndexInfo;
                    numberIndexInfo = source.declaredNumberIndexInfo;
                }
                else {
                    mapper = createTypeMapper(typeParameters, typeArguments);
                    members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
                    callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
                    constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
                    stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
                    numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
                }
                var baseTypes = getBaseTypes(source);
                if (baseTypes.length) {
                    if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
                        members = ts.createSymbolTable(source.declaredProperties);
                    }
                    setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
                    var thisArgument = ts.lastOrUndefined(typeArguments);
                    for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
                        var baseType = baseTypes_1[_i];
                        var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
                        addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
                        callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
                        constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
                        if (!stringIndexInfo) {
                            stringIndexInfo = instantiatedBaseType === anyType ?
                                createIndexInfo(anyType, /*isReadonly*/ false) :
                                getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
                        }
                        numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
                    }
                }
                setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
            }
            function resolveClassOrInterfaceMembers(type) {
                resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
            }
            function resolveTypeReferenceMembers(type) {
                var source = resolveDeclaredMembers(type.target);
                var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
                var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ?
                    type.typeArguments : ts.concatenate(type.typeArguments, [type]);
                resolveObjectTypeMembers(type, source, typeParameters, typeArguments);
            }
            function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) {
                var sig = new Signature(checker);
                sig.declaration = declaration;
                sig.typeParameters = typeParameters;
                sig.parameters = parameters;
                sig.thisParameter = thisParameter;
                sig.resolvedReturnType = resolvedReturnType;
                sig.resolvedTypePredicate = resolvedTypePredicate;
                sig.minArgumentCount = minArgumentCount;
                sig.hasRestParameter = hasRestParameter;
                sig.hasLiteralTypes = hasLiteralTypes;
                sig.target = undefined;
                sig.mapper = undefined;
                return sig;
            }
            function cloneSignature(sig) {
                return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
                /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
            }
            function getExpandedParameters(sig) {
                if (sig.hasRestParameter) {
                    var restIndex_1 = sig.parameters.length - 1;
                    var restParameter = sig.parameters[restIndex_1];
                    var restType = getTypeOfSymbol(restParameter);
                    if (isTupleType(restType)) {
                        var elementTypes = restType.typeArguments || ts.emptyArray;
                        var minLength_1 = restType.target.minLength;
                        var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
                        var restParams = ts.map(elementTypes, function (t, i) {
                            var name = getParameterNameAtPosition(sig, restIndex_1 + i);
                            var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ :
                                i >= minLength_1 ? 4096 /* OptionalParameter */ : 0;
                            var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
                            symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
                            return symbol;
                        });
                        return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
                    }
                }
                return sig.parameters;
            }
            function getDefaultConstructSignatures(classType) {
                var baseConstructorType = getBaseConstructorTypeOfClass(classType);
                var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
                if (baseSignatures.length === 0) {
                    return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217
                }
                var baseTypeNode = getBaseTypeNodeOfClass(classType);
                var isJavaScript = ts.isInJSFile(baseTypeNode);
                var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
                var typeArgCount = ts.length(typeArguments);
                var result = [];
                for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
                    var baseSig = baseSignatures_1[_i];
                    var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
                    var typeParamCount = ts.length(baseSig.typeParameters);
                    if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
                        var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
                        sig.typeParameters = classType.localTypeParameters;
                        sig.resolvedReturnType = classType;
                        result.push(sig);
                    }
                }
                return result;
            }
            function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
                for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
                    var s = signatureList_1[_i];
                    if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) {
                        return s;
                    }
                }
            }
            function findMatchingSignatures(signatureLists, signature, listIndex) {
                if (signature.typeParameters) {
                    // We require an exact match for generic signatures, so we only return signatures from the first
                    // signature list and only if they have exact matches in the other signature lists.
                    if (listIndex > 0) {
                        return undefined;
                    }
                    for (var i = 1; i < signatureLists.length; i++) {
                        if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
                            return undefined;
                        }
                    }
                    return [signature];
                }
                var result;
                for (var i = 0; i < signatureLists.length; i++) {
                    // Allow matching non-generic signatures to have excess parameters and different return types
                    var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true);
                    if (!match) {
                        return undefined;
                    }
                    result = ts.appendIfUnique(result, match);
                }
                return result;
            }
            // The signatures of a union type are those signatures that are present in each of the constituent types.
            // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
            // parameters and may differ in return types. When signatures differ in return types, the resulting return
            // type is the union of the constituent return types.
            function getUnionSignatures(types, kind) {
                var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });
                var result;
                for (var i = 0; i < signatureLists.length; i++) {
                    for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
                        var signature = _a[_i];
                        // Only process signatures with parameter lists that aren't already in the result list
                        if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) {
                            var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
                            if (unionSignatures) {
                                var s = signature;
                                // Union the result types when more than one signature matches
                                if (unionSignatures.length > 1) {
                                    var thisParameter = signature.thisParameter;
                                    if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) {
                                        // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do
                                        var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
                                        thisParameter = createSymbolWithType(signature.thisParameter, thisType);
                                    }
                                    s = cloneSignature(signature);
                                    s.thisParameter = thisParameter;
                                    s.unionSignatures = unionSignatures;
                                }
                                (result || (result = [])).push(s);
                            }
                        }
                    }
                }
                return result || ts.emptyArray;
            }
            function getUnionIndexInfo(types, kind) {
                var indexTypes = [];
                var isAnyReadonly = false;
                for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
                    var type = types_2[_i];
                    var indexInfo = getIndexInfoOfType(type, kind);
                    if (!indexInfo) {
                        return undefined;
                    }
                    indexTypes.push(indexInfo.type);
                    isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
                }
                return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
            }
            function resolveUnionTypeMembers(type) {
                // The members and properties collections are empty for union types. To get all properties of a union
                // type use getPropertiesOfType (only the language service uses this).
                var callSignatures = getUnionSignatures(type.types, 0 /* Call */);
                var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */);
                var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
                var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
                setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
            }
            function intersectTypes(type1, type2) {
                return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
            }
            function intersectIndexInfos(info1, info2) {
                return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
            }
            function unionSpreadIndexInfos(info1, info2) {
                return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
            }
            function includeMixinType(type, types, index) {
                var mixedTypes = [];
                for (var i = 0; i < types.length; i++) {
                    if (i === index) {
                        mixedTypes.push(type);
                    }
                    else if (isMixinConstructorType(types[i])) {
                        mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
                    }
                }
                return getIntersectionType(mixedTypes);
            }
            function resolveIntersectionTypeMembers(type) {
                // The members and properties collections are empty for intersection types. To get all properties of an
                // intersection type use getPropertiesOfType (only the language service uses this).
                var callSignatures = ts.emptyArray;
                var constructSignatures = ts.emptyArray;
                var stringIndexInfo;
                var numberIndexInfo;
                var types = type.types;
                var mixinCount = ts.countWhere(types, isMixinConstructorType);
                var _loop_4 = function (i) {
                    var t = type.types[i];
                    // When an intersection type contains mixin constructor types, the construct signatures from
                    // those types are discarded and their return types are mixed into the return types of all
                    // other construct signatures in the intersection type. For example, the intersection type
                    // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
                    // 'new(s: string) => A & B'.
                    if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
                        var signatures = getSignaturesOfType(t, 1 /* Construct */);
                        if (signatures.length && mixinCount > 0) {
                            signatures = ts.map(signatures, function (s) {
                                var clone = cloneSignature(s);
                                clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
                                return clone;
                            });
                        }
                        constructSignatures = ts.concatenate(constructSignatures, signatures);
                    }
                    callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */));
                    stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
                    numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
                };
                for (var i = 0; i < types.length; i++) {
                    _loop_4(i);
                }
                setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
            }
            /**
             * Converts an AnonymousType to a ResolvedType.
             */
            function resolveAnonymousTypeMembers(type) {
                var symbol = type.symbol;
                if (type.target) {
                    setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
                    var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
                    var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
                    var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
                    var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
                    var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
                    setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
                }
                else if (symbol.flags & 2048 /* TypeLiteral */) {
                    setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
                    var members = getMembersOfSymbol(symbol);
                    var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
                    var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
                    var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
                    var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
                    setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
                }
                else {
                    // Combinations of function, class, enum and module
                    var members = emptySymbols;
                    var stringIndexInfo = void 0;
                    if (symbol.exports) {
                        members = getExportsOfSymbol(symbol);
                    }
                    setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
                    if (symbol.flags & 32 /* Class */) {
                        var classType = getDeclaredTypeOfClassOrInterface(symbol);
                        var baseConstructorType = getBaseConstructorTypeOfClass(classType);
                        if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) {
                            members = ts.createSymbolTable(getNamedMembers(members));
                            addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
                        }
                        else if (baseConstructorType === anyType) {
                            stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
                        }
                    }
                    var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined;
                    setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
                    // We resolve the members before computing the signatures because a signature may use
                    // typeof with a qualified name expression that circularly references the type we are
                    // in the process of resolving (see issue #6072). The temporarily empty signature list
                    // will never be observed because a qualified name can't reference signatures.
                    if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
                        type.callSignatures = getSignaturesOfSymbol(symbol);
                    }
                    // And likewise for construct signatures for classes
                    if (symbol.flags & 32 /* Class */) {
                        var classType = getDeclaredTypeOfClassOrInterface(symbol);
                        var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */));
                        if (!constructSignatures.length) {
                            constructSignatures = getDefaultConstructSignatures(classType);
                        }
                        type.constructSignatures = constructSignatures;
                    }
                }
            }
            function resolveReverseMappedTypeMembers(type) {
                var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
                var modifiers = getMappedTypeModifiers(type.mappedType);
                var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
                var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
                var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly);
                var members = ts.createSymbolTable();
                for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
                    var prop = _a[_i];
                    var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
                    var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
                    inferredProp.declarations = prop.declarations;
                    inferredProp.nameType = prop.nameType;
                    inferredProp.propertyType = getTypeOfSymbol(prop);
                    inferredProp.mappedType = type.mappedType;
                    members.set(prop.escapedName, inferredProp);
                }
                setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
            }
            /** Resolve the members of a mapped type { [P in K]: T } */
            function resolveMappedTypeMembers(type) {
                var members = ts.createSymbolTable();
                var stringIndexInfo;
                var numberIndexInfo;
                // Resolve upfront such that recursive references see an empty object type.
                setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
                // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
                // and T as the template type.
                var typeParameter = getTypeParameterFromMappedType(type);
                var constraintType = getConstraintTypeFromMappedType(type);
                var templateType = getTemplateTypeFromMappedType(type.target || type);
                var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
                var templateModifiers = getMappedTypeModifiers(type);
                var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */;
                if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
                    // We have a { [P in keyof T]: X }
                    for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
                        var prop = _a[_i];
                        addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include));
                    }
                    if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
                        addMemberForKeyType(stringType);
                    }
                    if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
                        addMemberForKeyType(numberType);
                    }
                }
                else {
                    // First, if the constraint type is a type parameter, obtain the base constraint. Then,
                    // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X.
                    // Finally, iterate over the constituents of the resulting iteration type.
                    var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType;
                    var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType;
                    forEachType(iterationType, addMemberForKeyType);
                }
                setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
                function addMemberForKeyType(t) {
                    // Create a mapper from T to the current iteration type constituent. Then, if the
                    // mapped type is itself an instantiated type, combine the iteration mapper with the
                    // instantiation mapper.
                    var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t]));
                    var propType = instantiateType(templateType, templateMapper);
                    // If the current iteration type constituent is a string literal type, create a property.
                    // Otherwise, for type string create a string index signature.
                    if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) {
                        var propName = getLateBoundNameFromType(t);
                        var modifiersProp = getPropertyOfType(modifiersType, propName);
                        var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
                            !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
                        var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
                            !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
                        var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0);
                        // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
                        // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
                        // mode, if the underlying property is optional we remove 'undefined' from the type.
                        prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) :
                            strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) :
                                propType;
                        if (modifiersProp) {
                            prop.syntheticOrigin = modifiersProp;
                            prop.declarations = modifiersProp.declarations;
                        }
                        prop.nameType = t;
                        members.set(propName, prop);
                    }
                    else if (t.flags & (1 /* Any */ | 4 /* String */)) {
                        stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
                    }
                    else if (t.flags & 8 /* Number */) {
                        numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
                    }
                }
            }
            function getTypeParameterFromMappedType(type) {
                return type.typeParameter ||
                    (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
            }
            function getConstraintTypeFromMappedType(type) {
                return type.constraintType ||
                    (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType);
            }
            function getTemplateTypeFromMappedType(type) {
                return type.templateType ||
                    (type.templateType = type.declaration.type ?
                        instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) :
                        errorType);
            }
            function getConstraintDeclarationForMappedType(type) {
                return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
            }
            function isMappedTypeWithKeyofConstraintDeclaration(type) {
                var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
                return constraintDeclaration.kind === 177 /* TypeOperator */ &&
                    constraintDeclaration.operator === 128 /* KeyOfKeyword */;
            }
            function getModifiersTypeFromMappedType(type) {
                if (!type.modifiersType) {
                    if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
                        // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
                        // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
                        // 'keyof T' to a literal union type and we can't recover T from that type.
                        type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper);
                    }
                    else {
                        // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
                        // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
                        // the modifiers type is T. Otherwise, the modifiers type is {}.
                        var declaredType = getTypeFromMappedTypeNode(type.declaration);
                        var constraint = getConstraintTypeFromMappedType(declaredType);
                        var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
                        type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType;
                    }
                }
                return type.modifiersType;
            }
            function getMappedTypeModifiers(type) {
                var declaration = type.declaration;
                return (declaration.readonlyToken ? declaration.readonlyToken.kind === 38 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
                    (declaration.questionToken ? declaration.questionToken.kind === 38 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
            }
            function getMappedTypeOptionality(type) {
                var modifiers = getMappedTypeModifiers(type);
                return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
            }
            function getCombinedMappedTypeOptionality(type) {
                var optionality = getMappedTypeOptionality(type);
                var modifiersType = getModifiersTypeFromMappedType(type);
                return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
            }
            function isPartialMappedType(type) {
                return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
            }
            function isGenericMappedType(type) {
                return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
            }
            function resolveStructuredTypeMembers(type) {
                if (!type.members) {
                    if (type.flags & 131072 /* Object */) {
                        if (type.objectFlags & 4 /* Reference */) {
                            resolveTypeReferenceMembers(type);
                        }
                        else if (type.objectFlags & 3 /* ClassOrInterface */) {
                            resolveClassOrInterfaceMembers(type);
                        }
                        else if (type.objectFlags & 2048 /* ReverseMapped */) {
                            resolveReverseMappedTypeMembers(type);
                        }
                        else if (type.objectFlags & 16 /* Anonymous */) {
                            resolveAnonymousTypeMembers(type);
                        }
                        else if (type.objectFlags & 32 /* Mapped */) {
                            resolveMappedTypeMembers(type);
                        }
                    }
                    else if (type.flags & 262144 /* Union */) {
                        resolveUnionTypeMembers(type);
                    }
                    else if (type.flags & 524288 /* Intersection */) {
                        resolveIntersectionTypeMembers(type);
                    }
                }
                return type;
            }
            /** Return properties of an object type or an empty array for other types */
            function getPropertiesOfObjectType(type) {
                if (type.flags & 131072 /* Object */) {
                    return resolveStructuredTypeMembers(type).properties;
                }
                return ts.emptyArray;
            }
            /** If the given type is an object type and that type has a property by the given name,
             * return the symbol for that property. Otherwise return undefined.
             */
            function getPropertyOfObjectType(type, name) {
                if (type.flags & 131072 /* Object */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    var symbol = resolved.members.get(name);
                    if (symbol && symbolIsValue(symbol)) {
                        return symbol;
                    }
                }
            }
            function getPropertiesOfUnionOrIntersectionType(type) {
                if (!type.resolvedProperties) {
                    var members = ts.createSymbolTable();
                    for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
                        var current = _a[_i];
                        for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
                            var prop = _c[_b];
                            if (!members.has(prop.escapedName)) {
                                var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
                                if (combinedProp) {
                                    members.set(prop.escapedName, combinedProp);
                                }
                            }
                        }
                        // The properties of a union type are those that are present in all constituent types, so
                        // we only need to check the properties of the first type
                        if (type.flags & 262144 /* Union */) {
                            break;
                        }
                    }
                    type.resolvedProperties = getNamedMembers(members);
                }
                return type.resolvedProperties;
            }
            function getPropertiesOfType(type) {
                type = getApparentType(type);
                return type.flags & 786432 /* UnionOrIntersection */ ?
                    getPropertiesOfUnionOrIntersectionType(type) :
                    getPropertiesOfObjectType(type);
            }
            function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
                return obj.properties.some(function (property) {
                    var name = property.name && ts.getTextOfPropertyName(property.name);
                    var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
                    return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
                });
            }
            function getAllPossiblePropertiesOfTypes(types) {
                var unionType = getUnionType(types);
                if (!(unionType.flags & 262144 /* Union */)) {
                    return getAugmentedPropertiesOfType(unionType);
                }
                var props = ts.createSymbolTable();
                for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
                    var memberType = types_3[_i];
                    for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
                        var escapedName = _b[_a].escapedName;
                        if (!props.has(escapedName)) {
                            var prop = createUnionOrIntersectionProperty(unionType, escapedName);
                            // May be undefined if the property is private
                            if (prop)
                                props.set(escapedName, prop);
                        }
                    }
                }
                return ts.arrayFrom(props.values());
            }
            function getConstraintOfType(type) {
                return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
                    type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
                        type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) :
                            getBaseConstraintOfType(type);
            }
            function getConstraintOfTypeParameter(typeParameter) {
                return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
            }
            function getConstraintOfIndexedAccess(type) {
                var objectType = getConstraintOfType(type.objectType) || type.objectType;
                if (objectType !== type.objectType) {
                    var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
                    if (constraint && constraint !== errorType) {
                        return constraint;
                    }
                }
                var baseConstraint = getBaseConstraintOfType(type);
                return baseConstraint && baseConstraint !== type ? baseConstraint : undefined;
            }
            function getDefaultConstraintOfConditionalType(type) {
                if (!type.resolvedDefaultConstraint) {
                    var rootTrueType = type.root.trueType;
                    var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType;
                    type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
                }
                return type.resolvedDefaultConstraint;
            }
            function getConstraintOfDistributiveConditionalType(type) {
                // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
                // type parameter. If so, create an instantiation of the conditional type where T is replaced
                // with its constraint. We do this because if the constraint is a union type it will be distributed
                // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
                // removes 'undefined' from T.
                if (type.root.isDistributive) {
                    var simplified = getSimplifiedType(type.checkType);
                    var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
                    if (constraint) {
                        var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
                        var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
                        if (!(instantiated.flags & 32768 /* Never */)) {
                            return instantiated;
                        }
                    }
                }
                return undefined;
            }
            function getConstraintOfConditionalType(type) {
                return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
            }
            function getUnionConstraintOfIntersection(type, targetIsUnion) {
                var constraints;
                var hasDisjointDomainType = false;
                for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
                    var t = _a[_i];
                    if (t.flags & 15794176 /* Instantiable */) {
                        // We keep following constraints as long as we have an instantiable type that is known
                        // not to be circular or infinite (hence we stop on index access types).
                        var constraint = getConstraintOfType(t);
                        while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) {
                            constraint = getConstraintOfType(constraint);
                        }
                        if (constraint) {
                            // A constraint that isn't a union type implies that the final type would be a non-union
                            // type as well. Since non-union constraints are of no interest, we can exit here.
                            if (!(constraint.flags & 262144 /* Union */)) {
                                return undefined;
                            }
                            constraints = ts.append(constraints, constraint);
                        }
                    }
                    else if (t.flags & 16809468 /* DisjointDomains */) {
                        hasDisjointDomainType = true;
                    }
                }
                // If the target is a union type or if we are intersecting with types belonging to one of the
                // disjoint domans, we may end up producing a constraint that hasn't been examined before.
                if (constraints && (targetIsUnion || hasDisjointDomainType)) {
                    if (hasDisjointDomainType) {
                        // We add any types belong to one of the disjoint domans because they might cause the final
                        // intersection operation to reduce the union constraints.
                        for (var _b = 0, _c = type.types; _b < _c.length; _b++) {
                            var t = _c[_b];
                            if (t.flags & 16809468 /* DisjointDomains */) {
                                constraints = ts.append(constraints, t);
                            }
                        }
                    }
                    return getIntersectionType(constraints);
                }
                return undefined;
            }
            function getBaseConstraintOfType(type) {
                if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) {
                    var constraint = getResolvedBaseConstraint(type);
                    return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
                }
                return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined;
            }
            /**
             * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
             * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
             */
            function getBaseConstraintOrType(type) {
                return getBaseConstraintOfType(type) || type;
            }
            function hasNonCircularBaseConstraint(type) {
                return getResolvedBaseConstraint(type) !== circularConstraintType;
            }
            /**
             * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
             * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
             * circularly references the type variable.
             */
            function getResolvedBaseConstraint(type) {
                var nonTerminating = false;
                return type.resolvedBaseConstraint ||
                    (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
                function getImmediateBaseConstraint(t) {
                    if (!t.immediateBaseConstraint) {
                        if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
                            return circularConstraintType;
                        }
                        if (constraintDepth === 50) {
                            // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
                            // very high likelyhood we're dealing with an infinite generic type that perpetually generates
                            // new type identities as we descend into it. We stop the recursion here and mark this type
                            // and the outer types as having circular constraints.
                            nonTerminating = true;
                            return t.immediateBaseConstraint = noConstraintType;
                        }
                        constraintDepth++;
                        var result = computeBaseConstraint(getSimplifiedType(t));
                        constraintDepth--;
                        if (!popTypeResolution() || nonTerminating) {
                            result = circularConstraintType;
                        }
                        t.immediateBaseConstraint = result || noConstraintType;
                    }
                    return t.immediateBaseConstraint;
                }
                function getBaseConstraint(t) {
                    var c = getImmediateBaseConstraint(t);
                    return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
                }
                function computeBaseConstraint(t) {
                    if (t.flags & 65536 /* TypeParameter */) {
                        var constraint = getConstraintFromTypeParameter(t);
                        return t.isThisType || !constraint ?
                            constraint :
                            getBaseConstraint(constraint);
                    }
                    if (t.flags & 786432 /* UnionOrIntersection */) {
                        var types = t.types;
                        var baseTypes = [];
                        for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
                            var type_3 = types_4[_i];
                            var baseType = getBaseConstraint(type_3);
                            if (baseType) {
                                baseTypes.push(baseType);
                            }
                        }
                        return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
                            t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
                                undefined;
                    }
                    if (t.flags & 1048576 /* Index */) {
                        return keyofConstraintType;
                    }
                    if (t.flags & 2097152 /* IndexedAccess */) {
                        var baseObjectType = getBaseConstraint(t.objectType);
                        var baseIndexType = getBaseConstraint(t.indexType);
                        var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined;
                        return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
                    }
                    if (t.flags & 4194304 /* Conditional */) {
                        var constraint = getConstraintOfConditionalType(t);
                        return constraint && getBaseConstraint(constraint);
                    }
                    if (t.flags & 8388608 /* Substitution */) {
                        return getBaseConstraint(t.substitute);
                    }
                    return t;
                }
            }
            function getApparentTypeOfIntersectionType(type) {
                return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
            }
            function getResolvedTypeParameterDefault(typeParameter) {
                if (!typeParameter.default) {
                    if (typeParameter.target) {
                        var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
                        typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
                    }
                    else {
                        // To block recursion, set the initial value to the resolvingDefaultType.
                        typeParameter.default = resolvingDefaultType;
                        var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
                        var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
                        if (typeParameter.default === resolvingDefaultType) {
                            // If we have not been called recursively, set the correct default type.
                            typeParameter.default = defaultType;
                        }
                    }
                }
                else if (typeParameter.default === resolvingDefaultType) {
                    // If we are called recursively for this type parameter, mark the default as circular.
                    typeParameter.default = circularConstraintType;
                }
                return typeParameter.default;
            }
            /**
             * Gets the default type for a type parameter.
             *
             * If the type parameter is the result of an instantiation, this gets the instantiated
             * default type of its target. If the type parameter has no default type or the default is
             * circular, `undefined` is returned.
             */
            function getDefaultFromTypeParameter(typeParameter) {
                var defaultType = getResolvedTypeParameterDefault(typeParameter);
                return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
            }
            function hasNonCircularTypeParameterDefault(typeParameter) {
                return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
            }
            /**
             * Indicates whether the declaration of a typeParameter has a default type.
             */
            function hasTypeParameterDefault(typeParameter) {
                return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
            }
            function getApparentTypeOfMappedType(type) {
                return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
            }
            function getResolvedApparentTypeOfMappedType(type) {
                var typeVariable = getHomomorphicTypeVariable(type);
                if (typeVariable) {
                    var constraint = getConstraintOfTypeParameter(typeVariable);
                    if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
                        var mapper = makeUnaryTypeMapper(typeVariable, constraint);
                        return instantiateType(type, combineTypeMappers(mapper, type.mapper));
                    }
                }
                return type;
            }
            /**
             * For a type parameter, return the base constraint of the type parameter. For the string, number,
             * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
             * type itself. Note that the apparent type of a union type is the union type itself.
             */
            function getApparentType(type) {
                var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type;
                return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
                    t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
                        t.flags & 68 /* StringLike */ ? globalStringType :
                            t.flags & 168 /* NumberLike */ ? globalNumberType :
                                t.flags & 272 /* BooleanLike */ ? globalBooleanType :
                                    t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
                                        t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType :
                                            t.flags & 1048576 /* Index */ ? keyofConstraintType :
                                                t;
            }
            function createUnionOrIntersectionProperty(containingType, name) {
                var props;
                var indexTypes;
                var isUnion = containingType.flags & 262144 /* Union */;
                var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
                // Flags we want to propagate to the result if they exist in all source symbols
                var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */;
                var syntheticFlag = 4 /* SyntheticMethod */;
                var checkFlags = 0;
                for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
                    var current = _a[_i];
                    var type = getApparentType(current);
                    if (type !== errorType) {
                        var prop = getPropertyOfType(type, name);
                        var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
                        if (prop && !(modifiers & excludeModifiers)) {
                            commonFlags &= prop.flags;
                            props = ts.appendIfUnique(props, prop);
                            checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
                                (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) |
                                (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) |
                                (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) |
                                (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0);
                            if (!isPrototypeProperty(prop)) {
                                syntheticFlag = 2 /* SyntheticProperty */;
                            }
                        }
                        else if (isUnion) {
                            var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */));
                            if (index) {
                                checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0;
                                indexTypes = ts.append(indexTypes, index.type);
                            }
                            else {
                                checkFlags |= 16 /* Partial */;
                            }
                        }
                    }
                }
                if (!props) {
                    return undefined;
                }
                if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
                    return props[0];
                }
                var declarations;
                var commonType;
                var nameType;
                var propTypes = [];
                var first = true;
                var commonValueDeclaration;
                var hasNonUniformValueDeclaration = false;
                for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
                    var prop = props_1[_b];
                    if (!commonValueDeclaration) {
                        commonValueDeclaration = prop.valueDeclaration;
                    }
                    else if (prop.valueDeclaration !== commonValueDeclaration) {
                        hasNonUniformValueDeclaration = true;
                    }
                    declarations = ts.addRange(declarations, prop.declarations);
                    var type = getTypeOfSymbol(prop);
                    if (first) {
                        commonType = type;
                        nameType = prop.nameType;
                        first = false;
                    }
                    else {
                        if (type !== commonType) {
                            checkFlags |= 32 /* HasNonUniformType */;
                        }
                    }
                    propTypes.push(type);
                }
                ts.addRange(propTypes, indexTypes);
                var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags);
                result.containingType = containingType;
                if (!hasNonUniformValueDeclaration && commonValueDeclaration) {
                    result.valueDeclaration = commonValueDeclaration;
                }
                result.declarations = declarations;
                result.nameType = nameType;
                result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
                return result;
            }
            // Return the symbol for a given property in a union or intersection type, or undefined if the property
            // does not exist in any constituent type. Note that the returned property may only be present in some
            // constituents, in which case the isPartial flag is set when the containing type is union type. We need
            // these partial properties when identifying discriminant properties, but otherwise they are filtered out
            // and do not appear to be present in the union type.
            function getUnionOrIntersectionProperty(type, name) {
                var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
                var property = properties.get(name);
                if (!property) {
                    property = createUnionOrIntersectionProperty(type, name);
                    if (property) {
                        properties.set(name, property);
                    }
                }
                return property;
            }
            function getPropertyOfUnionOrIntersectionType(type, name) {
                var property = getUnionOrIntersectionProperty(type, name);
                // We need to filter out partial properties in union types
                return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined;
            }
            /**
             * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
             * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
             * Object and Function as appropriate.
             *
             * @param type a type to look up property from
             * @param name a name of property to look up in a given type
             */
            function getPropertyOfType(type, name) {
                type = getApparentType(type);
                if (type.flags & 131072 /* Object */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    var symbol = resolved.members.get(name);
                    if (symbol && symbolIsValue(symbol)) {
                        return symbol;
                    }
                    if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) {
                        var symbol_1 = getPropertyOfObjectType(globalFunctionType, name);
                        if (symbol_1) {
                            return symbol_1;
                        }
                    }
                    return getPropertyOfObjectType(globalObjectType, name);
                }
                if (type.flags & 786432 /* UnionOrIntersection */) {
                    return getPropertyOfUnionOrIntersectionType(type, name);
                }
                return undefined;
            }
            function getSignaturesOfStructuredType(type, kind) {
                if (type.flags & 917504 /* StructuredType */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
                }
                return ts.emptyArray;
            }
            /**
             * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
             * maps primitive types and type parameters are to their apparent types.
             */
            function getSignaturesOfType(type, kind) {
                return getSignaturesOfStructuredType(getApparentType(type), kind);
            }
            function getIndexInfoOfStructuredType(type, kind) {
                if (type.flags & 917504 /* StructuredType */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
                }
            }
            function getIndexTypeOfStructuredType(type, kind) {
                var info = getIndexInfoOfStructuredType(type, kind);
                return info && info.type;
            }
            // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
            // maps primitive types and type parameters are to their apparent types.
            function getIndexInfoOfType(type, kind) {
                return getIndexInfoOfStructuredType(getApparentType(type), kind);
            }
            // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
            // maps primitive types and type parameters are to their apparent types.
            function getIndexTypeOfType(type, kind) {
                return getIndexTypeOfStructuredType(getApparentType(type), kind);
            }
            function getImplicitIndexTypeOfType(type, kind) {
                if (isObjectTypeWithInferableIndex(type)) {
                    var propTypes = [];
                    for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
                        var prop = _a[_i];
                        if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
                            propTypes.push(getTypeOfSymbol(prop));
                        }
                    }
                    if (propTypes.length) {
                        return getUnionType(propTypes, 2 /* Subtype */);
                    }
                }
                return undefined;
            }
            // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
            // type checking functions).
            function getTypeParametersFromDeclaration(declaration) {
                var result;
                for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
                    var node = _a[_i];
                    result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
                }
                return result;
            }
            function symbolsToArray(symbols) {
                var result = [];
                symbols.forEach(function (symbol, id) {
                    if (!isReservedMemberName(id)) {
                        result.push(symbol);
                    }
                });
                return result;
            }
            function isJSDocOptionalParameter(node) {
                return ts.isInJSFile(node) && (
                // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
                node.type && node.type.kind === 286 /* JSDocOptionalType */
                    || ts.getJSDocParameterTags(node).some(function (_a) {
                        var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
                        return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */;
                    }));
            }
            function tryFindAmbientModule(moduleName, withAugmentations) {
                if (ts.isExternalModuleNameRelative(moduleName)) {
                    return undefined;
                }
                var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
                // merged symbol is module declaration symbol combined with all augmentations
                return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
            }
            function isOptionalParameter(node) {
                if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
                    return true;
                }
                if (node.initializer) {
                    var signature = getSignatureFromDeclaration(node.parent);
                    var parameterIndex = node.parent.parameters.indexOf(node);
                    ts.Debug.assert(parameterIndex >= 0);
                    return parameterIndex >= getMinArgumentCount(signature);
                }
                var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
                if (iife) {
                    return !node.type &&
                        !node.dotDotDotToken &&
                        node.parent.parameters.indexOf(node) >= iife.arguments.length;
                }
                return false;
            }
            function isOptionalJSDocParameterTag(node) {
                if (!ts.isJSDocParameterTag(node)) {
                    return false;
                }
                var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
                return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */;
            }
            function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
                return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
            }
            function createThisTypePredicate(type) {
                return { kind: 0 /* This */, type: type };
            }
            /**
             * Gets the minimum number of type arguments needed to satisfy all non-optional type
             * parameters.
             */
            function getMinTypeArgumentCount(typeParameters) {
                var minTypeArgumentCount = 0;
                if (typeParameters) {
                    for (var i = 0; i < typeParameters.length; i++) {
                        if (!hasTypeParameterDefault(typeParameters[i])) {
                            minTypeArgumentCount = i + 1;
                        }
                    }
                }
                return minTypeArgumentCount;
            }
            function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
                var numTypeParameters = ts.length(typeParameters);
                if (numTypeParameters) {
                    var numTypeArguments = ts.length(typeArguments);
                    if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
                        if (!typeArguments) {
                            typeArguments = [];
                        }
                        // Map an unsatisfied type parameter with a default type.
                        // If a type parameter does not have a default type, or if the default type
                        // is a forward reference, the empty object type is used.
                        for (var i = numTypeArguments; i < numTypeParameters; i++) {
                            typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
                        }
                        for (var i = numTypeArguments; i < numTypeParameters; i++) {
                            var mapper = createTypeMapper(typeParameters, typeArguments);
                            var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
                            if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) {
                                defaultType = anyType;
                            }
                            typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny);
                        }
                        typeArguments.length = typeParameters.length;
                    }
                }
                return typeArguments;
            }
            function getSignatureFromDeclaration(declaration) {
                var links = getNodeLinks(declaration);
                if (!links.resolvedSignature) {
                    var parameters = [];
                    var hasLiteralTypes = false;
                    var minArgumentCount = 0;
                    var thisParameter = void 0;
                    var hasThisParameter = false;
                    var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
                    var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
                    var isUntypedSignatureInJSFile = !iife &&
                        ts.isInJSFile(declaration) &&
                        ts.isValueSignatureDeclaration(declaration) &&
                        !ts.hasJSDocParameterTags(declaration) &&
                        !ts.getJSDocType(declaration);
                    // If this is a JSDoc construct signature, then skip the first parameter in the
                    // parameter list.  The first parameter represents the return type of the construct
                    // signature.
                    for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
                        var param = declaration.parameters[i];
                        var paramSymbol = param.symbol;
                        var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
                        // Include parameter symbol instead of property symbol in the signature
                        if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
                            var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false);
                            paramSymbol = resolvedSymbol;
                        }
                        if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
                            hasThisParameter = true;
                            thisParameter = param.symbol;
                        }
                        else {
                            parameters.push(paramSymbol);
                        }
                        if (type && type.kind === 180 /* LiteralType */) {
                            hasLiteralTypes = true;
                        }
                        // Record a new minimum argument count if this is not an optional parameter
                        var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
                            param.initializer || param.questionToken || param.dotDotDotToken ||
                            iife && parameters.length > iife.arguments.length && !type ||
                            isUntypedSignatureInJSFile ||
                            isJSDocOptionalParameter(param);
                        if (!isOptionalParameter_1) {
                            minArgumentCount = parameters.length;
                        }
                    }
                    // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
                    if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) &&
                        !hasNonBindableDynamicName(declaration) &&
                        (!hasThisParameter || !thisParameter)) {
                        var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */;
                        var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
                        if (other) {
                            thisParameter = getAnnotatedAccessorThisParameter(other);
                        }
                    }
                    var classType = declaration.kind === 155 /* Constructor */ ?
                        getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
                        : undefined;
                    var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
                    var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters);
                    links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
                    /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes);
                }
                return links.resolvedSignature;
            }
            /**
             * A JS function gets a synthetic rest parameter if it references `arguments` AND:
             * 1. It has no parameters but at least one `@param` with a type that starts with `...`
             * OR
             * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
             */
            function maybeAddJsSyntheticRestParameter(declaration, parameters) {
                if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
                    return false;
                }
                var lastParam = ts.lastOrUndefined(declaration.parameters);
                var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
                var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
                    return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
                });
                var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */);
                syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
                if (lastParamVariadicType) {
                    // Replace the last parameter with a rest parameter.
                    parameters.pop();
                }
                parameters.push(syntheticArgsSymbol);
                return true;
            }
            function getSignatureOfTypeTag(node) {
                var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
                var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
                return signature && getErasedSignature(signature);
            }
            function getReturnTypeOfTypeTag(node) {
                var signature = getSignatureOfTypeTag(node);
                return signature && getReturnTypeOfSignature(signature);
            }
            function containsArgumentsReference(declaration) {
                var links = getNodeLinks(declaration);
                if (links.containsArgumentsReference === undefined) {
                    if (links.flags & 8192 /* CaptureArguments */) {
                        links.containsArgumentsReference = true;
                    }
                    else {
                        links.containsArgumentsReference = traverse(declaration.body);
                    }
                }
                return links.containsArgumentsReference;
                function traverse(node) {
                    if (!node)
                        return false;
                    switch (node.kind) {
                        case 71 /* Identifier */:
                            return node.escapedText === "arguments" && ts.isExpressionNode(node);
                        case 152 /* PropertyDeclaration */:
                        case 154 /* MethodDeclaration */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            return node.name.kind === 147 /* ComputedPropertyName */
                                && traverse(node.name);
                        default:
                            return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
                    }
                }
            }
            function getSignaturesOfSymbol(symbol) {
                if (!symbol)
                    return ts.emptyArray;
                var result = [];
                for (var i = 0; i < symbol.declarations.length; i++) {
                    var decl = symbol.declarations[i];
                    if (!ts.isFunctionLike(decl))
                        continue;
                    // Don't include signature if node is the implementation of an overloaded function. A node is considered
                    // an implementation node if it has a body and the previous node is of the same kind and immediately
                    // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
                    if (i > 0 && decl.body) {
                        var previous = symbol.declarations[i - 1];
                        if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
                            continue;
                        }
                    }
                    result.push(getSignatureFromDeclaration(decl));
                }
                return result;
            }
            function resolveExternalModuleTypeByLiteral(name) {
                var moduleSym = resolveExternalModuleName(name, name);
                if (moduleSym) {
                    var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
                    if (resolvedModuleSymbol) {
                        return getTypeOfSymbol(resolvedModuleSymbol);
                    }
                }
                return anyType;
            }
            function getThisTypeOfSignature(signature) {
                if (signature.thisParameter) {
                    return getTypeOfSymbol(signature.thisParameter);
                }
            }
            function signatureHasTypePredicate(signature) {
                return getTypePredicateOfSignature(signature) !== undefined;
            }
            function getTypePredicateOfSignature(signature) {
                if (!signature.resolvedTypePredicate) {
                    if (signature.target) {
                        var targetTypePredicate = getTypePredicateOfSignature(signature.target);
                        signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
                    }
                    else if (signature.unionSignatures) {
                        signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
                    }
                    else {
                        var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
                        var jsdocPredicate = void 0;
                        if (!type && ts.isInJSFile(signature.declaration)) {
                            var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
                            if (jsdocSignature && signature !== jsdocSignature) {
                                jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
                            }
                        }
                        signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
                            createTypePredicateFromTypePredicateNode(type, signature.declaration) :
                            jsdocPredicate || noTypePredicate;
                    }
                    ts.Debug.assert(!!signature.resolvedTypePredicate);
                }
                return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
            }
            function createTypePredicateFromTypePredicateNode(node, func) {
                var parameterName = node.parameterName;
                var type = getTypeFromTypeNode(node.type);
                if (parameterName.kind === 71 /* Identifier */) {
                    return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
                }
                else {
                    return createThisTypePredicate(type);
                }
            }
            function getTypePredicateParameterIndex(parameterList, parameter) {
                for (var i = 0; i < parameterList.length; i++) {
                    var param = parameterList[i];
                    if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) {
                        return i;
                    }
                }
                return -1;
            }
            function getReturnTypeOfSignature(signature) {
                if (!signature.resolvedReturnType) {
                    if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
                        return errorType;
                    }
                    var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
                        signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
                            getReturnTypeFromAnnotation(signature.declaration) ||
                                (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
                    if (!popTypeResolution()) {
                        if (signature.declaration) {
                            var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
                            if (typeNode) {
                                error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
                            }
                            else if (noImplicitAny) {
                                var declaration = signature.declaration;
                                var name = ts.getNameOfDeclaration(declaration);
                                if (name) {
                                    error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name));
                                }
                                else {
                                    error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions);
                                }
                            }
                        }
                        type = anyType;
                    }
                    signature.resolvedReturnType = type;
                }
                return signature.resolvedReturnType;
            }
            function getReturnTypeFromAnnotation(declaration) {
                if (declaration.kind === 155 /* Constructor */) {
                    return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
                }
                if (ts.isJSDocConstructSignature(declaration)) {
                    return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
                }
                var typeNode = ts.getEffectiveReturnTypeNode(declaration);
                if (typeNode) {
                    return getTypeFromTypeNode(typeNode);
                }
                if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
                    var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
                    if (jsDocType) {
                        return jsDocType;
                    }
                    var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */);
                    var setterType = getAnnotatedAccessorType(setter);
                    if (setterType) {
                        return setterType;
                    }
                }
                return getReturnTypeOfTypeTag(declaration);
            }
            function isResolvingReturnTypeOfSignature(signature) {
                return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
            }
            function getRestTypeOfSignature(signature) {
                return tryGetRestTypeOfSignature(signature) || anyType;
            }
            function tryGetRestTypeOfSignature(signature) {
                if (signature.hasRestParameter) {
                    var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
                    var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
                    return restType && getIndexTypeOfType(restType, 1 /* Number */);
                }
                return undefined;
            }
            function getSignatureInstantiation(signature, typeArguments, isJavascript) {
                return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
            }
            function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
                var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
                var id = getTypeListId(typeArguments);
                var instantiation = instantiations.get(id);
                if (!instantiation) {
                    instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
                }
                return instantiation;
            }
            function createSignatureInstantiation(signature, typeArguments) {
                return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
            }
            function createSignatureTypeMapper(signature, typeArguments) {
                return createTypeMapper(signature.typeParameters, typeArguments);
            }
            function getErasedSignature(signature) {
                return signature.typeParameters ?
                    signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
                    signature;
            }
            function createErasedSignature(signature) {
                // Create an instantiation of the signature where all type arguments are the any type.
                return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
            }
            function getCanonicalSignature(signature) {
                return signature.typeParameters ?
                    signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
                    signature;
            }
            function createCanonicalSignature(signature) {
                // Create an instantiation of the signature where each unconstrained type parameter is replaced with
                // its original. When a generic class or interface is instantiated, each generic method in the class or
                // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
                // where different generations of the same type parameter are in scope). This leads to a lot of new type
                // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
                // that uses the original type identities for all unconstrained type parameters.
                return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
            }
            function getBaseSignature(signature) {
                var typeParameters = signature.typeParameters;
                if (typeParameters) {
                    var typeEraser_1 = createTypeEraser(typeParameters);
                    var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; });
                    return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
                }
                return signature;
            }
            function getOrCreateTypeFromSignature(signature) {
                // There are two ways to declare a construct signature, one is by declaring a class constructor
                // using the constructor keyword, and the other is declaring a bare construct signature in an
                // object type literal or interface (using the new keyword). Each way of declaring a constructor
                // will result in a different declaration kind.
                if (!signature.isolatedSignatureType) {
                    var isConstructor = signature.declaration.kind === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217
                    var type = createObjectType(16 /* Anonymous */);
                    type.members = emptySymbols;
                    type.properties = ts.emptyArray;
                    type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
                    type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
                    signature.isolatedSignatureType = type;
                }
                return signature.isolatedSignatureType;
            }
            function getIndexSymbol(symbol) {
                return symbol.members.get("__index" /* Index */);
            }
            function getIndexDeclarationOfSymbol(symbol, kind) {
                var syntaxKind = kind === 1 /* Number */ ? 134 /* NumberKeyword */ : 137 /* StringKeyword */;
                var indexSymbol = getIndexSymbol(symbol);
                if (indexSymbol) {
                    for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
                        if (node.parameters.length === 1) {
                            var parameter = node.parameters[0];
                            if (parameter.type && parameter.type.kind === syntaxKind) {
                                return node;
                            }
                        }
                    }
                }
                return undefined;
            }
            function createIndexInfo(type, isReadonly, declaration) {
                return { type: type, isReadonly: isReadonly, declaration: declaration };
            }
            function getIndexInfoOfSymbol(symbol, kind) {
                var declaration = getIndexDeclarationOfSymbol(symbol, kind);
                if (declaration) {
                    return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
                }
                return undefined;
            }
            function getConstraintDeclaration(type) {
                var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */);
                return decl && ts.getEffectiveConstraintOfTypeParameter(decl);
            }
            function getInferredTypeParameterConstraint(typeParameter) {
                var inferences;
                if (typeParameter.symbol) {
                    for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
                        var declaration = _a[_i];
                        if (declaration.parent.kind === 174 /* InferType */) {
                            // When an 'infer T' declaration is immediately contained in a type reference node
                            // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
                            // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
                            // present, we form an intersection of the inferred constraint types.
                            var grandParent = declaration.parent.parent;
                            if (grandParent.kind === 162 /* TypeReference */) {
                                var typeReference = grandParent;
                                var typeParameters = getTypeParametersForTypeReference(typeReference);
                                if (typeParameters) {
                                    var index = typeReference.typeArguments.indexOf(declaration.parent);
                                    if (index < typeParameters.length) {
                                        var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
                                        if (declaredConstraint) {
                                            // Type parameter constraints can reference other type parameters so
                                            // constraints need to be instantiated. If instantiation produces the
                                            // type parameter itself, we discard that inference. For example, in
                                            //   type Foo<T extends string, U extends T> = [T, U];
                                            //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
                                            // the instantiated constraint for U is X, so we discard that inference.
                                            var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
                                            var constraint = instantiateType(declaredConstraint, mapper);
                                            if (constraint !== typeParameter) {
                                                inferences = ts.append(inferences, constraint);
                                            }
                                        }
                                    }
                                }
                            }
                            // When an 'infer T' declaration is immediately contained in a rest parameter
                            // declaration, we infer an 'unknown[]' constraint.
                            else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) {
                                inferences = ts.append(inferences, createArrayType(unknownType));
                            }
                        }
                    }
                }
                return inferences && getIntersectionType(inferences);
            }
            /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
            function getConstraintFromTypeParameter(typeParameter) {
                if (!typeParameter.constraint) {
                    if (typeParameter.target) {
                        var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
                        typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
                    }
                    else {
                        var constraintDeclaration = getConstraintDeclaration(typeParameter);
                        typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) :
                            getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
                    }
                }
                return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
            }
            function getParentSymbolOfTypeParameter(typeParameter) {
                var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */);
                var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
                return host && getSymbolOfNode(host);
            }
            function getTypeListId(types) {
                var result = "";
                if (types) {
                    var length_3 = types.length;
                    var i = 0;
                    while (i < length_3) {
                        var startId = types[i].id;
                        var count = 1;
                        while (i + count < length_3 && types[i + count].id === startId + count) {
                            count++;
                        }
                        if (result.length) {
                            result += ",";
                        }
                        result += startId;
                        if (count > 1) {
                            result += ":" + count;
                        }
                        i += count;
                    }
                }
                return result;
            }
            // This function is used to propagate certain flags when creating new object type references and union types.
            // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
            // of an object literal or the anyFunctionType. This is because there are operations in the type checker
            // that care about the presence of such types at arbitrary depth in a containing type.
            function getPropagatingFlagsOfTypes(types, excludeKinds) {
                var result = 0;
                for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
                    var type = types_5[_i];
                    if (!(type.flags & excludeKinds)) {
                        result |= type.flags;
                    }
                }
                return result & 939524096 /* PropagatingFlags */;
            }
            function createTypeReference(target, typeArguments) {
                var id = getTypeListId(typeArguments);
                var type = target.instantiations.get(id);
                if (!type) {
                    type = createObjectType(4 /* Reference */, target.symbol);
                    target.instantiations.set(id, type);
                    type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
                    type.target = target;
                    type.typeArguments = typeArguments;
                }
                return type;
            }
            function cloneTypeReference(source) {
                var type = createType(source.flags);
                type.symbol = source.symbol;
                type.objectFlags = source.objectFlags;
                type.target = source.target;
                type.typeArguments = source.typeArguments;
                return type;
            }
            function getTypeReferenceArity(type) {
                return ts.length(type.target.typeParameters);
            }
            /**
             * Get type from type-reference that reference to class or interface
             */
            function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) {
                var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
                var typeParameters = type.localTypeParameters;
                if (typeParameters) {
                    var numTypeArguments = ts.length(node.typeArguments);
                    var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
                    var isJs = ts.isInJSFile(node);
                    var isJsImplicitAny = !noImplicitAny && isJs;
                    if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
                        var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */;
                        var diag = minTypeArgumentCount === typeParameters.length
                            ? missingAugmentsTag
                                ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag
                                : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s
                            : missingAugmentsTag
                                ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag
                                : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
                        var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
                        error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
                        if (!isJs) {
                            // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
                            return errorType;
                        }
                    }
                    // In a type reference, the outer type parameters of the referenced class or interface are automatically
                    // supplied as type arguments and the type reference only specifies arguments for the local type parameters
                    // of the class or interface.
                    var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs));
                    return createTypeReference(type, typeArguments);
                }
                return checkNoTypeArguments(node, symbol) ? type : errorType;
            }
            function getTypeAliasInstantiation(symbol, typeArguments) {
                var type = getDeclaredTypeOfSymbol(symbol);
                var links = getSymbolLinks(symbol);
                var typeParameters = links.typeParameters;
                var id = getTypeListId(typeArguments);
                var instantiation = links.instantiations.get(id);
                if (!instantiation) {
                    links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
                }
                return instantiation;
            }
            /**
             * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
             * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
             * declared type. Instantiations are cached using the type identities of the type arguments as the key.
             */
            function getTypeFromTypeAliasReference(node, symbol, typeArguments) {
                var type = getDeclaredTypeOfSymbol(symbol);
                var typeParameters = getSymbolLinks(symbol).typeParameters;
                if (typeParameters) {
                    var numTypeArguments = ts.length(node.typeArguments);
                    var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
                    if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
                        error(node, minTypeArgumentCount === typeParameters.length
                            ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s
                            : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
                        return errorType;
                    }
                    return getTypeAliasInstantiation(symbol, typeArguments);
                }
                return checkNoTypeArguments(node, symbol) ? type : errorType;
            }
            function getTypeReferenceName(node) {
                switch (node.kind) {
                    case 162 /* TypeReference */:
                        return node.typeName;
                    case 209 /* ExpressionWithTypeArguments */:
                        // We only support expressions that are simple qualified names. For other
                        // expressions this produces undefined.
                        var expr = node.expression;
                        if (ts.isEntityNameExpression(expr)) {
                            return expr;
                        }
                    // fall through;
                }
                return undefined;
            }
            function resolveTypeReferenceName(typeReferenceName, meaning) {
                if (!typeReferenceName) {
                    return unknownSymbol;
                }
                return resolveEntityName(typeReferenceName, meaning) || unknownSymbol;
            }
            function getTypeReferenceType(node, symbol) {
                var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced.
                if (symbol === unknownSymbol) {
                    return errorType;
                }
                var type = getTypeReferenceTypeWorker(node, symbol, typeArguments);
                if (type) {
                    return type;
                }
                // JS enums are 'string' or 'number', not an enum type.
                var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration);
                if (enumTag) {
                    var links = getNodeLinks(enumTag);
                    if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) {
                        return errorType;
                    }
                    var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType;
                    if (!popTypeResolution()) {
                        type_4 = errorType;
                        error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol));
                    }
                    return (links.resolvedEnumType = type_4);
                }
                // Get type from reference to named type that cannot be generic (enum or type parameter)
                var res = tryGetDeclaredTypeOfSymbol(symbol);
                if (res) {
                    return checkNoTypeArguments(node, symbol) ?
                        res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) :
                        errorType;
                }
                if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) {
                    return errorType;
                }
                var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
                if (jsdocType) {
                    return jsdocType;
                }
                // Resolve the type reference as a Type for the purpose of reporting errors.
                resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */);
                return getTypeOfSymbol(symbol);
            }
            /**
             * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If
             * the symbol is a constructor function, return the inferred class type; otherwise,
             * the type of this reference is just the type of the value we resolved to.
             */
            function getJSDocTypeReference(node, symbol, typeArguments) {
                if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) {
                    return errorType;
                }
                var assignedType = getAssignedClassType(symbol);
                var valueType = getTypeOfSymbol(symbol);
                var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments);
                if (!popTypeResolution()) {
                    getSymbolLinks(symbol).resolvedJSDocType = errorType;
                    error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol));
                    return errorType;
                }
                if (referenceType || assignedType) {
                    // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?)
                    var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType);
                    return getSymbolLinks(symbol).resolvedJSDocType = type;
                }
            }
            function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
                if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
                    if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
                        var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
                        if (jsdocType) {
                            return jsdocType;
                        }
                    }
                    return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments);
                }
                if (symbol.flags & 524288 /* TypeAlias */) {
                    return getTypeFromTypeAliasReference(node, symbol, typeArguments);
                }
                if (symbol.flags & 16 /* Function */ &&
                    isJSDocTypeReference(node) &&
                    (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) {
                    return getInferredClassType(symbol);
                }
            }
            function getSubstitutionType(typeVariable, substitute) {
                var result = createType(8388608 /* Substitution */);
                result.typeVariable = typeVariable;
                result.substitute = substitute;
                return result;
            }
            function isUnaryTupleTypeNode(node) {
                return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1;
            }
            function getImpliedConstraint(typeVariable, checkNode, extendsNode) {
                return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
                    getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) :
                        undefined;
            }
            function getConstrainedTypeVariable(typeVariable, node) {
                var constraints;
                while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) {
                    var parent = node.parent;
                    if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) {
                        var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
                        if (constraint) {
                            constraints = ts.append(constraints, constraint);
                        }
                    }
                    node = parent;
                }
                return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable;
            }
            function isJSDocTypeReference(node) {
                return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */);
            }
            function checkNoTypeArguments(node, symbol) {
                if (node.typeArguments) {
                    error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)");
                    return false;
                }
                return true;
            }
            function getIntendedTypeFromJSDocTypeReference(node) {
                if (ts.isIdentifier(node.typeName)) {
                    var typeArgs = node.typeArguments;
                    switch (node.typeName.escapedText) {
                        case "String":
                            checkNoTypeArguments(node);
                            return stringType;
                        case "Number":
                            checkNoTypeArguments(node);
                            return numberType;
                        case "Boolean":
                            checkNoTypeArguments(node);
                            return booleanType;
                        case "Void":
                            checkNoTypeArguments(node);
                            return voidType;
                        case "Undefined":
                            checkNoTypeArguments(node);
                            return undefinedType;
                        case "Null":
                            checkNoTypeArguments(node);
                            return nullType;
                        case "Function":
                        case "function":
                            checkNoTypeArguments(node);
                            return globalFunctionType;
                        case "Array":
                        case "array":
                            return !typeArgs || !typeArgs.length ? anyArrayType : undefined;
                        case "Promise":
                        case "promise":
                            return !typeArgs || !typeArgs.length ? createPromiseType(anyType) : undefined;
                        case "Object":
                            if (typeArgs && typeArgs.length === 2) {
                                if (ts.isJSDocIndexSignature(node)) {
                                    var indexed = getTypeFromTypeNode(typeArgs[0]);
                                    var target = getTypeFromTypeNode(typeArgs[1]);
                                    var index = createIndexInfo(target, /*isReadonly*/ false);
                                    return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
                                }
                                return anyType;
                            }
                            checkNoTypeArguments(node);
                            return anyType;
                    }
                }
            }
            function getTypeFromJSDocNullableTypeNode(node) {
                var type = getTypeFromTypeNode(node.type);
                return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type;
            }
            function getTypeFromTypeReference(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    var symbol = void 0;
                    var type = void 0;
                    var meaning = 67897832 /* Type */;
                    if (isJSDocTypeReference(node)) {
                        type = getIntendedTypeFromJSDocTypeReference(node);
                        meaning |= 67220415 /* Value */;
                    }
                    if (!type) {
                        symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
                        type = getTypeReferenceType(node, symbol);
                    }
                    // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
                    // type reference in checkTypeReferenceNode.
                    links.resolvedSymbol = symbol;
                    links.resolvedType = type;
                }
                return links.resolvedType;
            }
            function typeArgumentsFromTypeReferenceNode(node) {
                return ts.map(node.typeArguments, getTypeFromTypeNode);
            }
            function getTypeFromTypeQueryNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    // TypeScript 1.0 spec (April 2014): 3.6.3
                    // The expression is processed as an identifier expression (section 4.3)
                    // or property access expression(section 4.10),
                    // the widened type(section 3.9) of which becomes the result.
                    links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
                }
                return links.resolvedType;
            }
            function getTypeOfGlobalSymbol(symbol, arity) {
                function getTypeDeclaration(symbol) {
                    var declarations = symbol.declarations;
                    for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
                        var declaration = declarations_3[_i];
                        switch (declaration.kind) {
                            case 238 /* ClassDeclaration */:
                            case 239 /* InterfaceDeclaration */:
                            case 241 /* EnumDeclaration */:
                                return declaration;
                        }
                    }
                }
                if (!symbol) {
                    return arity ? emptyGenericType : emptyObjectType;
                }
                var type = getDeclaredTypeOfSymbol(symbol);
                if (!(type.flags & 131072 /* Object */)) {
                    error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
                    return arity ? emptyGenericType : emptyObjectType;
                }
                if (ts.length(type.typeParameters) !== arity) {
                    error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
                    return arity ? emptyGenericType : emptyObjectType;
                }
                return type;
            }
            function getGlobalValueSymbol(name, reportErrors) {
                return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
            }
            function getGlobalTypeSymbol(name, reportErrors) {
                return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
            }
            function getGlobalSymbol(name, meaning, diagnostic) {
                // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
                return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
            }
            function getGlobalType(name, arity, reportErrors) {
                var symbol = getGlobalTypeSymbol(name, reportErrors);
                return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
            }
            function getGlobalTypedPropertyDescriptorType() {
                return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
            }
            function getGlobalTemplateStringsArrayType() {
                return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
            }
            function getGlobalImportMetaType() {
                return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
            }
            function getGlobalESSymbolConstructorSymbol(reportErrors) {
                return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
            }
            function getGlobalESSymbolType(reportErrors) {
                return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
            }
            function getGlobalPromiseType(reportErrors) {
                return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
            }
            function getGlobalPromiseConstructorSymbol(reportErrors) {
                return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
            }
            function getGlobalPromiseConstructorLikeType(reportErrors) {
                return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
            }
            function getGlobalAsyncIterableType(reportErrors) {
                return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
            }
            function getGlobalAsyncIteratorType(reportErrors) {
                return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
            }
            function getGlobalAsyncIterableIteratorType(reportErrors) {
                return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
            }
            function getGlobalIterableType(reportErrors) {
                return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
            }
            function getGlobalIteratorType(reportErrors) {
                return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
            }
            function getGlobalIterableIteratorType(reportErrors) {
                return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
            }
            function getGlobalTypeOrUndefined(name, arity) {
                if (arity === void 0) {
                    arity = 0;
                }
                var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined);
                return symbol && getTypeOfGlobalSymbol(symbol, arity);
            }
            function getGlobalExtractSymbol() {
                return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
            }
            /**
             * Instantiates a global type that is generic with some element type, and returns that instantiation.
             */
            function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
                return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
            }
            function createTypedPropertyDescriptorType(propertyType) {
                return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
            }
            function createAsyncIterableType(iteratedType) {
                return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]);
            }
            function createAsyncIterableIteratorType(iteratedType) {
                return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
            }
            function createIterableType(iteratedType) {
                return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
            }
            function createIterableIteratorType(iteratedType) {
                return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
            }
            function createArrayType(elementType) {
                return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
            }
            function createReadonlyArrayType(elementType) {
                return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
            }
            function getTypeFromArrayTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
                }
                return links.resolvedType;
            }
            // We represent tuple types as type references to synthesized generic interface types created by
            // this function. The types are of the form:
            //
            //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
            //
            // Note that the generic type created by this function has no symbol associated with it. The same
            // is true for each of the synthesized type parameters.
            function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
                var typeParameters;
                var properties = [];
                var maxLength = hasRestElement ? arity - 1 : arity;
                if (arity) {
                    typeParameters = new Array(arity);
                    for (var i = 0; i < arity; i++) {
                        var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */);
                        if (i < maxLength) {
                            var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i);
                            property.type = typeParameter;
                            properties.push(property);
                        }
                    }
                }
                var literalTypes = [];
                for (var i = minLength; i <= maxLength; i++)
                    literalTypes.push(getLiteralType(i));
                var lengthSymbol = createSymbol(4 /* Property */, "length");
                lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
                properties.push(lengthSymbol);
                var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
                type.typeParameters = typeParameters;
                type.outerTypeParameters = undefined;
                type.localTypeParameters = typeParameters;
                type.instantiations = ts.createMap();
                type.instantiations.set(getTypeListId(type.typeParameters), type);
                type.target = type;
                type.typeArguments = type.typeParameters;
                type.thisType = createType(65536 /* TypeParameter */);
                type.thisType.isThisType = true;
                type.thisType.constraint = type;
                type.declaredProperties = properties;
                type.declaredCallSignatures = ts.emptyArray;
                type.declaredConstructSignatures = ts.emptyArray;
                type.declaredStringIndexInfo = undefined;
                type.declaredNumberIndexInfo = undefined;
                type.minLength = minLength;
                type.hasRestElement = hasRestElement;
                type.associatedNames = associatedNames;
                return type;
            }
            function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
                var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
                var type = tupleTypes.get(key);
                if (!type) {
                    tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
                }
                return type;
            }
            function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
                if (minLength === void 0) {
                    minLength = elementTypes.length;
                }
                if (hasRestElement === void 0) {
                    hasRestElement = false;
                }
                var arity = elementTypes.length;
                if (arity === 1 && hasRestElement) {
                    return createArrayType(elementTypes[0]);
                }
                var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
                return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
            }
            function getTypeFromTupleTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    var lastElement = ts.lastOrUndefined(node.elementTypes);
                    var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined;
                    var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1;
                    var elementTypes = ts.map(node.elementTypes, function (n) {
                        var type = getTypeFromTypeNode(n);
                        return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
                    });
                    links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
                }
                return links.resolvedType;
            }
            function getTypeFromOptionalTypeNode(node) {
                var type = getTypeFromTypeNode(node.type);
                return strictNullChecks ? getOptionalType(type) : type;
            }
            function getTypeId(type) {
                return type.id;
            }
            function containsType(types, type) {
                return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
            }
            function insertType(types, type) {
                var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
                if (index < 0) {
                    types.splice(~index, 0, type);
                    return true;
                }
                return false;
            }
            // Return true if the given intersection type contains
            // more than one unit type or,
            // an object type and a nullable type (null or undefined), or
            // a string-like type and a type known to be non-string-like, or
            // a number-like type and a type known to be non-number-like, or
            // a symbol-like type and a type known to be non-symbol-like, or
            // a void-like type and a type known to be non-void-like, or
            // a non-primitive type and a type known to be primitive.
            function isEmptyIntersectionType(type) {
                var combined = 0;
                for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
                    var t = _a[_i];
                    if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) {
                        return true;
                    }
                    combined |= t.flags;
                    if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) ||
                        combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) ||
                        combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) ||
                        combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) ||
                        combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) ||
                        combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) {
                        return true;
                    }
                }
                return false;
            }
            function addTypeToUnion(typeSet, includes, type) {
                var flags = type.flags;
                if (flags & 262144 /* Union */) {
                    return addTypesToUnion(typeSet, includes, type.types);
                }
                // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are
                // another form of 'never' (in that they have an empty value domain). We could in theory turn
                // intersections of unit types into 'never' upon construction, but deferring the reduction makes it
                // easier to reason about their origin.
                if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) {
                    includes |= flags & ~939524096 /* ConstructionFlags */;
                    if (flags & 3 /* AnyOrUnknown */) {
                        if (type === wildcardType)
                            includes |= 268435456 /* Wildcard */;
                    }
                    else if (!strictNullChecks && flags & 24576 /* Nullable */) {
                        if (!(flags & 134217728 /* ContainsWideningType */))
                            includes |= 134217728 /* NonWideningType */;
                    }
                    else {
                        var len = typeSet.length;
                        var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
                        if (index < 0) {
                            typeSet.splice(~index, 0, type);
                        }
                    }
                }
                return includes;
            }
            // Add the given types to the given type set. Order is preserved, duplicates are removed,
            // and nested types of the given kind are flattened into the set.
            function addTypesToUnion(typeSet, includes, types) {
                for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
                    var type = types_6[_i];
                    includes = addTypeToUnion(typeSet, includes, type);
                }
                return includes;
            }
            function isSubtypeOfAny(source, targets) {
                for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
                    var target = targets_1[_i];
                    if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
                        !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
                        isTypeDerivedFrom(source, target))) {
                        return true;
                    }
                }
                return false;
            }
            function isSetOfLiteralsFromSameEnum(types) {
                var first = types[0];
                if (first.flags & 512 /* EnumLiteral */) {
                    var firstEnum = getParentOfSymbol(first.symbol);
                    for (var i = 1; i < types.length; i++) {
                        var other = types[i];
                        if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
                            return false;
                        }
                    }
                    return true;
                }
                return false;
            }
            function removeSubtypes(types) {
                if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
                    return;
                }
                var i = types.length;
                while (i > 0) {
                    i--;
                    if (isSubtypeOfAny(types[i], types)) {
                        ts.orderedRemoveItemAt(types, i);
                    }
                }
            }
            function removeRedundantLiteralTypes(types, includes) {
                var i = types.length;
                while (i > 0) {
                    i--;
                    var t = types[i];
                    var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ ||
                        t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ ||
                        t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ ||
                        t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType);
                    if (remove) {
                        ts.orderedRemoveItemAt(types, i);
                    }
                }
            }
            // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
            // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
            // of other types. Subtype reduction is expensive for large union types and is possible only when union
            // types are known not to circularly reference themselves (as is the case with union types created by
            // expression constructs such as array literals and the || and ?: operators). Named types can
            // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
            // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
            function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
                if (unionReduction === void 0) {
                    unionReduction = 1 /* Literal */;
                }
                if (types.length === 0) {
                    return neverType;
                }
                if (types.length === 1) {
                    return types[0];
                }
                var typeSet = [];
                var includes = addTypesToUnion(typeSet, 0, types);
                if (includes & 3 /* AnyOrUnknown */) {
                    return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType;
                }
                switch (unionReduction) {
                    case 1 /* Literal */:
                        if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) {
                            removeRedundantLiteralTypes(typeSet, includes);
                        }
                        break;
                    case 2 /* Subtype */:
                        removeSubtypes(typeSet);
                        break;
                }
                if (typeSet.length === 0) {
                    return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType :
                        includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType :
                            neverType;
                }
                return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments);
            }
            function getUnionTypePredicate(signatures) {
                var first;
                var types = [];
                for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
                    var sig = signatures_2[_i];
                    var pred = getTypePredicateOfSignature(sig);
                    if (!pred) {
                        continue;
                    }
                    if (first) {
                        if (!typePredicateKindsMatch(first, pred)) {
                            // No common type predicate.
                            return undefined;
                        }
                    }
                    else {
                        first = pred;
                    }
                    types.push(pred.type);
                }
                if (!first) {
                    // No union signatures had a type predicate.
                    return undefined;
                }
                var unionType = getUnionType(types);
                return ts.isIdentifierTypePredicate(first)
                    ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType)
                    : createThisTypePredicate(unionType);
            }
            function typePredicateKindsMatch(a, b) {
                return ts.isIdentifierTypePredicate(a)
                    ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex
                    : !ts.isIdentifierTypePredicate(b);
            }
            // This function assumes the constituent type list is sorted and deduplicated.
            function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) {
                if (types.length === 0) {
                    return neverType;
                }
                if (types.length === 1) {
                    return types[0];
                }
                var id = getTypeListId(types);
                var type = unionTypes.get(id);
                if (!type) {
                    var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */);
                    type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes);
                    unionTypes.set(id, type);
                    type.types = types;
                    /*
                    Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
                    For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
                    (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
                    It's important that we create equivalent union types only once, so that's an unfortunate side effect.
                    */
                    type.aliasSymbol = aliasSymbol;
                    type.aliasTypeArguments = aliasTypeArguments;
                }
                return type;
            }
            function getTypeFromUnionTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    var aliasSymbol = getAliasSymbolForTypeNode(node);
                    links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
                }
                return links.resolvedType;
            }
            function addTypeToIntersection(typeSet, includes, type) {
                var flags = type.flags;
                if (flags & 524288 /* Intersection */) {
                    return addTypesToIntersection(typeSet, includes, type.types);
                }
                if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) {
                    includes |= 536870912 /* EmptyObject */;
                }
                else {
                    includes |= flags & ~939524096 /* ConstructionFlags */;
                    if (flags & 3 /* AnyOrUnknown */) {
                        if (type === wildcardType)
                            includes |= 268435456 /* Wildcard */;
                    }
                    else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) {
                        typeSet.push(type);
                    }
                }
                return includes;
            }
            // Add the given types to the given type set. Order is preserved, freshness is removed from literal
            // types, duplicates are removed, and nested types of the given kind are flattened into the set.
            function addTypesToIntersection(typeSet, includes, types) {
                for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
                    var type = types_7[_i];
                    includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
                }
                return includes;
            }
            function removeRedundantPrimitiveTypes(types, includes) {
                var i = types.length;
                while (i > 0) {
                    i--;
                    var t = types[i];
                    var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ ||
                        t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ ||
                        t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */;
                    if (remove) {
                        ts.orderedRemoveItemAt(types, i);
                    }
                }
            }
            // Check that the given type has a match in every union. A given type is matched by
            // an identical type, and a literal type is additionally matched by its corresponding
            // primitive type.
            function eachUnionContains(unionTypes, type) {
                for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
                    var u = unionTypes_1[_i];
                    if (!containsType(u.types, type)) {
                        var primitive = type.flags & 64 /* StringLiteral */ ? stringType :
                            type.flags & 128 /* NumberLiteral */ ? numberType :
                                type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType :
                                    undefined;
                        if (!primitive || !containsType(u.types, primitive)) {
                            return false;
                        }
                    }
                }
                return true;
            }
            // If the given list of types contains more than one union of primitive types, replace the
            // first with a union containing an intersection of those primitive types, then remove the
            // other unions and return true. Otherwise, do nothing and return false.
            function intersectUnionsOfPrimitiveTypes(types) {
                var unionTypes;
                var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; });
                var i = index + 1;
                // Remove all but the first union of primitive types and collect them in
                // the unionTypes array.
                while (i < types.length) {
                    var t = types[i];
                    if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) {
                        (unionTypes || (unionTypes = [types[index]])).push(t);
                        ts.orderedRemoveItemAt(types, i);
                    }
                    else {
                        i++;
                    }
                }
                // Return false if there was only one union of primitive types
                if (!unionTypes) {
                    return false;
                }
                // We have more than one union of primitive types, now intersect them. For each
                // type in each union we check if the type is matched in every union and if so
                // we include it in the result.
                var checked = [];
                var result = [];
                for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
                    var u = unionTypes_2[_i];
                    for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
                        var t = _b[_a];
                        if (insertType(checked, t)) {
                            if (eachUnionContains(unionTypes, t)) {
                                insertType(result, t);
                            }
                        }
                    }
                }
                // Finally replace the first union with the result
                types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */);
                return true;
            }
            // We normalize combinations of intersection and union types based on the distributive property of the '&'
            // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
            // types with union type constituents into equivalent union types with intersection type constituents and
            // effectively ensure that union types are always at the top level in type representations.
            //
            // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
            // type operator and we can't reduce those because we want to support recursive intersection types. For example,
            // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
            // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
            // for intersections of types with signatures can be deterministic.
            function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
                var typeSet = [];
                var includes = addTypesToIntersection(typeSet, 0, types);
                if (includes & 32768 /* Never */) {
                    return neverType;
                }
                if (includes & 1 /* Any */) {
                    return includes & 268435456 /* Wildcard */ ? wildcardType : anyType;
                }
                if (!strictNullChecks && includes & 24576 /* Nullable */) {
                    return includes & 8192 /* Undefined */ ? undefinedType : nullType;
                }
                if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ ||
                    includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ ||
                    includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) {
                    removeRedundantPrimitiveTypes(typeSet, includes);
                }
                if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) {
                    typeSet.push(emptyObjectType);
                }
                if (typeSet.length === 0) {
                    return unknownType;
                }
                if (typeSet.length === 1) {
                    return typeSet[0];
                }
                if (includes & 262144 /* Union */) {
                    if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) {
                        // When the intersection creates a reduced set (which might mean that *all* union types have
                        // disappeared), we restart the operation to get a new set of combined flags. Once we have
                        // reduced we'll never reduce again, so this occurs at most once.
                        return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
                    }
                    // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
                    // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
                    var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; });
                    var unionType = typeSet[unionIndex_1];
                    return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
                }
                var id = getTypeListId(typeSet);
                var type = intersectionTypes.get(id);
                if (!type) {
                    var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */);
                    type = createType(524288 /* Intersection */ | propagatedFlags);
                    intersectionTypes.set(id, type);
                    type.types = typeSet;
                    type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
                    type.aliasTypeArguments = aliasTypeArguments;
                }
                return type;
            }
            function getTypeFromIntersectionTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    var aliasSymbol = getAliasSymbolForTypeNode(node);
                    links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
                }
                return links.resolvedType;
            }
            function createIndexType(type, stringsOnly) {
                var result = createType(1048576 /* Index */);
                result.type = type;
                result.stringsOnly = stringsOnly;
                return result;
            }
            function getIndexTypeForGenericType(type, stringsOnly) {
                return stringsOnly ?
                    type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
                    type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
            }
            function getLiteralTypeFromPropertyName(prop, include) {
                if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
                    var type = getLateBoundSymbol(prop).nameType;
                    if (!type && !ts.isKnownSymbol(prop)) {
                        var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
                        type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) :
                            name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) :
                                getLiteralType(ts.symbolName(prop));
                    }
                    if (type && type.flags & include) {
                        return type;
                    }
                }
                return neverType;
            }
            function getLiteralTypeFromPropertyNames(type, include) {
                return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); }));
            }
            function getNonEnumNumberIndexInfo(type) {
                var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
                return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
            }
            function getIndexType(type, stringsOnly) {
                if (stringsOnly === void 0) {
                    stringsOnly = keyofStringsOnly;
                }
                return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) :
                    type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) :
                        maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
                            ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
                                type === wildcardType ? wildcardType :
                                    type.flags & 1 /* Any */ ? keyofConstraintType :
                                        stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) :
                                            getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) :
                                                getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) :
                                                    getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */);
            }
            function getExtractStringType(type) {
                if (keyofStringsOnly) {
                    return type;
                }
                var extractTypeAlias = getGlobalExtractSymbol();
                return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
            }
            function getIndexTypeOrString(type) {
                var indexType = getExtractStringType(getIndexType(type));
                return indexType.flags & 32768 /* Never */ ? stringType : indexType;
            }
            function getTypeFromTypeOperatorNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    switch (node.operator) {
                        case 128 /* KeyOfKeyword */:
                            links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
                            break;
                        case 141 /* UniqueKeyword */:
                            links.resolvedType = node.type.kind === 138 /* SymbolKeyword */
                                ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
                                : errorType;
                            break;
                    }
                }
                return links.resolvedType; // TODO: GH#18217
            }
            function createIndexedAccessType(objectType, indexType) {
                var type = createType(2097152 /* IndexedAccess */);
                type.objectType = objectType;
                type.indexType = indexType;
                return type;
            }
            /**
             * Returns if a type is or consists of a JSLiteral object type
             * In addition to objects which are directly literals,
             * * unions where every element is a jsliteral
             * * intersections where at least one element is a jsliteral
             * * and instantiable types constrained to a jsliteral
             * Should all count as literals and not print errors on access or assignment of possibly existing properties.
             * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
             */
            function isJSLiteralType(type) {
                if (noImplicitAny) {
                    return false; // Flag is meaningless under `noImplicitAny` mode
                }
                if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
                    return true;
                }
                if (type.flags & 262144 /* Union */) {
                    return ts.every(type.types, isJSLiteralType);
                }
                if (type.flags & 524288 /* Intersection */) {
                    return ts.some(type.types, isJSLiteralType);
                }
                if (type.flags & 15794176 /* Instantiable */) {
                    return isJSLiteralType(getResolvedBaseConstraint(type));
                }
                return false;
            }
            function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) {
                var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined;
                var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) :
                    accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
                        ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
                        undefined;
                if (propName !== undefined) {
                    var prop = getPropertyOfType(objectType, propName);
                    if (prop) {
                        if (accessExpression) {
                            markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */);
                            if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) {
                                error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop));
                                return missingType;
                            }
                            if (cacheSymbol) {
                                getNodeLinks(accessNode).resolvedSymbol = prop;
                            }
                        }
                        var propType = getTypeOfSymbol(prop);
                        return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType;
                    }
                    if (isTupleType(objectType)) {
                        var restType = getRestTypeOfTupleType(objectType);
                        if (restType && isNumericLiteralName(propName) && +propName >= 0) {
                            return restType;
                        }
                    }
                }
                if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) {
                    if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) {
                        return objectType;
                    }
                    var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) ||
                        getIndexInfoOfType(objectType, 0 /* String */) ||
                        undefined;
                    if (indexInfo) {
                        if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
                            var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType;
                            error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
                        }
                        else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
                            error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
                        }
                        return indexInfo.type;
                    }
                    if (indexType.flags & 32768 /* Never */) {
                        return neverType;
                    }
                    if (isJSLiteralType(objectType)) {
                        return anyType;
                    }
                    if (accessExpression && !isConstEnumObjectType(objectType)) {
                        if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
                            if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
                                error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
                            }
                            else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
                                error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
                            }
                            else {
                                var suggestion = void 0;
                                if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
                                    if (suggestion !== undefined) {
                                        error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
                                    }
                                }
                                else {
                                    error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType));
                                }
                            }
                        }
                        return missingType;
                    }
                }
                if (isJSLiteralType(objectType)) {
                    return anyType;
                }
                if (accessNode) {
                    var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType;
                    if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) {
                        error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
                    }
                    else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
                        error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
                    }
                    else {
                        error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
                    }
                }
                if (isTypeAny(indexType)) {
                    return indexType;
                }
                return missingType;
            }
            function isGenericObjectType(type) {
                return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
            }
            function isGenericIndexType(type) {
                return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */);
            }
            function getSimplifiedType(type) {
                return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type;
            }
            // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
            // the type itself if no transformation is possible.
            function getSimplifiedIndexedAccessType(type) {
                if (type.simplified) {
                    return type.simplified === circularConstraintType ? type : type.simplified;
                }
                type.simplified = circularConstraintType;
                // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
                // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
                var objectType = getSimplifiedType(type.objectType);
                var indexType = getSimplifiedType(type.indexType);
                // T[A | B] -> T[A] | T[B]
                if (indexType.flags & 262144 /* Union */) {
                    return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); });
                }
                // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
                if (!(indexType.flags & 15794176 /* Instantiable */)) {
                    // (T | U)[K] -> T[K] | U[K]
                    if (objectType.flags & 262144 /* Union */) {
                        return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); });
                    }
                    // (T & U)[K] -> T[K] & U[K]
                    if (objectType.flags & 524288 /* Intersection */) {
                        return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }));
                    }
                }
                // So ultimately:
                // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2]
                // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
                // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
                // construct the type Box<T[X]>. We do not further simplify the result because mapped types can be recursive
                // and we might never terminate.
                if (isGenericMappedType(objectType)) {
                    return type.simplified = substituteIndexedMappedType(objectType, type);
                }
                if (objectType.flags & 65536 /* TypeParameter */) {
                    var constraint = getConstraintOfTypeParameter(objectType);
                    if (constraint && isGenericMappedType(constraint)) {
                        return type.simplified = substituteIndexedMappedType(constraint, type);
                    }
                }
                return type.simplified = type;
            }
            function substituteIndexedMappedType(objectType, type) {
                var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
                var templateMapper = combineTypeMappers(objectType.mapper, mapper);
                return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
            }
            function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
                if (missingType === void 0) {
                    missingType = accessNode ? errorType : unknownType;
                }
                if (objectType === wildcardType || indexType === wildcardType) {
                    return wildcardType;
                }
                // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
                // we are performing a higher-order index access where we cannot meaningfully access the properties of the
                // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
                // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
                // has always been resolved eagerly using the constraint type of 'this' at the given location.
                if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) {
                    if (objectType.flags & 3 /* AnyOrUnknown */) {
                        return objectType;
                    }
                    // Defer the operation by creating an indexed access type.
                    var id = objectType.id + "," + indexType.id;
                    var type = indexedAccessTypes.get(id);
                    if (!type) {
                        indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType));
                    }
                    return type;
                }
                // In the following we resolve T[K] to the type of the property in T selected by K.
                // We treat boolean as different from other unions to improve errors;
                // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
                var apparentObjectType = getApparentType(objectType);
                if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
                    var propTypes = [];
                    var wasMissingProp = false;
                    for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
                        var t = _a[_i];
                        var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType);
                        if (propType === missingType) {
                            if (!accessNode) {
                                // If there's no error node, we can immeditely stop, since error reporting is off
                                return missingType;
                            }
                            else {
                                // Otherwise we set a flag and return at the end of the loop so we still mark all errors
                                wasMissingProp = true;
                            }
                        }
                        propTypes.push(propType);
                    }
                    if (wasMissingProp) {
                        return missingType;
                    }
                    return getUnionType(propTypes);
                }
                return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType);
            }
            function getTypeFromIndexedAccessTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    var objectType = getTypeFromTypeNode(node.objectType);
                    var indexType = getTypeFromTypeNode(node.indexType);
                    var resolved = getIndexedAccessType(objectType, indexType, node);
                    links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ &&
                        resolved.objectType === objectType &&
                        resolved.indexType === indexType ?
                        getConstrainedTypeVariable(resolved, node) : resolved;
                }
                return links.resolvedType;
            }
            function getTypeFromMappedTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    var type = createObjectType(32 /* Mapped */, node.symbol);
                    type.declaration = node;
                    type.aliasSymbol = getAliasSymbolForTypeNode(node);
                    type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
                    links.resolvedType = type;
                    // Eagerly resolve the constraint type which forces an error if the constraint type circularly
                    // references itself through one or more type aliases.
                    getConstraintTypeFromMappedType(type);
                }
                return links.resolvedType;
            }
            function getActualTypeVariable(type) {
                return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type;
            }
            function getConditionalType(root, mapper) {
                var checkType = instantiateType(root.checkType, mapper);
                var extendsType = instantiateType(root.extendsType, mapper);
                if (checkType === wildcardType || extendsType === wildcardType) {
                    return wildcardType;
                }
                // If this is a distributive conditional type and the check type is generic we need to defer
                // resolution of the conditional type such that a later instantiation will properly distribute
                // over union types.
                var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */);
                var combinedMapper;
                if (root.inferTypeParameters) {
                    var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
                    if (!isDeferred) {
                        // We don't want inferences from constraints as they may cause us to eagerly resolve the
                        // conditional type instead of deferring resolution. Also, we always want strict function
                        // types rules (i.e. proper contravariance) for inferences.
                        inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
                    }
                    combinedMapper = combineTypeMappers(mapper, context);
                }
                if (!isDeferred) {
                    if (extendsType.flags & 3 /* AnyOrUnknown */) {
                        return instantiateType(root.trueType, mapper);
                    }
                    // Return union of trueType and falseType for 'any' since it matches anything
                    if (checkType.flags & 1 /* Any */) {
                        return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
                    }
                    // Instantiate the extends type including inferences for 'infer T' type parameters
                    var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
                    // Return falseType for a definitely false extends check. We check an instantations of the two
                    // types with type parameters mapped to the wildcard type, the most permissive instantiations
                    // possible (the wildcard type is assignable to and from all types). If those are not related,
                    // then no instatiations will be and we can just return the false branch type.
                    if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) {
                        return instantiateType(root.falseType, mapper);
                    }
                    // Return trueType for a definitely true extends check. The definitely assignable relation excludes
                    // type variable constraints from consideration. Without the definitely assignable relation, the type
                    //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
                    // would immediately resolve to 'string' instead of being deferred.
                    if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) {
                        return instantiateType(root.trueType, combinedMapper || mapper);
                    }
                }
                // Return a deferred type for a check that is neither definitely true nor definitely false
                var erasedCheckType = getActualTypeVariable(checkType);
                var result = createType(4194304 /* Conditional */);
                result.root = root;
                result.checkType = erasedCheckType;
                result.extendsType = extendsType;
                result.mapper = mapper;
                result.combinedMapper = combinedMapper;
                result.aliasSymbol = root.aliasSymbol;
                result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
                return result;
            }
            function getTrueTypeFromConditionalType(type) {
                return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
            }
            function getFalseTypeFromConditionalType(type) {
                return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
            }
            function getInferTypeParameters(node) {
                var result;
                if (node.locals) {
                    node.locals.forEach(function (symbol) {
                        if (symbol.flags & 262144 /* TypeParameter */) {
                            result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
                        }
                    });
                }
                return result;
            }
            function isPossiblyReferencedInConditionalType(tp, node) {
                if (isTypeParameterPossiblyReferenced(tp, node)) {
                    return true;
                }
                while (node) {
                    if (node.kind === 173 /* ConditionalType */) {
                        if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) {
                            return true;
                        }
                    }
                    node = node.parent;
                }
                return false;
            }
            function getTypeFromConditionalTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    var checkType = getTypeFromTypeNode(node.checkType);
                    var aliasSymbol = getAliasSymbolForTypeNode(node);
                    var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
                    var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
                    var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); });
                    var root = {
                        node: node,
                        checkType: checkType,
                        extendsType: getTypeFromTypeNode(node.extendsType),
                        trueType: getTypeFromTypeNode(node.trueType),
                        falseType: getTypeFromTypeNode(node.falseType),
                        isDistributive: !!(checkType.flags & 65536 /* TypeParameter */),
                        inferTypeParameters: getInferTypeParameters(node),
                        outerTypeParameters: outerTypeParameters,
                        instantiations: undefined,
                        aliasSymbol: aliasSymbol,
                        aliasTypeArguments: aliasTypeArguments
                    };
                    links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
                    if (outerTypeParameters) {
                        root.instantiations = ts.createMap();
                        root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
                    }
                }
                return links.resolvedType;
            }
            function getTypeFromInferTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
                }
                return links.resolvedType;
            }
            function getIdentifierChain(node) {
                if (ts.isIdentifier(node)) {
                    return [node];
                }
                else {
                    return ts.append(getIdentifierChain(node.left), node.right);
                }
            }
            function getTypeFromImportTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
                        error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
                        links.resolvedSymbol = unknownSymbol;
                        return links.resolvedType = errorType;
                    }
                    if (!ts.isLiteralImportTypeNode(node)) {
                        error(node.argument, ts.Diagnostics.String_literal_expected);
                        links.resolvedSymbol = unknownSymbol;
                        return links.resolvedType = errorType;
                    }
                    var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */;
                    // TODO: Future work: support unions/generics/whatever via a deferred import-type
                    var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
                    if (!innerModuleSymbol) {
                        links.resolvedSymbol = unknownSymbol;
                        return links.resolvedType = errorType;
                    }
                    var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
                    if (!ts.nodeIsMissing(node.qualifier)) {
                        var nameStack = getIdentifierChain(node.qualifier);
                        var currentNamespace = moduleSymbol;
                        var current = void 0;
                        while (current = nameStack.shift()) {
                            var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
                            var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
                            if (!next) {
                                error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
                                return links.resolvedType = errorType;
                            }
                            getNodeLinks(current).resolvedSymbol = next;
                            getNodeLinks(current.parent).resolvedSymbol = next;
                            currentNamespace = next;
                        }
                        resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
                    }
                    else {
                        if (moduleSymbol.flags & targetMeaning) {
                            resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
                        }
                        else {
                            var errorMessage = targetMeaning === 67220415 /* Value */
                                ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
                                : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
                            error(node, errorMessage, node.argument.literal.text);
                            links.resolvedSymbol = unknownSymbol;
                            links.resolvedType = errorType;
                        }
                    }
                }
                return links.resolvedType; // TODO: GH#18217
            }
            function resolveImportSymbolType(node, links, symbol, meaning) {
                var resolvedSymbol = resolveSymbol(symbol);
                links.resolvedSymbol = resolvedSymbol;
                if (meaning === 67220415 /* Value */) {
                    return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
                }
                else {
                    return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
                }
            }
            function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    // Deferred resolution of members is handled by resolveObjectTypeMembers
                    var aliasSymbol = getAliasSymbolForTypeNode(node);
                    if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
                        links.resolvedType = emptyTypeLiteralType;
                    }
                    else {
                        var type = createObjectType(16 /* Anonymous */, node.symbol);
                        type.aliasSymbol = aliasSymbol;
                        type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
                        if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
                            type = createArrayType(type);
                        }
                        links.resolvedType = type;
                    }
                }
                return links.resolvedType;
            }
            function getAliasSymbolForTypeNode(node) {
                return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined;
            }
            function getTypeArgumentsForAliasSymbol(symbol) {
                return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
            }
            /**
             * Since the source of spread types are object literals, which are not binary,
             * this function should be called in a left folding style, with left = previous result of getSpreadType
             * and right = the new element to be spread.
             */
            function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
                if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
                    return anyType;
                }
                if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
                    return unknownType;
                }
                if (left.flags & 32768 /* Never */) {
                    return right;
                }
                if (right.flags & 32768 /* Never */) {
                    return left;
                }
                if (left.flags & 262144 /* Union */) {
                    return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
                }
                if (right.flags & 262144 /* Union */) {
                    return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
                }
                if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) {
                    return left;
                }
                var members = ts.createSymbolTable();
                var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
                var stringIndexInfo;
                var numberIndexInfo;
                if (left === emptyObjectType) {
                    // for the first spread element, left === emptyObjectType, so take the right's string indexer
                    stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
                    numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
                }
                else {
                    stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
                    numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
                }
                for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
                    var rightProp = _a[_i];
                    if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
                        skippedPrivateMembers.set(rightProp.escapedName, true);
                    }
                    else if (isSpreadableProperty(rightProp)) {
                        members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp));
                    }
                }
                for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
                    var leftProp = _c[_b];
                    if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
                        continue;
                    }
                    if (members.has(leftProp.escapedName)) {
                        var rightProp = members.get(leftProp.escapedName);
                        var rightType = getTypeOfSymbol(rightProp);
                        if (rightProp.flags & 16777216 /* Optional */) {
                            var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
                            var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
                            var result = createSymbol(flags, leftProp.escapedName);
                            result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]);
                            result.leftSpread = leftProp;
                            result.rightSpread = rightProp;
                            result.declarations = declarations;
                            result.nameType = leftProp.nameType;
                            members.set(leftProp.escapedName, result);
                        }
                    }
                    else {
                        members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp));
                    }
                }
                var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
                spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */;
                spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */);
                return spread;
            }
            /** We approximate own properties as non-methods plus methods that are inside the object literal */
            function isSpreadableProperty(prop) {
                return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */)
                    ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })
                    : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable
            }
            function getNonReadonlySymbol(prop) {
                if (!isReadonlySymbol(prop)) {
                    return prop;
                }
                var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
                var result = createSymbol(flags, prop.escapedName);
                result.type = getTypeOfSymbol(prop);
                result.declarations = prop.declarations;
                result.nameType = prop.nameType;
                result.syntheticOrigin = prop;
                return result;
            }
            function getNonReadonlyIndexSignature(index) {
                if (index && index.isReadonly) {
                    return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
                }
                return index;
            }
            function createLiteralType(flags, value, symbol) {
                var type = createType(flags);
                type.symbol = symbol;
                type.value = value;
                return type;
            }
            function getFreshTypeOfLiteralType(type) {
                if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) {
                    if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already
                        var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol);
                        freshType.regularType = type;
                        type.freshType = freshType;
                    }
                    return type.freshType;
                }
                return type;
            }
            function getRegularTypeOfLiteralType(type) {
                return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType :
                    type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) :
                        type;
            }
            function getLiteralType(value, enumId, symbol) {
                // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
                // where NNN is the text representation of a numeric literal and SSS are the characters
                // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
                // EEE is a unique id for the containing enum type.
                var qualifier = typeof value === "number" ? "#" : "@";
                var key = enumId ? enumId + qualifier + value : qualifier + value;
                var type = literalTypes.get(key);
                if (!type) {
                    var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0);
                    literalTypes.set(key, type = createLiteralType(flags, value, symbol));
                }
                return type;
            }
            function getTypeFromLiteralTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
                }
                return links.resolvedType;
            }
            function createUniqueESSymbolType(symbol) {
                var type = createType(2048 /* UniqueESSymbol */);
                type.symbol = symbol;
                return type;
            }
            function getESSymbolLikeTypeForNode(node) {
                if (ts.isValidESSymbolDeclaration(node)) {
                    var symbol = getSymbolOfNode(node);
                    var links = getSymbolLinks(symbol);
                    return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
                }
                return esSymbolType;
            }
            function getThisType(node) {
                var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
                var parent = container && container.parent;
                if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) {
                    if (!ts.hasModifier(container, 32 /* Static */) &&
                        (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) {
                        return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
                    }
                }
                error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
                return errorType;
            }
            function getTypeFromThisTypeNode(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    links.resolvedType = getThisType(node);
                }
                return links.resolvedType;
            }
            function getTypeFromTypeNode(node) {
                switch (node.kind) {
                    case 119 /* AnyKeyword */:
                    case 282 /* JSDocAllType */:
                    case 283 /* JSDocUnknownType */:
                        return anyType;
                    case 142 /* UnknownKeyword */:
                        return unknownType;
                    case 137 /* StringKeyword */:
                        return stringType;
                    case 134 /* NumberKeyword */:
                        return numberType;
                    case 122 /* BooleanKeyword */:
                        return booleanType;
                    case 138 /* SymbolKeyword */:
                        return esSymbolType;
                    case 105 /* VoidKeyword */:
                        return voidType;
                    case 140 /* UndefinedKeyword */:
                        return undefinedType;
                    case 95 /* NullKeyword */:
                        return nullType;
                    case 131 /* NeverKeyword */:
                        return neverType;
                    case 135 /* ObjectKeyword */:
                        return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType;
                    case 176 /* ThisType */:
                    case 99 /* ThisKeyword */:
                        return getTypeFromThisTypeNode(node);
                    case 180 /* LiteralType */:
                        return getTypeFromLiteralTypeNode(node);
                    case 162 /* TypeReference */:
                        return getTypeFromTypeReference(node);
                    case 161 /* TypePredicate */:
                        return booleanType;
                    case 209 /* ExpressionWithTypeArguments */:
                        return getTypeFromTypeReference(node);
                    case 165 /* TypeQuery */:
                        return getTypeFromTypeQueryNode(node);
                    case 167 /* ArrayType */:
                        return getTypeFromArrayTypeNode(node);
                    case 168 /* TupleType */:
                        return getTypeFromTupleTypeNode(node);
                    case 169 /* OptionalType */:
                        return getTypeFromOptionalTypeNode(node);
                    case 171 /* UnionType */:
                        return getTypeFromUnionTypeNode(node);
                    case 172 /* IntersectionType */:
                        return getTypeFromIntersectionTypeNode(node);
                    case 284 /* JSDocNullableType */:
                        return getTypeFromJSDocNullableTypeNode(node);
                    case 286 /* JSDocOptionalType */:
                        return addOptionality(getTypeFromTypeNode(node.type));
                    case 175 /* ParenthesizedType */:
                    case 170 /* RestType */:
                    case 285 /* JSDocNonNullableType */:
                    case 281 /* JSDocTypeExpression */:
                        return getTypeFromTypeNode(node.type);
                    case 288 /* JSDocVariadicType */:
                        return getTypeFromJSDocVariadicType(node);
                    case 163 /* FunctionType */:
                    case 164 /* ConstructorType */:
                    case 166 /* TypeLiteral */:
                    case 290 /* JSDocTypeLiteral */:
                    case 287 /* JSDocFunctionType */:
                    case 291 /* JSDocSignature */:
                        return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
                    case 177 /* TypeOperator */:
                        return getTypeFromTypeOperatorNode(node);
                    case 178 /* IndexedAccessType */:
                        return getTypeFromIndexedAccessTypeNode(node);
                    case 179 /* MappedType */:
                        return getTypeFromMappedTypeNode(node);
                    case 173 /* ConditionalType */:
                        return getTypeFromConditionalTypeNode(node);
                    case 174 /* InferType */:
                        return getTypeFromInferTypeNode(node);
                    case 181 /* ImportType */:
                        return getTypeFromImportTypeNode(node);
                    // This function assumes that an identifier or qualified name is a type expression
                    // Callers should first ensure this by calling isTypeNode
                    case 71 /* Identifier */:
                    case 146 /* QualifiedName */:
                        var symbol = getSymbolAtLocation(node);
                        return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
                    default:
                        return errorType;
                }
            }
            function instantiateList(items, mapper, instantiator) {
                if (items && items.length) {
                    for (var i = 0; i < items.length; i++) {
                        var item = items[i];
                        var mapped = instantiator(item, mapper);
                        if (item !== mapped) {
                            var result = i === 0 ? [] : items.slice(0, i);
                            result.push(mapped);
                            for (i++; i < items.length; i++) {
                                result.push(instantiator(items[i], mapper));
                            }
                            return result;
                        }
                    }
                }
                return items;
            }
            function instantiateTypes(types, mapper) {
                return instantiateList(types, mapper, instantiateType);
            }
            function instantiateSignatures(signatures, mapper) {
                return instantiateList(signatures, mapper, instantiateSignature);
            }
            function makeUnaryTypeMapper(source, target) {
                return function (t) { return t === source ? target : t; };
            }
            function makeBinaryTypeMapper(source1, target1, source2, target2) {
                return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; };
            }
            function makeArrayTypeMapper(sources, targets) {
                return function (t) {
                    for (var i = 0; i < sources.length; i++) {
                        if (t === sources[i]) {
                            return targets ? targets[i] : anyType;
                        }
                    }
                    return t;
                };
            }
            function createTypeMapper(sources, targets) {
                ts.Debug.assert(targets === undefined || sources.length === targets.length);
                return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) :
                    sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) :
                        makeArrayTypeMapper(sources, targets);
            }
            function createTypeEraser(sources) {
                return createTypeMapper(sources, /*targets*/ undefined);
            }
            /**
             * Maps forward-references to later types parameters to the empty object type.
             * This is used during inference when instantiating type parameter defaults.
             */
            function createBackreferenceMapper(typeParameters, index) {
                return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
            }
            function isInferenceContext(mapper) {
                return !!mapper.typeParameters;
            }
            function cloneTypeMapper(mapper) {
                return mapper && isInferenceContext(mapper) ?
                    createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
                    mapper;
            }
            function combineTypeMappers(mapper1, mapper2) {
                if (!mapper1)
                    return mapper2;
                if (!mapper2)
                    return mapper1;
                return function (t) { return instantiateType(mapper1(t), mapper2); };
            }
            function createReplacementMapper(source, target, baseMapper) {
                return function (t) { return t === source ? target : baseMapper(t); };
            }
            function wildcardMapper(type) {
                return type.flags & 65536 /* TypeParameter */ ? wildcardType : type;
            }
            function cloneTypeParameter(typeParameter) {
                var result = createType(65536 /* TypeParameter */);
                result.symbol = typeParameter.symbol;
                result.target = typeParameter;
                return result;
            }
            function instantiateTypePredicate(predicate, mapper) {
                if (ts.isIdentifierTypePredicate(predicate)) {
                    return {
                        kind: 1 /* Identifier */,
                        parameterName: predicate.parameterName,
                        parameterIndex: predicate.parameterIndex,
                        type: instantiateType(predicate.type, mapper)
                    };
                }
                else {
                    return {
                        kind: 0 /* This */,
                        type: instantiateType(predicate.type, mapper)
                    };
                }
            }
            function instantiateSignature(signature, mapper, eraseTypeParameters) {
                var freshTypeParameters;
                if (signature.typeParameters && !eraseTypeParameters) {
                    // First create a fresh set of type parameters, then include a mapping from the old to the
                    // new type parameters in the mapper function. Finally store this mapper in the new type
                    // parameters such that we can use it when instantiating constraints.
                    freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
                    mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
                    for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
                        var tp = freshTypeParameters_1[_i];
                        tp.mapper = mapper;
                    }
                }
                // Don't compute resolvedReturnType and resolvedTypePredicate now,
                // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
                // See GH#17600.
                var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
                /*resolvedReturnType*/ undefined, 
                /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes);
                result.target = signature;
                result.mapper = mapper;
                return result;
            }
            function instantiateSymbol(symbol, mapper) {
                var links = getSymbolLinks(symbol);
                if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) {
                    // If the type of the symbol is already resolved, and if that type could not possibly
                    // be affected by instantiation, simply return the symbol itself.
                    return symbol;
                }
                if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
                    // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
                    // type mappers. This ensures that original type identities are properly preserved and that aliases
                    // always reference a non-aliases.
                    symbol = links.target;
                    mapper = combineTypeMappers(links.mapper, mapper);
                }
                // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
                // also transient so that we can just store data on it directly.
                var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */));
                result.declarations = symbol.declarations;
                result.parent = symbol.parent;
                result.target = symbol;
                result.mapper = mapper;
                if (symbol.valueDeclaration) {
                    result.valueDeclaration = symbol.valueDeclaration;
                }
                if (symbol.nameType) {
                    result.nameType = symbol.nameType;
                }
                return result;
            }
            function getAnonymousTypeInstantiation(type, mapper) {
                var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
                var symbol = target.symbol;
                var links = getSymbolLinks(symbol);
                var typeParameters = links.outerTypeParameters;
                if (!typeParameters) {
                    // The first time an anonymous type is instantiated we compute and store a list of the type
                    // parameters that are in scope (and therefore potentially referenced). For type literals that
                    // aren't the right hand side of a generic type alias declaration we optimize by reducing the
                    // set of type parameters to those that are possibly referenced in the literal.
                    var declaration_1 = symbol.declarations[0];
                    if (ts.isInJSFile(declaration_1)) {
                        var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
                        if (paramTag) {
                            var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
                            if (paramSymbol) {
                                declaration_1 = paramSymbol.valueDeclaration;
                            }
                        }
                    }
                    var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
                    if (isJSConstructor(declaration_1)) {
                        var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
                        outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
                    }
                    typeParameters = outerTypeParameters || ts.emptyArray;
                    typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ?
                        ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
                        typeParameters;
                    links.outerTypeParameters = typeParameters;
                    if (typeParameters.length) {
                        links.instantiations = ts.createMap();
                        links.instantiations.set(getTypeListId(typeParameters), target);
                    }
                }
                if (typeParameters.length) {
                    // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
                    // mapper to the type parameters to produce the effective list of type arguments, and compute the
                    // instantiation cache key from the type IDs of the type arguments.
                    var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper;
                    var typeArguments = ts.map(typeParameters, combinedMapper);
                    var id = getTypeListId(typeArguments);
                    var result = links.instantiations.get(id);
                    if (!result) {
                        var newMapper = createTypeMapper(typeParameters, typeArguments);
                        result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper);
                        links.instantiations.set(id, result);
                    }
                    return result;
                }
                return type;
            }
            function maybeTypeParameterReference(node) {
                return !(node.kind === 146 /* QualifiedName */ ||
                    node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName);
            }
            function isTypeParameterPossiblyReferenced(tp, node) {
                // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
                // between the node and the type parameter declaration, if the node contains actual references to the
                // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
                if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
                    var container_3 = tp.symbol.declarations[0].parent;
                    if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) {
                        return !!ts.forEachChild(node, containsReference);
                    }
                }
                return true;
                function containsReference(node) {
                    switch (node.kind) {
                        case 176 /* ThisType */:
                            return !!tp.isThisType;
                        case 71 /* Identifier */:
                            return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
                                getTypeFromTypeNode(node) === tp;
                        case 165 /* TypeQuery */:
                            return true;
                    }
                    return !!ts.forEachChild(node, containsReference);
                }
            }
            function getHomomorphicTypeVariable(type) {
                var constraintType = getConstraintTypeFromMappedType(type);
                if (constraintType.flags & 1048576 /* Index */) {
                    var typeVariable = constraintType.type;
                    if (typeVariable.flags & 65536 /* TypeParameter */) {
                        return typeVariable;
                    }
                }
                return undefined;
            }
            function instantiateMappedType(type, mapper) {
                // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
                // operation depends on T as follows:
                // * If T is a primitive type no mapping is performed and the result is simply T.
                // * If T is a union type we distribute the mapped type over the union.
                // * If T is an array we map to an array where the element type has been transformed.
                // * If T is a tuple we map to a tuple where the element types have been transformed.
                // * Otherwise we map to an object type where the type of each property has been transformed.
                // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
                // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
                // { [P in keyof A]: X } | undefined.
                var typeVariable = getHomomorphicTypeVariable(type);
                if (typeVariable) {
                    var mappedTypeVariable = instantiateType(typeVariable, mapper);
                    if (typeVariable !== mappedTypeVariable) {
                        return mapType(mappedTypeVariable, function (t) {
                            if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) {
                                var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
                                return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
                                    isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
                                        isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
                                            instantiateAnonymousType(type, replacementMapper);
                            }
                            return t;
                        });
                    }
                }
                return instantiateAnonymousType(type, mapper);
            }
            function instantiateMappedTupleType(tupleType, mappedType, mapper) {
                var minLength = tupleType.target.minLength;
                var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
                    return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
                });
                var modifiers = getMappedTypeModifiers(mappedType);
                var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
                    modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
                        minLength;
                return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames);
            }
            function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
                var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
                var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
                var modifiers = getMappedTypeModifiers(type);
                return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) :
                    strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) :
                        propType;
            }
            function instantiateAnonymousType(type, mapper) {
                var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
                if (type.objectFlags & 32 /* Mapped */) {
                    result.declaration = type.declaration;
                }
                result.target = type;
                result.mapper = mapper;
                result.aliasSymbol = type.aliasSymbol;
                result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
                return result;
            }
            function getConditionalTypeInstantiation(type, mapper) {
                var root = type.root;
                if (root.outerTypeParameters) {
                    // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
                    // mapper to the type parameters to produce the effective list of type arguments, and compute the
                    // instantiation cache key from the type IDs of the type arguments.
                    var typeArguments = ts.map(root.outerTypeParameters, mapper);
                    var id = getTypeListId(typeArguments);
                    var result = root.instantiations.get(id);
                    if (!result) {
                        var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
                        result = instantiateConditionalType(root, newMapper);
                        root.instantiations.set(id, result);
                    }
                    return result;
                }
                return type;
            }
            function instantiateConditionalType(root, mapper) {
                // Check if we have a conditional type where the check type is a naked type parameter. If so,
                // the conditional type is distributive over union types and when T is instantiated to a union
                // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
                if (root.isDistributive) {
                    var checkType_1 = root.checkType;
                    var instantiatedType = mapper(checkType_1);
                    if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) {
                        return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); });
                    }
                }
                return getConditionalType(root, mapper);
            }
            function instantiateType(type, mapper) {
                if (!type || !mapper || mapper === identityMapper) {
                    return type;
                }
                if (instantiationDepth === 50) {
                    // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
                    // with a combination of infinite generic types that perpetually generate new type identities. We stop
                    // the recursion here by yielding the error type.
                    return errorType;
                }
                instantiationDepth++;
                var result = instantiateTypeWorker(type, mapper);
                instantiationDepth--;
                return result;
            }
            function instantiateTypeWorker(type, mapper) {
                var flags = type.flags;
                if (flags & 65536 /* TypeParameter */) {
                    return mapper(type);
                }
                if (flags & 131072 /* Object */) {
                    var objectFlags = type.objectFlags;
                    if (objectFlags & 16 /* Anonymous */) {
                        // If the anonymous type originates in a declaration of a function, method, class, or
                        // interface, in an object type literal, or in an object literal expression, we may need
                        // to instantiate the type because it might reference a type parameter.
                        return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ?
                            getAnonymousTypeInstantiation(type, mapper) : type;
                    }
                    if (objectFlags & 32 /* Mapped */) {
                        return getAnonymousTypeInstantiation(type, mapper);
                    }
                    if (objectFlags & 4 /* Reference */) {
                        var typeArguments = type.typeArguments;
                        var newTypeArguments = instantiateTypes(typeArguments, mapper);
                        return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type;
                    }
                    return type;
                }
                if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) {
                    var types = type.types;
                    var newTypes = instantiateTypes(types, mapper);
                    return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
                }
                if (flags & 524288 /* Intersection */) {
                    var types = type.types;
                    var newTypes = instantiateTypes(types, mapper);
                    return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type;
                }
                if (flags & 1048576 /* Index */) {
                    return getIndexType(instantiateType(type.type, mapper));
                }
                if (flags & 2097152 /* IndexedAccess */) {
                    return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
                }
                if (flags & 4194304 /* Conditional */) {
                    return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
                }
                if (flags & 8388608 /* Substitution */) {
                    return instantiateType(type.typeVariable, mapper);
                }
                return type;
            }
            function getWildcardInstantiation(type) {
                return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type :
                    type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper));
            }
            function instantiateIndexInfo(info, mapper) {
                return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
            }
            // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
            // that is subject to contextual typing.
            function isContextSensitive(node) {
                ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
                switch (node.kind) {
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                    case 154 /* MethodDeclaration */:
                        return isContextSensitiveFunctionLikeDeclaration(node);
                    case 186 /* ObjectLiteralExpression */:
                        return ts.some(node.properties, isContextSensitive);
                    case 185 /* ArrayLiteralExpression */:
                        return ts.some(node.elements, isContextSensitive);
                    case 203 /* ConditionalExpression */:
                        return isContextSensitive(node.whenTrue) ||
                            isContextSensitive(node.whenFalse);
                    case 202 /* BinaryExpression */:
                        return node.operatorToken.kind === 54 /* BarBarToken */ &&
                            (isContextSensitive(node.left) || isContextSensitive(node.right));
                    case 273 /* PropertyAssignment */:
                        return isContextSensitive(node.initializer);
                    case 193 /* ParenthesizedExpression */:
                        return isContextSensitive(node.expression);
                    case 266 /* JsxAttributes */:
                        return ts.some(node.properties, isContextSensitive);
                    case 265 /* JsxAttribute */: {
                        // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
                        var initializer = node.initializer;
                        return !!initializer && isContextSensitive(initializer);
                    }
                    case 268 /* JsxExpression */: {
                        // It is possible to that node.expression is undefined (e.g <div x={} />)
                        var expression = node.expression;
                        return !!expression && isContextSensitive(expression);
                    }
                }
                return false;
            }
            function isContextSensitiveFunctionLikeDeclaration(node) {
                // Functions with type parameters are not context sensitive.
                if (node.typeParameters) {
                    return false;
                }
                // Functions with any parameters that lack type annotations are context sensitive.
                if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
                    return true;
                }
                if (node.kind !== 195 /* ArrowFunction */) {
                    // If the first parameter is not an explicit 'this' parameter, then the function has
                    // an implicit 'this' parameter which is subject to contextual typing.
                    var parameter = ts.firstOrUndefined(node.parameters);
                    if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
                        return true;
                    }
                }
                return hasContextSensitiveReturnExpression(node);
            }
            function hasContextSensitiveReturnExpression(node) {
                // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
                var body = node.body;
                return body.kind === 216 /* Block */ ? false : isContextSensitive(body);
            }
            function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
                return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
                    isContextSensitiveFunctionLikeDeclaration(func);
            }
            function getTypeWithoutSignatures(type) {
                if (type.flags & 131072 /* Object */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    if (resolved.constructSignatures.length || resolved.callSignatures.length) {
                        var result = createObjectType(16 /* Anonymous */, type.symbol);
                        result.members = resolved.members;
                        result.properties = resolved.properties;
                        result.callSignatures = ts.emptyArray;
                        result.constructSignatures = ts.emptyArray;
                        return result;
                    }
                }
                else if (type.flags & 524288 /* Intersection */) {
                    return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
                }
                return type;
            }
            // TYPE CHECKING
            function isTypeIdenticalTo(source, target) {
                return isTypeRelatedTo(source, target, identityRelation);
            }
            function compareTypesIdentical(source, target) {
                return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
            }
            function compareTypesAssignable(source, target) {
                return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
            }
            function isTypeSubtypeOf(source, target) {
                return isTypeRelatedTo(source, target, subtypeRelation);
            }
            function isTypeAssignableTo(source, target) {
                return isTypeRelatedTo(source, target, assignableRelation);
            }
            // An object type S is considered to be derived from an object type T if
            // S is a union type and every constituent of S is derived from T,
            // T is a union type and S is derived from at least one constituent of T, or
            // S is a type variable with a base constraint that is derived from T,
            // T is one of the global types Object and Function and S is a subtype of T, or
            // T occurs directly or indirectly in an 'extends' clause of S.
            // Note that this check ignores type parameters and only considers the
            // inheritance hierarchy.
            function isTypeDerivedFrom(source, target) {
                return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
                    target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
                        source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) :
                            target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) :
                                hasBaseType(source, getTargetType(target));
            }
            /**
             * This is *not* a bi-directional relationship.
             * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
             *
             * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T.
             * It is used to check following cases:
             *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
             *   - the types of `case` clause expressions and their respective `switch` expressions.
             *   - the type of an expression in a type assertion with the type being asserted.
             */
            function isTypeComparableTo(source, target) {
                return isTypeRelatedTo(source, target, comparableRelation);
            }
            function areTypesComparable(type1, type2) {
                return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
            }
            function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
                return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
            }
            /**
             * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
             * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
             */
            function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
                return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain);
            }
            function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) {
                if (isTypeRelatedTo(source, target, relation))
                    return true;
                if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) {
                    return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain);
                }
                return false;
            }
            function isOrHasGenericConditional(type) {
                return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
            }
            function elaborateError(node, source, target, relation, headMessage) {
                if (!node || isOrHasGenericConditional(target))
                    return false;
                if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) {
                    return true;
                }
                switch (node.kind) {
                    case 268 /* JsxExpression */:
                    case 193 /* ParenthesizedExpression */:
                        return elaborateError(node.expression, source, target, relation, headMessage);
                    case 202 /* BinaryExpression */:
                        switch (node.operatorToken.kind) {
                            case 58 /* EqualsToken */:
                            case 26 /* CommaToken */:
                                return elaborateError(node.right, source, target, relation, headMessage);
                        }
                        break;
                    case 186 /* ObjectLiteralExpression */:
                        return elaborateObjectLiteral(node, source, target, relation);
                    case 185 /* ArrayLiteralExpression */:
                        return elaborateArrayLiteral(node, source, target, relation);
                    case 266 /* JsxAttributes */:
                        return elaborateJsxAttributes(node, source, target, relation);
                    case 195 /* ArrowFunction */:
                        return elaborateArrowFunction(node, source, target, relation);
                }
                return false;
            }
            function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) {
                var callSignatures = getSignaturesOfType(source, 0 /* Call */);
                var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
                for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
                    var signatures = _a[_i];
                    if (ts.some(signatures, function (s) {
                        var returnType = getReturnTypeOfSignature(s);
                        return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
                    })) {
                        var resultObj = {};
                        checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
                        var diagnostic = resultObj.error;
                        addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
                        return true;
                    }
                }
                return false;
            }
            function elaborateArrowFunction(node, source, target, relation) {
                // Don't elaborate blocks
                if (ts.isBlock(node.body)) {
                    return false;
                }
                // Or functions with annotated parameter types
                if (ts.some(node.parameters, ts.hasType)) {
                    return false;
                }
                var sourceSig = getSingleCallSignature(source);
                if (!sourceSig) {
                    return false;
                }
                var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
                if (!ts.length(targetSignatures)) {
                    return false;
                }
                var returnExpression = node.body;
                var sourceReturn = getReturnTypeOfSignature(sourceSig);
                var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
                if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
                    var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined);
                    if (elaborated) {
                        return elaborated;
                    }
                    var resultObj = {};
                    checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
                    if (resultObj.error) {
                        if (target.symbol && ts.length(target.symbol.declarations)) {
                            addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
                        }
                        return true;
                    }
                }
                return false;
            }
            /**
             * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
             * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError`
             * Otherwise, we issue an error on _every_ element which fail the assignability check
             */
            function elaborateElementwise(iterator, source, target, relation) {
                // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
                var reportedError = false;
                for (var status = iterator.next(); !status.done; status = iterator.next()) {
                    var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
                    var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType);
                    var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType);
                    if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
                        var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined);
                        if (elaborated) {
                            reportedError = true;
                        }
                        else {
                            // Issue error on the prop itself, since the prop couldn't elaborate the error
                            var resultObj = {};
                            // Use the expression type, if available
                            var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType;
                            var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj);
                            if (result && specificSource !== sourcePropType) {
                                // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
                                checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj);
                            }
                            if (resultObj.error) {
                                var reportedDiag = resultObj.error;
                                var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined;
                                var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
                                var issuedElaboration = false;
                                if (!targetProp) {
                                    var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
                                        getIndexInfoOfType(target, 0 /* String */) ||
                                        undefined;
                                    if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
                                        issuedElaboration = true;
                                        addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
                                    }
                                }
                                if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
                                    var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
                                    if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
                                        addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
                                    }
                                }
                            }
                            reportedError = true;
                        }
                    }
                }
                return reportedError;
            }
            function generateJsxAttributes(node) {
                var _i, _a, prop;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!ts.length(node.properties))
                                return [2 /*return*/];
                            _i = 0, _a = node.properties;
                            _b.label = 1;
                        case 1:
                            if (!(_i < _a.length))
                                return [3 /*break*/, 4];
                            prop = _a[_i];
                            if (ts.isJsxSpreadAttribute(prop))
                                return [3 /*break*/, 3];
                            return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
                        case 2:
                            _b.sent();
                            _b.label = 3;
                        case 3:
                            _i++;
                            return [3 /*break*/, 1];
                        case 4: return [2 /*return*/];
                    }
                });
            }
            function elaborateJsxAttributes(node, source, target, relation) {
                return elaborateElementwise(generateJsxAttributes(node), source, target, relation);
            }
            function generateLimitedTupleElements(node, target) {
                var len, i, elem, nameType;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            len = ts.length(node.elements);
                            if (!len)
                                return [2 /*return*/];
                            i = 0;
                            _a.label = 1;
                        case 1:
                            if (!(i < len))
                                return [3 /*break*/, 4];
                            // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature
                            if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
                                return [3 /*break*/, 3];
                            elem = node.elements[i];
                            if (ts.isOmittedExpression(elem))
                                return [3 /*break*/, 3];
                            nameType = getLiteralType(i);
                            return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3:
                            i++;
                            return [3 /*break*/, 1];
                        case 4: return [2 /*return*/];
                    }
                });
            }
            function elaborateArrayLiteral(node, source, target, relation) {
                if (isTupleLikeType(source)) {
                    return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
                }
                // recreate a tuple from the elements, if possible
                var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
                if (isTupleLikeType(tupleizedType)) {
                    return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
                }
                return false;
            }
            function generateObjectLiteralElements(node) {
                var _i, _a, prop, type, _b;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            if (!ts.length(node.properties))
                                return [2 /*return*/];
                            _i = 0, _a = node.properties;
                            _c.label = 1;
                        case 1:
                            if (!(_i < _a.length))
                                return [3 /*break*/, 8];
                            prop = _a[_i];
                            if (ts.isSpreadAssignment(prop))
                                return [3 /*break*/, 7];
                            type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */);
                            if (!type || (type.flags & 32768 /* Never */)) {
                                return [3 /*break*/, 7];
                            }
                            _b = prop.kind;
                            switch (_b) {
                                case 157 /* SetAccessor */: return [3 /*break*/, 2];
                                case 156 /* GetAccessor */: return [3 /*break*/, 2];
                                case 154 /* MethodDeclaration */: return [3 /*break*/, 2];
                                case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
                                case 273 /* PropertyAssignment */: return [3 /*break*/, 4];
                            }
                            return [3 /*break*/, 6];
                        case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
                        case 3:
                            _c.sent();
                            return [3 /*break*/, 7];
                        case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }];
                        case 5:
                            _c.sent();
                            return [3 /*break*/, 7];
                        case 6:
                            ts.Debug.assertNever(prop);
                            _c.label = 7;
                        case 7:
                            _i++;
                            return [3 /*break*/, 1];
                        case 8: return [2 /*return*/];
                    }
                });
            }
            function elaborateObjectLiteral(node, source, target, relation) {
                return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation);
            }
            /**
             * This is *not* a bi-directional relationship.
             * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
             */
            function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
                return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
            }
            function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
                return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, 
                /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
            }
            /**
             * See signatureRelatedTo, compareSignaturesIdentical
             */
            function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
                // TODO (drosen): De-duplicate code between related functions.
                if (source === target) {
                    return -1 /* True */;
                }
                var targetCount = getParameterCount(target);
                if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) {
                    return 0 /* False */;
                }
                if (source.typeParameters && source.typeParameters !== target.typeParameters) {
                    target = getCanonicalSignature(target);
                    source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes);
                }
                var sourceCount = getParameterCount(source);
                var sourceRestType = getNonArrayRestType(source);
                var targetRestType = getNonArrayRestType(target);
                if (sourceRestType && targetRestType && sourceCount !== targetCount) {
                    // We're not able to relate misaligned complex rest parameters
                    return 0 /* False */;
                }
                var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
                var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ &&
                    kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */;
                var result = -1 /* True */;
                var sourceThisType = getThisTypeOfSignature(source);
                if (sourceThisType && sourceThisType !== voidType) {
                    var targetThisType = getThisTypeOfSignature(target);
                    if (targetThisType) {
                        // void sources are assignable to anything.
                        var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
                            || compareTypes(targetThisType, sourceThisType, reportErrors);
                        if (!related) {
                            if (reportErrors) {
                                errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
                            }
                            return 0 /* False */;
                        }
                        result &= related;
                    }
                }
                var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
                var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
                for (var i = 0; i < paramCount; i++) {
                    var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
                    var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
                    // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
                    // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
                    // they naturally relate only contra-variantly). However, if the source and target parameters both have
                    // function types with a single call signature, we know we are relating two callback parameters. In
                    // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
                    // similar to return values, callback parameters are output positions. This means that a Promise<T>,
                    // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
                    // with respect to T.
                    var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
                    var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType));
                    var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) &&
                        (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */);
                    var related = callbacks ?
                        // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is
                        compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) :
                        !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
                    if (!related) {
                        if (reportErrors) {
                            errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
                        }
                        return 0 /* False */;
                    }
                    result &= related;
                }
                if (!ignoreReturnTypes) {
                    var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ?
                        getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target);
                    if (targetReturnType === voidType) {
                        return result;
                    }
                    var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ?
                        getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source);
                    // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
                    var targetTypePredicate = getTypePredicateOfSignature(target);
                    if (targetTypePredicate) {
                        var sourceTypePredicate = getTypePredicateOfSignature(source);
                        if (sourceTypePredicate) {
                            result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217
                        }
                        else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
                            if (reportErrors) {
                                errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
                            }
                            return 0 /* False */;
                        }
                    }
                    else {
                        // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
                        // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
                        // wouldn't be co-variant for T without this rule.
                        result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
                            compareTypes(sourceReturnType, targetReturnType, reportErrors);
                    }
                }
                return result;
            }
            function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
                if (source.kind !== target.kind) {
                    if (reportErrors) {
                        errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
                        errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
                    }
                    return 0 /* False */;
                }
                if (source.kind === 1 /* Identifier */) {
                    var targetPredicate = target;
                    var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
                    var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
                    if (sourceIndex !== targetIndex) {
                        if (reportErrors) {
                            errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
                            errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
                        }
                        return 0 /* False */;
                    }
                }
                var related = compareTypes(source.type, target.type, reportErrors);
                if (related === 0 /* False */ && reportErrors) {
                    errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
                }
                return related;
            }
            function isImplementationCompatibleWithOverload(implementation, overload) {
                var erasedSource = getErasedSignature(implementation);
                var erasedTarget = getErasedSignature(overload);
                // First see if the return types are compatible in either direction.
                var sourceReturnType = getReturnTypeOfSignature(erasedSource);
                var targetReturnType = getReturnTypeOfSignature(erasedTarget);
                if (targetReturnType === voidType
                    || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
                    || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
                    return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
                }
                return false;
            }
            function isEmptyResolvedType(t) {
                return t.properties.length === 0 &&
                    t.callSignatures.length === 0 &&
                    t.constructSignatures.length === 0 &&
                    !t.stringIndexInfo &&
                    !t.numberIndexInfo;
            }
            function isEmptyObjectType(type) {
                return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
                    type.flags & 16777216 /* NonPrimitive */ ? true :
                        type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
                            type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
                                false;
            }
            function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
                if (sourceSymbol === targetSymbol) {
                    return true;
                }
                var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
                var relation = enumRelation.get(id);
                if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) {
                    return relation === 1 /* Succeeded */;
                }
                if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
                    enumRelation.set(id, 3 /* FailedAndReported */);
                    return false;
                }
                var targetEnumType = getTypeOfSymbol(targetSymbol);
                for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
                    var property = _a[_i];
                    if (property.flags & 8 /* EnumMember */) {
                        var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
                        if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
                            if (errorReporter) {
                                errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
                                enumRelation.set(id, 3 /* FailedAndReported */);
                            }
                            else {
                                enumRelation.set(id, 2 /* Failed */);
                            }
                            return false;
                        }
                    }
                }
                enumRelation.set(id, 1 /* Succeeded */);
                return true;
            }
            function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
                var s = source.flags;
                var t = target.flags;
                if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType)
                    return true;
                if (t & 32768 /* Never */)
                    return false;
                if (s & 68 /* StringLike */ && t & 4 /* String */)
                    return true;
                if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ &&
                    t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) &&
                    source.value === target.value)
                    return true;
                if (s & 168 /* NumberLike */ && t & 8 /* Number */)
                    return true;
                if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ &&
                    t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) &&
                    source.value === target.value)
                    return true;
                if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */)
                    return true;
                if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */)
                    return true;
                if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
                    return true;
                if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) {
                    if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
                        return true;
                    if (s & 448 /* Literal */ && t & 448 /* Literal */ &&
                        source.value === target.value &&
                        isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
                        return true;
                }
                if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */)))
                    return true;
                if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */))
                    return true;
                if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */)
                    return true;
                if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */)
                    return false;
                if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) {
                    if (s & 1 /* Any */)
                        return true;
                    // Type number or any numeric literal type is assignable to any numeric enum type or any
                    // numeric enum literal type. This rule exists for backwards compatibility reasons because
                    // bit-flag enum types sometimes look like literal enum types with numeric literal values.
                    if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */))
                        return true;
                }
                return false;
            }
            function isTypeRelatedTo(source, target, relation) {
                if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) {
                    source = source.regularType;
                }
                if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) {
                    target = target.regularType;
                }
                if (source === target ||
                    relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
                    relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) {
                    return true;
                }
                if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) {
                    var related = relation.get(getRelationKey(source, target, relation));
                    if (related !== undefined) {
                        return related === 1 /* Succeeded */;
                    }
                }
                if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) {
                    return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
                }
                return false;
            }
            function isIgnoredJsxProperty(source, sourceProp, targetMemberType) {
                return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType);
            }
            /**
             * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
             * @param source The left-hand-side of the relation.
             * @param target The right-hand-side of the relation.
             * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
             * Used as both to determine which checks are performed and as a cache of previously computed results.
             * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
             * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
             * @param containingMessageChain A chain of errors to prepend any new errors found.
             */
            function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
                var errorInfo;
                var maybeKeys;
                var sourceStack;
                var targetStack;
                var maybeCount = 0;
                var depth = 0;
                var expandingFlags = 0 /* None */;
                var overflow = false;
                var isIntersectionConstituent = false;
                ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
                var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
                if (overflow) {
                    error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
                }
                else if (errorInfo) {
                    if (containingMessageChain) {
                        var chain_1 = containingMessageChain();
                        if (chain_1) {
                            errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo);
                        }
                    }
                    var relatedInformation = void 0;
                    // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
                    if (headMessage && errorNode && !result && source.symbol) {
                        var links = getSymbolLinks(source.symbol);
                        if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
                            var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
                            if (helpfulRetry) {
                                // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
                                var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead);
                                relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
                            }
                        }
                    }
                    var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
                    if (errorOutputContainer) {
                        errorOutputContainer.error = diag;
                    }
                    diagnostics.add(diag); // TODO: GH#18217
                }
                return result !== 0 /* False */;
                function reportError(message, arg0, arg1, arg2) {
                    ts.Debug.assert(!!errorNode);
                    errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2);
                }
                function reportRelationError(message, source, target) {
                    var sourceType = typeToString(source);
                    var targetType = typeToString(target);
                    if (sourceType === targetType) {
                        sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
                        targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
                    }
                    if (!message) {
                        if (relation === comparableRelation) {
                            message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
                        }
                        else if (sourceType === targetType) {
                            message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
                        }
                        else {
                            message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
                        }
                    }
                    reportError(message, sourceType, targetType);
                }
                function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
                    var sourceType = typeToString(source);
                    var targetType = typeToString(target);
                    if ((globalStringType === source && stringType === target) ||
                        (globalNumberType === source && numberType === target) ||
                        (globalBooleanType === source && booleanType === target) ||
                        (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
                        reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
                    }
                }
                function isUnionOrIntersectionTypeWithoutNullableConstituents(type) {
                    if (!(type.flags & 786432 /* UnionOrIntersection */)) {
                        return false;
                    }
                    // at this point we know that this is union or intersection type possibly with nullable constituents.
                    // check if we still will have compound type if we ignore nullable components.
                    var seenNonNullable = false;
                    for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
                        var t = _a[_i];
                        if (t.flags & 24576 /* Nullable */) {
                            continue;
                        }
                        if (seenNonNullable) {
                            return true;
                        }
                        seenNonNullable = true;
                    }
                    return false;
                }
                /**
                 * Compare two types and return
                 * * Ternary.True if they are related with no assumptions,
                 * * Ternary.Maybe if they are related with assumptions of other relationships, or
                 * * Ternary.False if they are not related.
                 */
                function isRelatedTo(source, target, reportErrors, headMessage) {
                    if (reportErrors === void 0) {
                        reportErrors = false;
                    }
                    if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) {
                        source = source.regularType;
                    }
                    if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) {
                        target = target.regularType;
                    }
                    if (source.flags & 8388608 /* Substitution */) {
                        source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute;
                    }
                    if (target.flags & 8388608 /* Substitution */) {
                        target = target.typeVariable;
                    }
                    if (source.flags & 2097152 /* IndexedAccess */) {
                        source = getSimplifiedType(source);
                    }
                    if (target.flags & 2097152 /* IndexedAccess */) {
                        target = getSimplifiedType(target);
                    }
                    // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
                    // If so, reporting the `null` and `undefined` in the type is hardly useful.
                    // First, see if we're even relating an object type to a union.
                    // Then see if the target is stripped down to a single non-union type.
                    // Note
                    //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
                    //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
                    //    when dealing with generics.
                    //  * We also don't deal with primitive source types, since we already halt elaboration below.
                    if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ &&
                        target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) {
                        var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */);
                        if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) {
                            target = nullStrippedTarget;
                        }
                    }
                    // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases
                    if (source === target)
                        return -1 /* True */;
                    if (relation === identityRelation) {
                        return isIdenticalTo(source, target);
                    }
                    if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
                        isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
                        return -1 /* True */;
                    if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) {
                        var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined;
                        if (hasExcessProperties(source, target, discriminantType, reportErrors)) {
                            if (reportErrors) {
                                reportRelationError(headMessage, source, target);
                            }
                            return 0 /* False */;
                        }
                        // Above we check for excess properties with respect to the entire target type. When union
                        // and intersection types are further deconstructed on the target side, we don't want to
                        // make the check again (as it might fail for a partial target type). Therefore we obtain
                        // the regular source type and proceed with that.
                        if (isUnionOrIntersectionTypeWithoutNullableConstituents(target) && !discriminantType) {
                            source = getRegularTypeOfObjectLiteral(source);
                        }
                    }
                    if (relation !== comparableRelation && !isIntersectionConstituent &&
                        source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType &&
                        target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) &&
                        (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) &&
                        !hasCommonProperties(source, target)) {
                        if (reportErrors) {
                            var calls = getSignaturesOfType(source, 0 /* Call */);
                            var constructs = getSignaturesOfType(source, 1 /* Construct */);
                            if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
                                constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
                                reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target));
                            }
                            else {
                                reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
                            }
                        }
                        return 0 /* False */;
                    }
                    var result = 0 /* False */;
                    var saveErrorInfo = errorInfo;
                    var saveIsIntersectionConstituent = isIntersectionConstituent;
                    isIntersectionConstituent = false;
                    // Note that these checks are specifically ordered to produce correct results. In particular,
                    // we need to deconstruct unions before intersections (because unions are always at the top),
                    // and we need to handle "each" relations before "some" relations for the same kind of type.
                    if (source.flags & 262144 /* Union */) {
                        result = relation === comparableRelation ?
                            someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) :
                            eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */));
                    }
                    else {
                        if (target.flags & 262144 /* Union */) {
                            result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */));
                        }
                        else if (target.flags & 524288 /* Intersection */) {
                            isIntersectionConstituent = true;
                            result = typeRelatedToEachType(source, target, reportErrors);
                        }
                        else if (source.flags & 524288 /* Intersection */) {
                            // Check to see if any constituents of the intersection are immediately related to the target.
                            //
                            // Don't report errors though. Checking whether a constituent is related to the source is not actually
                            // useful and leads to some confusing error messages. Instead it is better to let the below checks
                            // take care of this, or to not elaborate at all. For instance,
                            //
                            //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
                            //
                            //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
                            //          than to report that 'D' is not assignable to 'A' or 'B'.
                            //
                            //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
                            //          breaking the intersection apart.
                            result = someTypeRelatedToType(source, target, /*reportErrors*/ false);
                        }
                        if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) {
                            if (result = recursiveTypeRelatedTo(source, target, reportErrors)) {
                                errorInfo = saveErrorInfo;
                            }
                        }
                    }
                    if (!result && source.flags & 524288 /* Intersection */) {
                        // The combined constraint of an intersection type is the intersection of the constraints of
                        // the constituents. When an intersection type contains instantiable types with union type
                        // constraints, there are situations where we need to examine the combined constraint. One is
                        // when the target is a union type. Another is when the intersection contains types belonging
                        // to one of the disjoint domains. For example, given type variables T and U, each with the
                        // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
                        // we need to check this constraint against a union on the target side. Also, given a type
                        // variable V constrained to 'string | number', 'V & number' has a combined constraint of
                        // 'string & number | number & number' which reduces to just 'number'.
                        var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */));
                        if (constraint) {
                            if (result = isRelatedTo(constraint, target, reportErrors)) {
                                errorInfo = saveErrorInfo;
                            }
                        }
                    }
                    isIntersectionConstituent = saveIsIntersectionConstituent;
                    if (!result && reportErrors) {
                        if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) {
                            tryElaborateErrorsForPrimitivesAndObjects(source, target);
                        }
                        else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) {
                            reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
                        }
                        else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) {
                            var targetTypes = target.types;
                            var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
                            var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
                            if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
                                (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
                                // do not report top error
                                return result;
                            }
                        }
                        reportRelationError(headMessage, source, target);
                    }
                    return result;
                }
                function isIdenticalTo(source, target) {
                    var result;
                    var flags = source.flags & target.flags;
                    if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) {
                        return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false);
                    }
                    if (flags & (262144 /* Union */ | 524288 /* Intersection */)) {
                        if (result = eachTypeRelatedToSomeType(source, target)) {
                            if (result &= eachTypeRelatedToSomeType(target, source)) {
                                return result;
                            }
                        }
                    }
                    return 0 /* False */;
                }
                function hasExcessProperties(source, target, discriminant, reportErrors) {
                    if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
                        return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
                    }
                    if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
                        var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
                        if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) &&
                            (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
                            return false;
                        }
                        if (discriminant) {
                            // check excess properties against discriminant type only, not the entire union
                            return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors);
                        }
                        var _loop_5 = function (prop) {
                            if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
                                if (reportErrors) {
                                    // We know *exactly* where things went wrong when comparing the types.
                                    // Use this property as the error node as this will be more helpful in
                                    // reasoning about what went wrong.
                                    if (!errorNode)
                                        return { value: ts.Debug.fail() };
                                    if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) {
                                        // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
                                        // However, using an object-literal error message will be very confusing to the users so we give different a message.
                                        reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target));
                                    }
                                    else {
                                        // use the property's value declaration if the property is assigned inside the literal itself
                                        var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
                                        var suggestion = void 0;
                                        if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) {
                                            var propDeclaration = prop.valueDeclaration;
                                            ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
                                            errorNode = propDeclaration;
                                            var name = propDeclaration.name;
                                            if (ts.isIdentifier(name)) {
                                                suggestion = getSuggestionForNonexistentProperty(name, target);
                                            }
                                        }
                                        if (suggestion !== undefined) {
                                            reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion);
                                        }
                                        else {
                                            reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target));
                                        }
                                    }
                                }
                                return { value: true };
                            }
                        };
                        for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
                            var prop = _a[_i];
                            var state_2 = _loop_5(prop);
                            if (typeof state_2 === "object")
                                return state_2.value;
                        }
                    }
                    return false;
                }
                function isPropertyFromSpread(prop, container) {
                    return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration;
                }
                function eachTypeRelatedToSomeType(source, target) {
                    var result = -1 /* True */;
                    var sourceTypes = source.types;
                    for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
                        var sourceType = sourceTypes_1[_i];
                        var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
                        if (!related) {
                            return 0 /* False */;
                        }
                        result &= related;
                    }
                    return result;
                }
                function typeRelatedToSomeType(source, target, reportErrors) {
                    var targetTypes = target.types;
                    if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) {
                        return -1 /* True */;
                    }
                    for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
                        var type = targetTypes_1[_i];
                        var related = isRelatedTo(source, type, /*reportErrors*/ false);
                        if (related) {
                            return related;
                        }
                    }
                    if (reportErrors) {
                        var bestMatchingType = findMatchingDiscriminantType(source, target) ||
                            findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
                            findBestTypeForObjectLiteral(source, target) ||
                            findBestTypeForInvokable(source, target);
                        isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
                    }
                    return 0 /* False */;
                }
                function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
                    var sourceObjectFlags = ts.getObjectFlags(source);
                    if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) {
                        return ts.find(unionTarget.types, function (target) {
                            if (target.flags & 131072 /* Object */) {
                                var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
                                if (overlapObjFlags & 4 /* Reference */) {
                                    return source.target === target.target;
                                }
                                if (overlapObjFlags & 16 /* Anonymous */) {
                                    return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
                                }
                            }
                            return false;
                        });
                    }
                }
                function findBestTypeForObjectLiteral(source, unionTarget) {
                    if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
                        return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
                    }
                }
                function findBestTypeForInvokable(source, unionTarget) {
                    var signatureKind = 0 /* Call */;
                    var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
                        (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
                    if (hasSignatures) {
                        return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
                    }
                }
                // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
                function findMatchingDiscriminantType(source, target) {
                    var match;
                    var sourceProperties = getPropertiesOfObjectType(source);
                    if (sourceProperties) {
                        var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
                        if (sourcePropertiesFiltered) {
                            for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
                                var sourceProperty = sourcePropertiesFiltered_1[_i];
                                var sourceType = getTypeOfSymbol(sourceProperty);
                                for (var _a = 0, _b = target.types; _a < _b.length; _a++) {
                                    var type = _b[_a];
                                    var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName);
                                    if (targetType && isRelatedTo(sourceType, targetType)) {
                                        if (type === match)
                                            continue; // Finding multiple fields which discriminate to the same type is fine
                                        if (match) {
                                            return undefined;
                                        }
                                        match = type;
                                    }
                                }
                            }
                        }
                    }
                    return match;
                }
                function typeRelatedToEachType(source, target, reportErrors) {
                    var result = -1 /* True */;
                    var targetTypes = target.types;
                    for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
                        var targetType = targetTypes_2[_i];
                        var related = isRelatedTo(source, targetType, reportErrors);
                        if (!related) {
                            return 0 /* False */;
                        }
                        result &= related;
                    }
                    return result;
                }
                function someTypeRelatedToType(source, target, reportErrors) {
                    var sourceTypes = source.types;
                    if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) {
                        return -1 /* True */;
                    }
                    var len = sourceTypes.length;
                    for (var i = 0; i < len; i++) {
                        var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1);
                        if (related) {
                            return related;
                        }
                    }
                    return 0 /* False */;
                }
                function eachTypeRelatedToType(source, target, reportErrors) {
                    var result = -1 /* True */;
                    var sourceTypes = source.types;
                    for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) {
                        var sourceType = sourceTypes_2[_i];
                        var related = isRelatedTo(sourceType, target, reportErrors);
                        if (!related) {
                            return 0 /* False */;
                        }
                        result &= related;
                    }
                    return result;
                }
                function typeArgumentsRelatedTo(source, target, variances, reportErrors) {
                    var sources = source.typeArguments || ts.emptyArray;
                    var targets = target.typeArguments || ts.emptyArray;
                    if (sources.length !== targets.length && relation === identityRelation) {
                        return 0 /* False */;
                    }
                    var length = sources.length <= targets.length ? sources.length : targets.length;
                    var result = -1 /* True */;
                    for (var i = 0; i < length; i++) {
                        // When variance information isn't available we default to covariance. This happens
                        // in the process of computing variance information for recursive types and when
                        // comparing 'this' type arguments.
                        var variance = i < variances.length ? variances[i] : 1 /* Covariant */;
                        // We ignore arguments for independent type parameters (because they're never witnessed).
                        if (variance !== 4 /* Independent */) {
                            var s = sources[i];
                            var t = targets[i];
                            var related = -1 /* True */;
                            if (variance === 1 /* Covariant */) {
                                related = isRelatedTo(s, t, reportErrors);
                            }
                            else if (variance === 2 /* Contravariant */) {
                                related = isRelatedTo(t, s, reportErrors);
                            }
                            else if (variance === 3 /* Bivariant */) {
                                // In the bivariant case we first compare contravariantly without reporting
                                // errors. Then, if that doesn't succeed, we compare covariantly with error
                                // reporting. Thus, error elaboration will be based on the the covariant check,
                                // which is generally easier to reason about.
                                related = isRelatedTo(t, s, /*reportErrors*/ false);
                                if (!related) {
                                    related = isRelatedTo(s, t, reportErrors);
                                }
                            }
                            else {
                                // In the invariant case we first compare covariantly, and only when that
                                // succeeds do we proceed to compare contravariantly. Thus, error elaboration
                                // will typically be based on the covariant check.
                                related = isRelatedTo(s, t, reportErrors);
                                if (related) {
                                    related &= isRelatedTo(t, s, reportErrors);
                                }
                            }
                            if (!related) {
                                return 0 /* False */;
                            }
                            result &= related;
                        }
                    }
                    return result;
                }
                // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
                // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
                // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
                // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
                // and issue an error. Otherwise, actually compare the structure of the two types.
                function recursiveTypeRelatedTo(source, target, reportErrors) {
                    if (overflow) {
                        return 0 /* False */;
                    }
                    var id = getRelationKey(source, target, relation);
                    var related = relation.get(id);
                    if (related !== undefined) {
                        if (reportErrors && related === 2 /* Failed */) {
                            // We are elaborating errors and the cached result is an unreported failure. The result will be reported
                            // as a failure, and should be updated as a reported failure by the bottom of this function.
                        }
                        else {
                            return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
                        }
                    }
                    if (!maybeKeys) {
                        maybeKeys = [];
                        sourceStack = [];
                        targetStack = [];
                    }
                    else {
                        for (var i = 0; i < maybeCount; i++) {
                            // If source and target are already being compared, consider them related with assumptions
                            if (id === maybeKeys[i]) {
                                return 1 /* Maybe */;
                            }
                        }
                        if (depth === 100) {
                            overflow = true;
                            return 0 /* False */;
                        }
                    }
                    var maybeStart = maybeCount;
                    maybeKeys[maybeCount] = id;
                    maybeCount++;
                    sourceStack[depth] = source;
                    targetStack[depth] = target;
                    depth++;
                    var saveExpandingFlags = expandingFlags;
                    if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
                        expandingFlags |= 1 /* Source */;
                    if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
                        expandingFlags |= 2 /* Target */;
                    var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */;
                    expandingFlags = saveExpandingFlags;
                    depth--;
                    if (result) {
                        if (result === -1 /* True */ || depth === 0) {
                            // If result is definitely true, record all maybe keys as having succeeded
                            for (var i = maybeStart; i < maybeCount; i++) {
                                relation.set(maybeKeys[i], 1 /* Succeeded */);
                            }
                            maybeCount = maybeStart;
                        }
                    }
                    else {
                        // A false result goes straight into global cache (when something is false under
                        // assumptions it will also be false without assumptions)
                        relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */);
                        maybeCount = maybeStart;
                    }
                    return result;
                }
                function getConstraintForRelation(type) {
                    return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type);
                }
                function structuredTypeRelatedTo(source, target, reportErrors) {
                    var flags = source.flags & target.flags;
                    if (relation === identityRelation && !(flags & 131072 /* Object */)) {
                        if (flags & 1048576 /* Index */) {
                            return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
                        }
                        var result_2 = 0 /* False */;
                        if (flags & 2097152 /* IndexedAccess */) {
                            if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
                                if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
                                    return result_2;
                                }
                            }
                        }
                        if (flags & 4194304 /* Conditional */) {
                            if (source.root.isDistributive === target.root.isDistributive) {
                                if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
                                    if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
                                        if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
                                            if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
                                                return result_2;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (flags & 8388608 /* Substitution */) {
                            return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
                        }
                        return 0 /* False */;
                    }
                    var result;
                    var originalErrorInfo;
                    var saveErrorInfo = errorInfo;
                    if (target.flags & 65536 /* TypeParameter */) {
                        // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P].
                        if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) {
                            if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
                                var templateType = getTemplateTypeFromMappedType(source);
                                var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
                                if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
                                    return result;
                                }
                            }
                        }
                    }
                    else if (target.flags & 1048576 /* Index */) {
                        // A keyof S is related to a keyof T if T is related to S.
                        if (source.flags & 1048576 /* Index */) {
                            if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
                                return result;
                            }
                        }
                        // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
                        // simplified form of T or, if T doesn't simplify, the constraint of T.
                        if (relation !== definitelyAssignableRelation) {
                            var simplified = getSimplifiedType(target.type);
                            var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type);
                            if (constraint) {
                                // We require Ternary.True here such that circular constraints don't cause
                                // false positives. For example, given 'T extends { [K in keyof T]: string }',
                                // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
                                // related to other types.
                                if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
                                    return -1 /* True */;
                                }
                            }
                        }
                    }
                    else if (target.flags & 2097152 /* IndexedAccess */) {
                        // A type S is related to a type T[K] if S is related to C, where C is the base constraint of T[K]
                        if (relation !== identityRelation) {
                            var constraint = getBaseConstraintOfType(target);
                            if (constraint && constraint !== target) {
                                if (result = isRelatedTo(source, constraint, reportErrors)) {
                                    return result;
                                }
                            }
                        }
                    }
                    else if (isGenericMappedType(target)) {
                        // A source type T is related to a target type { [P in X]: T[P] }
                        var template = getTemplateTypeFromMappedType(target);
                        var modifiers = getMappedTypeModifiers(target);
                        if (!(modifiers & 8 /* ExcludeOptional */)) {
                            if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source &&
                                template.indexType === getTypeParameterFromMappedType(target)) {
                                return -1 /* True */;
                            }
                            // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X.
                            if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) {
                                var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
                                var templateType = getTemplateTypeFromMappedType(target);
                                if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
                                    return result;
                                }
                            }
                        }
                    }
                    if (source.flags & 2162688 /* TypeVariable */) {
                        if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) {
                            // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
                            if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
                                result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
                            }
                            if (result) {
                                errorInfo = saveErrorInfo;
                                return result;
                            }
                        }
                        var constraint = getConstraintForRelation(source);
                        if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) {
                            // A type variable with no constraint is not related to the non-primitive object type.
                            if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) {
                                errorInfo = saveErrorInfo;
                                return result;
                            }
                        }
                        else {
                            var instantiated = getTypeWithThisArgument(constraint, source);
                            if (result = isRelatedTo(instantiated, target, reportErrors)) {
                                errorInfo = saveErrorInfo;
                                return result;
                            }
                        }
                    }
                    else if (source.flags & 1048576 /* Index */) {
                        if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
                            errorInfo = saveErrorInfo;
                            return result;
                        }
                    }
                    else if (source.flags & 4194304 /* Conditional */) {
                        if (target.flags & 4194304 /* Conditional */) {
                            // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
                            // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
                            // and Y1 is related to Y2.
                            if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
                                (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
                                if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
                                    result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
                                }
                                if (result) {
                                    errorInfo = saveErrorInfo;
                                    return result;
                                }
                            }
                        }
                        else if (relation !== definitelyAssignableRelation) {
                            var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
                            if (distributiveConstraint) {
                                if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
                                    errorInfo = saveErrorInfo;
                                    return result;
                                }
                            }
                            var defaultConstraint = getDefaultConstraintOfConditionalType(source);
                            if (defaultConstraint) {
                                if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
                                    errorInfo = saveErrorInfo;
                                    return result;
                                }
                            }
                        }
                    }
                    else {
                        // An empty object type is related to any mapped type that includes a '?' modifier.
                        if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) {
                            return -1 /* True */;
                        }
                        if (isGenericMappedType(target)) {
                            if (isGenericMappedType(source)) {
                                if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
                                    errorInfo = saveErrorInfo;
                                    return result;
                                }
                            }
                            return 0 /* False */;
                        }
                        if (relation === definitelyAssignableRelation && isGenericMappedType(source)) {
                            return 0 /* False */;
                        }
                        var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */);
                        if (relation !== identityRelation) {
                            source = getApparentType(source);
                        }
                        if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
                            !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
                            // We have type references to the same generic type, and the type references are not marker
                            // type references (which are intended by be compared structurally). Obtain the variance
                            // information for the type parameters and relate the type arguments accordingly.
                            var variances = getVariances(source.target);
                            if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) {
                                return result;
                            }
                            // The type arguments did not relate appropriately, but it may be because we have no variance
                            // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
                            // arguments). It might also be the case that the target type has a 'void' type argument for
                            // a covariant type parameter that is only used in return positions within the generic type
                            // (in which case any type argument is permitted on the source side). In those cases we proceed
                            // with a structural comparison. Otherwise, we know for certain the instantiations aren't
                            // related and we can return here.
                            if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
                                // In some cases generic types that are covariant in regular type checking mode become
                                // invariant in --strictFunctionTypes mode because one or more type parameters are used in
                                // both co- and contravariant positions. In order to make it easier to diagnose *why* such
                                // types are invariant, if any of the type parameters are invariant we reset the reported
                                // errors and instead force a structural comparison (which will include elaborations that
                                // reveal the reason).
                                if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
                                    return 0 /* False */;
                                }
                                // We remember the original error information so we can restore it in case the structural
                                // comparison unexpectedly succeeds. This can happen when the structural comparison result
                                // is a Ternary.Maybe for example caused by the recursion depth limiter.
                                originalErrorInfo = errorInfo;
                                errorInfo = saveErrorInfo;
                            }
                        }
                        else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
                            return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
                        }
                        // Even if relationship doesn't hold for unions, intersections, or generic type references,
                        // it may hold in a structural comparison.
                        // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
                        // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
                        // relates to X. Thus, we include intersection types on the source side here.
                        if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) {
                            // Report structural errors only if we haven't reported any errors yet
                            var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive;
                            result = propertiesRelatedTo(source, target, reportStructuralErrors);
                            if (result) {
                                result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
                                if (result) {
                                    result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
                                    if (result) {
                                        result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors);
                                        if (result) {
                                            result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors);
                                        }
                                    }
                                }
                            }
                            if (result) {
                                if (!originalErrorInfo) {
                                    errorInfo = saveErrorInfo;
                                    return result;
                                }
                                errorInfo = originalErrorInfo;
                            }
                        }
                    }
                    return 0 /* False */;
                }
                // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
                // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
                // that S and T are contra-variant whereas X and Y are co-variant.
                function mappedTypeRelatedTo(source, target, reportErrors) {
                    var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
                        getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
                    if (modifiersRelated) {
                        var result_3;
                        if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
                            var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
                            return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
                        }
                    }
                    return 0 /* False */;
                }
                function propertiesRelatedTo(source, target, reportErrors) {
                    if (relation === identityRelation) {
                        return propertiesIdenticalTo(source, target);
                    }
                    var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
                    var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties);
                    if (unmatchedProperty) {
                        if (reportErrors) {
                            reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source));
                        }
                        return 0 /* False */;
                    }
                    if (isObjectLiteralType(target)) {
                        for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
                            var sourceProp = _a[_i];
                            if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
                                var sourceType = getTypeOfSymbol(sourceProp);
                                if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) {
                                    if (reportErrors) {
                                        reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
                                    }
                                    return 0 /* False */;
                                }
                            }
                        }
                    }
                    var result = -1 /* True */;
                    if (isTupleType(target)) {
                        var targetRestType = getRestTypeOfTupleType(target);
                        if (targetRestType) {
                            if (!isTupleType(source)) {
                                return 0 /* False */;
                            }
                            var sourceRestType = getRestTypeOfTupleType(source);
                            if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
                                if (reportErrors) {
                                    reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
                                }
                                return 0 /* False */;
                            }
                            var targetCount = getTypeReferenceArity(target) - 1;
                            var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
                            for (var i = targetCount; i < sourceCount; i++) {
                                var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors);
                                if (!related) {
                                    if (reportErrors) {
                                        reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
                                    }
                                    return 0 /* False */;
                                }
                                result &= related;
                            }
                        }
                    }
                    var properties = getPropertiesOfObjectType(target);
                    for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) {
                        var targetProp = properties_3[_b];
                        if (!(targetProp.flags & 4194304 /* Prototype */)) {
                            var sourceProp = getPropertyOfType(source, targetProp.escapedName);
                            if (sourceProp && sourceProp !== targetProp) {
                                if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) {
                                    continue;
                                }
                                var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
                                var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
                                if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
                                    var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration;
                                    if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) {
                                        if (reportErrors) {
                                            reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source));
                                        }
                                        return 0 /* False */;
                                    }
                                    if (hasDifferingDeclarations) {
                                        if (reportErrors) {
                                            if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
                                                reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
                                            }
                                            else {
                                                reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source));
                                            }
                                        }
                                        return 0 /* False */;
                                    }
                                }
                                else if (targetPropFlags & 16 /* Protected */) {
                                    if (!isValidOverrideOf(sourceProp, targetProp)) {
                                        if (reportErrors) {
                                            reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target));
                                        }
                                        return 0 /* False */;
                                    }
                                }
                                else if (sourcePropFlags & 16 /* Protected */) {
                                    if (reportErrors) {
                                        reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
                                    }
                                    return 0 /* False */;
                                }
                                var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors);
                                if (!related) {
                                    if (reportErrors) {
                                        reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
                                    }
                                    return 0 /* False */;
                                }
                                result &= related;
                                // When checking for comparability, be more lenient with optional properties.
                                if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
                                    // TypeScript 1.0 spec (April 2014): 3.8.3
                                    // S is a subtype of a type T, and T is a supertype of S if ...
                                    // S' and T are object types and, for each member M in T..
                                    // M is a property and S' contains a property N where
                                    // if M is a required property, N is also a required property
                                    // (M - property in T)
                                    // (N - property in S)
                                    if (reportErrors) {
                                        reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
                                    }
                                    return 0 /* False */;
                                }
                            }
                        }
                    }
                    return result;
                }
                function propertiesIdenticalTo(source, target) {
                    if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) {
                        return 0 /* False */;
                    }
                    var sourceProperties = getPropertiesOfObjectType(source);
                    var targetProperties = getPropertiesOfObjectType(target);
                    if (sourceProperties.length !== targetProperties.length) {
                        return 0 /* False */;
                    }
                    var result = -1 /* True */;
                    for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
                        var sourceProp = sourceProperties_1[_i];
                        var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
                        if (!targetProp) {
                            return 0 /* False */;
                        }
                        var related = compareProperties(sourceProp, targetProp, isRelatedTo);
                        if (!related) {
                            return 0 /* False */;
                        }
                        result &= related;
                    }
                    return result;
                }
                function signaturesRelatedTo(source, target, kind, reportErrors) {
                    if (relation === identityRelation) {
                        return signaturesIdenticalTo(source, target, kind);
                    }
                    if (target === anyFunctionType || source === anyFunctionType) {
                        return -1 /* True */;
                    }
                    var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
                    var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
                    var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
                        0 /* Call */ : kind);
                    var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
                        0 /* Call */ : kind);
                    if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
                        if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
                            // An abstract constructor type is not assignable to a non-abstract constructor type
                            // as it would otherwise be possible to new an abstract class. Note that the assignability
                            // check we perform for an extends clause excludes construct signatures from the target,
                            // so this check never proceeds.
                            if (reportErrors) {
                                reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
                            }
                            return 0 /* False */;
                        }
                        if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
                            return 0 /* False */;
                        }
                    }
                    var result = -1 /* True */;
                    var saveErrorInfo = errorInfo;
                    if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
                        // We have instantiations of the same anonymous type (which typically will be the type of a
                        // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
                        // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
                        // as they are known to always be the same.
                        for (var i = 0; i < targetSignatures.length; i++) {
                            var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors);
                            if (!related) {
                                return 0 /* False */;
                            }
                            result &= related;
                        }
                    }
                    else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
                        // For simple functions (functions with a single signature) we only erase type parameters for
                        // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
                        // in the context of the target signature before checking the relationship. Ideally we'd do
                        // this regardless of the number of signatures, but the potential costs are prohibitive due
                        // to the quadratic nature of the logic below.
                        var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
                        result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors);
                    }
                    else {
                        outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
                            var t = targetSignatures_1[_i];
                            // Only elaborate errors from the first failure
                            var shouldElaborateErrors = reportErrors;
                            for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
                                var s = sourceSignatures_1[_a];
                                var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors);
                                if (related) {
                                    result &= related;
                                    errorInfo = saveErrorInfo;
                                    continue outer;
                                }
                                shouldElaborateErrors = false;
                            }
                            if (shouldElaborateErrors) {
                                reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
                            }
                            return 0 /* False */;
                        }
                    }
                    return result;
                }
                /**
                 * See signatureAssignableTo, compareSignaturesIdentical
                 */
                function signatureRelatedTo(source, target, erase, reportErrors) {
                    return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo);
                }
                function signaturesIdenticalTo(source, target, kind) {
                    var sourceSignatures = getSignaturesOfType(source, kind);
                    var targetSignatures = getSignaturesOfType(target, kind);
                    if (sourceSignatures.length !== targetSignatures.length) {
                        return 0 /* False */;
                    }
                    var result = -1 /* True */;
                    for (var i = 0; i < sourceSignatures.length; i++) {
                        var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
                        if (!related) {
                            return 0 /* False */;
                        }
                        result &= related;
                    }
                    return result;
                }
                function eachPropertyRelatedTo(source, target, kind, reportErrors) {
                    var result = -1 /* True */;
                    for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
                        var prop = _a[_i];
                        if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) {
                            continue;
                        }
                        // Skip over symbol-named members
                        if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) {
                            continue;
                        }
                        if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
                            var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
                            if (!related) {
                                if (reportErrors) {
                                    reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
                                }
                                return 0 /* False */;
                            }
                            result &= related;
                        }
                    }
                    return result;
                }
                function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) {
                    var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors);
                    if (!related && reportErrors) {
                        reportError(ts.Diagnostics.Index_signatures_are_incompatible);
                    }
                    return related;
                }
                function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) {
                    if (relation === identityRelation) {
                        return indexTypesIdenticalTo(source, target, kind);
                    }
                    var targetInfo = getIndexInfoOfType(target, kind);
                    if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) {
                        // Index signature of type any permits assignment from everything but primitives
                        return -1 /* True */;
                    }
                    var sourceInfo = getIndexInfoOfType(source, kind) ||
                        kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */);
                    if (sourceInfo) {
                        return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors);
                    }
                    if (isGenericMappedType(source)) {
                        // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
                        // if T is related to U.
                        return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217
                    }
                    if (isObjectTypeWithInferableIndex(source)) {
                        var related = -1 /* True */;
                        if (kind === 0 /* String */) {
                            var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */);
                            if (sourceNumberInfo) {
                                related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors);
                            }
                        }
                        if (related) {
                            related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors);
                        }
                        return related;
                    }
                    if (reportErrors) {
                        reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
                    }
                    return 0 /* False */;
                }
                function indexTypesIdenticalTo(source, target, indexKind) {
                    var targetInfo = getIndexInfoOfType(target, indexKind);
                    var sourceInfo = getIndexInfoOfType(source, indexKind);
                    if (!sourceInfo && !targetInfo) {
                        return -1 /* True */;
                    }
                    if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
                        return isRelatedTo(sourceInfo.type, targetInfo.type);
                    }
                    return 0 /* False */;
                }
                function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
                    if (!sourceSignature.declaration || !targetSignature.declaration) {
                        return true;
                    }
                    var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
                    var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
                    // A public, protected and private signature is assignable to a private signature.
                    if (targetAccessibility === 8 /* Private */) {
                        return true;
                    }
                    // A public and protected signature is assignable to a protected signature.
                    if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
                        return true;
                    }
                    // Only a public signature is assignable to public signature.
                    if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
                        return true;
                    }
                    if (reportErrors) {
                        reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
                    }
                    return false;
                }
            }
            /**
             * A type is 'weak' if it is an object type with at least one optional property
             * and no required properties, call/construct signatures or index signatures
             */
            function isWeakType(type) {
                if (type.flags & 131072 /* Object */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
                        !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
                        resolved.properties.length > 0 &&
                        ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
                }
                if (type.flags & 524288 /* Intersection */) {
                    return ts.every(type.types, isWeakType);
                }
                return false;
            }
            function hasCommonProperties(source, target) {
                var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
                for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
                    var prop = _a[_i];
                    if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
                        return true;
                    }
                }
                return false;
            }
            // Return a type reference where the source type parameter is replaced with the target marker
            // type, and flag the result as a marker type reference.
            function getMarkerTypeReference(type, source, target) {
                var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
                result.objectFlags |= 8192 /* MarkerType */;
                return result;
            }
            // Return an array containing the variance of each type parameter. The variance is effectively
            // a digest of the type comparisons that occur for each type argument when instantiations of the
            // generic type are structurally compared. We infer the variance information by comparing
            // instantiations of the generic type for type arguments with known relations. The function
            // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function
            // has been invoked recursively for the given generic type.
            function getVariances(type) {
                if (!strictFunctionTypes) {
                    return ts.emptyArray;
                }
                var typeParameters = type.typeParameters || ts.emptyArray;
                var variances = type.variances;
                if (!variances) {
                    if (type === globalArrayType || type === globalReadonlyArrayType) {
                        // Arrays are known to be covariant, no need to spend time computing this
                        variances = [1 /* Covariant */];
                    }
                    else {
                        // The emptyArray singleton is used to signal a recursive invocation.
                        type.variances = ts.emptyArray;
                        variances = [];
                        for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
                            var tp = typeParameters_1[_i];
                            // We first compare instantiations where the type parameter is replaced with
                            // marker types that have a known subtype relationship. From this we can infer
                            // invariance, covariance, contravariance or bivariance.
                            var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType);
                            var typeWithSub = getMarkerTypeReference(type, tp, markerSubType);
                            var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
                                (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
                            // If the instantiations appear to be related bivariantly it may be because the
                            // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
                            // type). To determine this we compare instantiations where the type parameter is
                            // replaced with marker types that are known to be unrelated.
                            if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) {
                                variance = 4 /* Independent */;
                            }
                            variances.push(variance);
                        }
                    }
                    type.variances = variances;
                }
                return variances;
            }
            // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
            // See comment at call in recursiveTypeRelatedTo for when this case matters.
            function hasCovariantVoidArgument(type, variances) {
                for (var i = 0; i < variances.length; i++) {
                    if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) {
                        return true;
                    }
                }
                return false;
            }
            function isUnconstrainedTypeParameter(type) {
                return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
            }
            function isTypeReferenceWithGenericArguments(type) {
                return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
            }
            /**
             * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
             *   where A.id=111 and number.id=12
             */
            function getTypeReferenceId(type, typeParameters, depth) {
                if (depth === void 0) {
                    depth = 0;
                }
                var result = "" + type.target.id;
                for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) {
                    var t = _a[_i];
                    if (isUnconstrainedTypeParameter(t)) {
                        var index = typeParameters.indexOf(t);
                        if (index < 0) {
                            index = typeParameters.length;
                            typeParameters.push(t);
                        }
                        result += "=" + index;
                    }
                    else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
                        result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
                    }
                    else {
                        result += "-" + t.id;
                    }
                }
                return result;
            }
            /**
             * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
             * For other cases, the types ids are used.
             */
            function getRelationKey(source, target, relation) {
                if (relation === identityRelation && source.id > target.id) {
                    var temp = source;
                    source = target;
                    target = temp;
                }
                if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
                    var typeParameters = [];
                    return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters);
                }
                return source.id + "," + target.id;
            }
            // Invoke the callback for each underlying property symbol of the given symbol and return the first
            // value that isn't undefined.
            function forEachProperty(prop, callback) {
                if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
                    for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
                        var t = _a[_i];
                        var p = getPropertyOfType(t, prop.escapedName);
                        var result = p && forEachProperty(p, callback);
                        if (result) {
                            return result;
                        }
                    }
                    return undefined;
                }
                return callback(prop);
            }
            // Return the declaring class type of a property or undefined if property not declared in class
            function getDeclaringClass(prop) {
                return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
            }
            // Return true if some underlying source property is declared in a class that derives
            // from the given base class.
            function isPropertyInClassDerivedFrom(prop, baseClass) {
                return forEachProperty(prop, function (sp) {
                    var sourceClass = getDeclaringClass(sp);
                    return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
                });
            }
            // Return true if source property is a valid override of protected parts of target property.
            function isValidOverrideOf(sourceProp, targetProp) {
                return !forEachProperty(targetProp, function (tp) {
                    return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
                        !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false;
                });
            }
            // Return true if the given class derives from each of the declaring classes of the protected
            // constituents of the given property.
            function isClassDerivedFromDeclaringClasses(checkClass, prop) {
                return forEachProperty(prop, function (p) {
                    return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
                        !hasBaseType(checkClass, getDeclaringClass(p)) : false;
                }) ? undefined : checkClass;
            }
            // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
            // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
            // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
            // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
            // levels, but unequal at some level beyond that.
            function isDeeplyNestedType(type, stack, depth) {
                // We track all object types that have an associated symbol (representing the origin of the type)
                if (depth >= 5 && type.flags & 131072 /* Object */) {
                    var symbol = type.symbol;
                    if (symbol) {
                        var count = 0;
                        for (var i = 0; i < depth; i++) {
                            var t = stack[i];
                            if (t.flags & 131072 /* Object */ && t.symbol === symbol) {
                                count++;
                                if (count >= 5)
                                    return true;
                            }
                        }
                    }
                }
                return false;
            }
            function isPropertyIdenticalTo(sourceProp, targetProp) {
                return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
            }
            function compareProperties(sourceProp, targetProp, compareTypes) {
                // Two members are considered identical when
                // - they are public properties with identical names, optionality, and types,
                // - they are private or protected properties originating in the same declaration and having identical types
                if (sourceProp === targetProp) {
                    return -1 /* True */;
                }
                var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
                var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
                if (sourcePropAccessibility !== targetPropAccessibility) {
                    return 0 /* False */;
                }
                if (sourcePropAccessibility) {
                    if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
                        return 0 /* False */;
                    }
                }
                else {
                    if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
                        return 0 /* False */;
                    }
                }
                if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
                    return 0 /* False */;
                }
                return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
            }
            function isMatchingSignature(source, target, partialMatch) {
                var sourceParameterCount = getParameterCount(source);
                var targetParameterCount = getParameterCount(target);
                var sourceMinArgumentCount = getMinArgumentCount(source);
                var targetMinArgumentCount = getMinArgumentCount(target);
                var sourceHasRestParameter = hasEffectiveRestParameter(source);
                var targetHasRestParameter = hasEffectiveRestParameter(target);
                // A source signature matches a target signature if the two signatures have the same number of required,
                // optional, and rest parameters.
                if (sourceParameterCount === targetParameterCount &&
                    sourceMinArgumentCount === targetMinArgumentCount &&
                    sourceHasRestParameter === targetHasRestParameter) {
                    return true;
                }
                // A source signature partially matches a target signature if the target signature has no fewer required
                // parameters and no more overall parameters than the source signature (where a signature with a rest
                // parameter is always considered to have more overall parameters than one without).
                var sourceRestCount = sourceHasRestParameter ? 1 : 0;
                var targetRestCount = targetHasRestParameter ? 1 : 0;
                if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount ||
                    sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) {
                    return true;
                }
                return false;
            }
            /**
             * See signatureRelatedTo, compareSignaturesIdentical
             */
            function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
                // TODO (drosen): De-duplicate code between related functions.
                if (source === target) {
                    return -1 /* True */;
                }
                if (!(isMatchingSignature(source, target, partialMatch))) {
                    return 0 /* False */;
                }
                // Check that the two signatures have the same number of type parameters. We might consider
                // also checking that any type parameter constraints match, but that would require instantiating
                // the constraints with a common set of type arguments to get relatable entities in places where
                // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile,
                // particularly as we're comparing erased versions of the signatures below.
                if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
                    return 0 /* False */;
                }
                // Spec 1.0 Section 3.8.3 & 3.8.4:
                // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N
                source = getErasedSignature(source);
                target = getErasedSignature(target);
                var result = -1 /* True */;
                if (!ignoreThisTypes) {
                    var sourceThisType = getThisTypeOfSignature(source);
                    if (sourceThisType) {
                        var targetThisType = getThisTypeOfSignature(target);
                        if (targetThisType) {
                            var related = compareTypes(sourceThisType, targetThisType);
                            if (!related) {
                                return 0 /* False */;
                            }
                            result &= related;
                        }
                    }
                }
                var targetLen = getParameterCount(target);
                for (var i = 0; i < targetLen; i++) {
                    var s = getTypeAtPosition(source, i);
                    var t = getTypeAtPosition(target, i);
                    var related = compareTypes(s, t);
                    if (!related) {
                        return 0 /* False */;
                    }
                    result &= related;
                }
                if (!ignoreReturnTypes) {
                    var sourceTypePredicate = getTypePredicateOfSignature(source);
                    var targetTypePredicate = getTypePredicateOfSignature(target);
                    result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined
                        ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes)
                        // If they're both type predicates their return types will both be `boolean`, so no need to compare those.
                        : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
                }
                return result;
            }
            function compareTypePredicatesIdentical(source, target, compareTypes) {
                return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type);
            }
            function literalTypesWithSameBaseType(types) {
                var commonBaseType;
                for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
                    var t = types_8[_i];
                    var baseType = getBaseTypeOfLiteralType(t);
                    if (!commonBaseType) {
                        commonBaseType = baseType;
                    }
                    if (baseType === t || baseType !== commonBaseType) {
                        return false;
                    }
                }
                return true;
            }
            // When the candidate types are all literal types with the same base type, return a union
            // of those literal types. Otherwise, return the leftmost type for which no type to the
            // right is a supertype.
            function getSupertypeOrUnion(types) {
                return literalTypesWithSameBaseType(types) ?
                    getUnionType(types) :
                    ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
            }
            function getCommonSupertype(types) {
                if (!strictNullChecks) {
                    return getSupertypeOrUnion(types);
                }
                var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); });
                return primaryTypes.length ?
                    getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) :
                    getUnionType(types, 2 /* Subtype */);
            }
            // Return the leftmost type for which no type to the right is a subtype.
            function getCommonSubtype(types) {
                return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
            }
            function isArrayType(type) {
                return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType;
            }
            function isReadonlyArrayType(type) {
                return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
            }
            function isArrayLikeType(type) {
                // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
                // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
                return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
                    !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
            }
            function isEmptyArrayLiteralType(type) {
                var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
                return elementType === undefinedWideningType || elementType === implicitNeverType;
            }
            function isTupleLikeType(type) {
                return isTupleType(type) || !!getPropertyOfType(type, "0");
            }
            function getTupleElementType(type, index) {
                return isTupleType(type) ?
                    index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) :
                    getTypeOfPropertyOfType(type, "" + index);
            }
            function isNeitherUnitTypeNorNever(type) {
                return !(type.flags & (27072 /* Unit */ | 32768 /* Never */));
            }
            function isUnitType(type) {
                return !!(type.flags & 27072 /* Unit */);
            }
            function isLiteralType(type) {
                return type.flags & 16 /* Boolean */ ? true :
                    type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
                        isUnitType(type);
            }
            function getBaseTypeOfLiteralType(type) {
                return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
                    type.flags & 64 /* StringLiteral */ ? stringType :
                        type.flags & 128 /* NumberLiteral */ ? numberType :
                            type.flags & 256 /* BooleanLiteral */ ? booleanType :
                                type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
                                    type;
            }
            function getWidenedLiteralType(type) {
                return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
                    type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType :
                        type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType :
                            type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType :
                                type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
                                    type;
            }
            function getWidenedUniqueESSymbolType(type) {
                return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType :
                    type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
                        type;
            }
            function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
                if (!isLiteralOfContextualType(type, contextualType)) {
                    type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
                }
                return type;
            }
            /**
             * Check if a Type was written as a tuple type literal.
             * Prefer using isTupleLikeType() unless the use of `elementTypes` is required.
             */
            function isTupleType(type) {
                return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
            }
            function getRestTypeOfTupleType(type) {
                return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined;
            }
            function getRestArrayTypeOfTupleType(type) {
                var restType = getRestTypeOfTupleType(type);
                return restType && createArrayType(restType);
            }
            function getLengthOfTupleType(type) {
                return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
            }
            function getFalsyFlagsOfTypes(types) {
                var result = 0;
                for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
                    var t = types_9[_i];
                    result |= getFalsyFlags(t);
                }
                return result;
            }
            // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
            // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
            // no flags for all other types (including non-falsy literal types).
            function getFalsyFlags(type) {
                return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
                    type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 :
                        type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 :
                            type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 :
                                type.flags & 29148 /* PossiblyFalsy */;
            }
            function removeDefinitelyFalsyTypes(type) {
                return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ?
                    filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) :
                    type;
            }
            function extractDefinitelyFalsyTypes(type) {
                return mapType(type, getDefinitelyFalsyPartOfType);
            }
            function getDefinitelyFalsyPartOfType(type) {
                return type.flags & 4 /* String */ ? emptyStringType :
                    type.flags & 8 /* Number */ ? zeroType :
                        type === regularFalseType ||
                            type === falseType ||
                            type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) ||
                            type.flags & 64 /* StringLiteral */ && type.value === "" ||
                            type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type :
                            neverType;
            }
            /**
             * Add undefined or null or both to a type if they are missing.
             * @param type - type to add undefined and/or null to if not present
             * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
             */
            function getNullableType(type, flags) {
                var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */);
                return missing === 0 ? type :
                    missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) :
                        missing === 16384 /* Null */ ? getUnionType([type, nullType]) :
                            getUnionType([type, undefinedType, nullType]);
            }
            function getOptionalType(type) {
                ts.Debug.assert(strictNullChecks);
                return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]);
            }
            function getGlobalNonNullableTypeInstantiation(type) {
                if (!deferredGlobalNonNullableTypeAlias) {
                    deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
                }
                // Use NonNullable global type alias if available to improve quick info/declaration emit
                if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
                    return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
                }
                return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
            }
            function getNonNullableType(type) {
                return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
            }
            /**
             * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
             * with no call or construct signatures.
             */
            function isObjectTypeWithInferableIndex(type) {
                return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 &&
                    !typeHasCallOrConstructSignatures(type);
            }
            function createSymbolWithType(source, type) {
                var symbol = createSymbol(source.flags, source.escapedName);
                symbol.declarations = source.declarations;
                symbol.parent = source.parent;
                symbol.type = type;
                symbol.target = source;
                if (source.valueDeclaration) {
                    symbol.valueDeclaration = source.valueDeclaration;
                }
                if (source.nameType) {
                    symbol.nameType = source.nameType;
                }
                return symbol;
            }
            function transformTypeOfMembers(type, f) {
                var members = ts.createSymbolTable();
                for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
                    var property = _a[_i];
                    var original = getTypeOfSymbol(property);
                    var updated = f(original);
                    members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
                }
                return members;
            }
            /**
             * If the the provided object literal is subject to the excess properties check,
             * create a new that is exempt. Recursively mark object literal members as exempt.
             * Leave signatures alone since they are not subject to the check.
             */
            function getRegularTypeOfObjectLiteral(type) {
                if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) {
                    return type;
                }
                var regularType = type.regularType;
                if (regularType) {
                    return regularType;
                }
                var resolved = type;
                var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
                var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
                regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */;
                regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */);
                type.regularType = regularNew;
                return regularNew;
            }
            function createWideningContext(parent, propertyName, siblings) {
                return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
            }
            function getSiblingsOfContext(context) {
                if (!context.siblings) {
                    var siblings_1 = [];
                    for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
                        var type = _a[_i];
                        if (isObjectLiteralType(type)) {
                            var prop = getPropertyOfObjectType(type, context.propertyName);
                            if (prop) {
                                forEachType(getTypeOfSymbol(prop), function (t) {
                                    siblings_1.push(t);
                                });
                            }
                        }
                    }
                    context.siblings = siblings_1;
                }
                return context.siblings;
            }
            function getPropertiesOfContext(context) {
                if (!context.resolvedProperties) {
                    var names = ts.createMap();
                    for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
                        var t = _a[_i];
                        if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
                            for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
                                var prop = _c[_b];
                                names.set(prop.escapedName, prop);
                            }
                        }
                    }
                    context.resolvedProperties = ts.arrayFrom(names.values());
                }
                return context.resolvedProperties;
            }
            function getWidenedProperty(prop, context) {
                if (!(prop.flags & 4 /* Property */)) {
                    // Since get accessors already widen their return value there is no need to
                    // widen accessor based properties here.
                    return prop;
                }
                var original = getTypeOfSymbol(prop);
                var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
                var widened = getWidenedTypeWithContext(original, propContext);
                return widened === original ? prop : createSymbolWithType(prop, widened);
            }
            function getUndefinedProperty(prop) {
                var cached = undefinedProperties.get(prop.escapedName);
                if (cached) {
                    return cached;
                }
                var result = createSymbolWithType(prop, undefinedType);
                result.flags |= 16777216 /* Optional */;
                undefinedProperties.set(prop.escapedName, result);
                return result;
            }
            function getWidenedTypeOfObjectLiteral(type, context) {
                var members = ts.createSymbolTable();
                for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
                    var prop = _a[_i];
                    members.set(prop.escapedName, getWidenedProperty(prop, context));
                }
                if (context) {
                    for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
                        var prop = _c[_b];
                        if (!members.has(prop.escapedName)) {
                            members.set(prop.escapedName, getUndefinedProperty(prop));
                        }
                    }
                }
                var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
                var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
                var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
                result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening
                return result;
            }
            function getWidenedType(type) {
                return getWidenedTypeWithContext(type, /*context*/ undefined);
            }
            function getWidenedTypeWithContext(type, context) {
                if (type.flags & 402653184 /* RequiresWidening */) {
                    if (type.flags & 24576 /* Nullable */) {
                        return anyType;
                    }
                    if (isObjectLiteralType(type)) {
                        return getWidenedTypeOfObjectLiteral(type, context);
                    }
                    if (type.flags & 262144 /* Union */) {
                        var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
                        var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
                        // Widening an empty object literal transitions from a highly restrictive type to
                        // a highly inclusive one. For that reason we perform subtype reduction here if the
                        // union includes empty object types (e.g. reducing {} | string to just {}).
                        return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
                    }
                    if (isArrayType(type) || isTupleType(type)) {
                        return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType));
                    }
                }
                return type;
            }
            /**
             * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
             * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
             * getWidenedType. But in some cases getWidenedType is called without reporting errors
             * (type argument inference is an example).
             *
             * The return value indicates whether an error was in fact reported. The particular circumstances
             * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
             * an object literal property (arbitrarily deeply), this function reports an error. If no error is
             * reported, reportImplicitAnyError is a suitable fallback to report a general error.
             */
            function reportWideningErrorsInType(type) {
                var errorReported = false;
                if (type.flags & 134217728 /* ContainsWideningType */) {
                    if (type.flags & 262144 /* Union */) {
                        if (ts.some(type.types, isEmptyObjectType)) {
                            errorReported = true;
                        }
                        else {
                            for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
                                var t = _a[_i];
                                if (reportWideningErrorsInType(t)) {
                                    errorReported = true;
                                }
                            }
                        }
                    }
                    if (isArrayType(type) || isTupleType(type)) {
                        for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) {
                            var t = _c[_b];
                            if (reportWideningErrorsInType(t)) {
                                errorReported = true;
                            }
                        }
                    }
                    if (isObjectLiteralType(type)) {
                        for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
                            var p = _e[_d];
                            var t = getTypeOfSymbol(p);
                            if (t.flags & 134217728 /* ContainsWideningType */) {
                                if (!reportWideningErrorsInType(t)) {
                                    error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
                                }
                                errorReported = true;
                            }
                        }
                    }
                }
                return errorReported;
            }
            function reportImplicitAnyError(declaration, type) {
                var typeAsString = typeToString(getWidenedType(type));
                var diagnostic;
                switch (declaration.kind) {
                    case 202 /* BinaryExpression */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                        diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type;
                        break;
                    case 149 /* Parameter */:
                        diagnostic = declaration.dotDotDotToken ?
                            ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type :
                            ts.Diagnostics.Parameter_0_implicitly_has_an_1_type;
                        break;
                    case 184 /* BindingElement */:
                        diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
                        break;
                    case 237 /* FunctionDeclaration */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        if (!declaration.name) {
                            error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
                            return;
                        }
                        diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
                        break;
                    case 179 /* MappedType */:
                        error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
                        return;
                    default:
                        diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type;
                }
                error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
            }
            function reportErrorsFromWidening(declaration, type) {
                if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) {
                    // Report implicit any error within type if possible, otherwise report error on declaration
                    if (!reportWideningErrorsInType(type)) {
                        reportImplicitAnyError(declaration, type);
                    }
                }
            }
            function forEachMatchingParameterType(source, target, callback) {
                var sourceCount = getParameterCount(source);
                var targetCount = getParameterCount(target);
                var sourceRestType = getEffectiveRestType(source);
                var targetRestType = getEffectiveRestType(target);
                var paramCount = targetRestType ? Math.min(targetCount - 1, sourceCount) :
                    sourceRestType ? targetCount :
                        Math.min(sourceCount, targetCount);
                var sourceThisType = getThisTypeOfSignature(source);
                if (sourceThisType) {
                    var targetThisType = getThisTypeOfSignature(target);
                    if (targetThisType) {
                        callback(sourceThisType, targetThisType);
                    }
                }
                for (var i = 0; i < paramCount; i++) {
                    callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
                }
                if (targetRestType) {
                    callback(getRestTypeAtPosition(source, paramCount), targetRestType);
                }
            }
            function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
                var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
                var context = mapper;
                context.typeParameters = typeParameters;
                context.signature = signature;
                context.inferences = inferences;
                context.flags = flags;
                context.compareTypes = compareTypes || compareTypesAssignable;
                return context;
                function mapper(t) {
                    for (var i = 0; i < inferences.length; i++) {
                        if (t === inferences[i].typeParameter) {
                            inferences[i].isFixed = true;
                            return getInferredType(context, i);
                        }
                    }
                    return t;
                }
            }
            function createInferenceInfo(typeParameter) {
                return {
                    typeParameter: typeParameter,
                    candidates: undefined,
                    contraCandidates: undefined,
                    inferredType: undefined,
                    priority: undefined,
                    topLevel: true,
                    isFixed: false
                };
            }
            function cloneInferenceInfo(inference) {
                return {
                    typeParameter: inference.typeParameter,
                    candidates: inference.candidates && inference.candidates.slice(),
                    contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
                    inferredType: inference.inferredType,
                    priority: inference.priority,
                    topLevel: inference.topLevel,
                    isFixed: inference.isFixed
                };
            }
            // Return true if the given type could possibly reference a type parameter for which
            // we perform type inference (i.e. a type parameter of a generic function). We cache
            // results for union and intersection types for performance reasons.
            function couldContainTypeVariables(type) {
                var objectFlags = ts.getObjectFlags(type);
                return !!(type.flags & 15794176 /* Instantiable */ ||
                    objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) ||
                    objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) ||
                    objectFlags & 32 /* Mapped */ ||
                    type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type));
            }
            function couldUnionOrIntersectionContainTypeVariables(type) {
                if (type.couldContainTypeVariables === undefined) {
                    type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables);
                }
                return type.couldContainTypeVariables;
            }
            function isTypeParameterAtTopLevel(type, typeParameter) {
                return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); });
            }
            /** Create an object with properties named in the string literal type. Every property has type `any` */
            function createEmptyObjectTypeFromStringLiteral(type) {
                var members = ts.createSymbolTable();
                forEachType(type, function (t) {
                    if (!(t.flags & 64 /* StringLiteral */)) {
                        return;
                    }
                    var name = ts.escapeLeadingUnderscores(t.value);
                    var literalProp = createSymbol(4 /* Property */, name);
                    literalProp.type = anyType;
                    if (t.symbol) {
                        literalProp.declarations = t.symbol.declarations;
                        literalProp.valueDeclaration = t.symbol.valueDeclaration;
                    }
                    members.set(name, literalProp);
                });
                var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
                return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
            }
            /**
             * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
             * an object type with the same set of properties as the source type, where the type of each
             * property is computed by inferring from the source property type to X for the type
             * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
             */
            function inferTypeForHomomorphicMappedType(source, target) {
                var key = source.id + "," + target.id;
                if (reverseMappedCache.has(key)) {
                    return reverseMappedCache.get(key);
                }
                reverseMappedCache.set(key, undefined);
                var type = createReverseMappedType(source, target);
                reverseMappedCache.set(key, type);
                return type;
            }
            function createReverseMappedType(source, target) {
                var properties = getPropertiesOfType(source);
                if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
                    return undefined;
                }
                // If any property contains context sensitive functions that have been skipped, the source type
                // is incomplete and we can't infer a meaningful input type.
                for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
                    var prop = properties_4[_i];
                    if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) {
                        return undefined;
                    }
                }
                // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
                // applied to the element type(s).
                if (isArrayType(source)) {
                    return createArrayType(inferReverseMappedType(source.typeArguments[0], target));
                }
                if (isReadonlyArrayType(source)) {
                    return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target));
                }
                if (isTupleType(source)) {
                    var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); });
                    var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
                        getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
                    return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames);
                }
                // For all other object types we infer a new object type where the reverse mapping has been
                // applied to the type of each property.
                var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
                reversed.source = source;
                reversed.mappedType = target;
                return reversed;
            }
            function getTypeOfReverseMappedSymbol(symbol) {
                return inferReverseMappedType(symbol.propertyType, symbol.mappedType);
            }
            function inferReverseMappedType(sourceType, target) {
                var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target));
                var templateType = getTemplateTypeFromMappedType(target);
                var inference = createInferenceInfo(typeParameter);
                inferTypes([inference], sourceType, templateType);
                return getTypeFromInference(inference);
            }
            function getUnmatchedProperty(source, target, requireOptionalProperties) {
                var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
                for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
                    var targetProp = properties_5[_i];
                    if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) {
                        var sourceProp = getPropertyOfType(source, targetProp.escapedName);
                        if (!sourceProp) {
                            return targetProp;
                        }
                    }
                }
                return undefined;
            }
            function tupleTypesDefinitelyUnrelated(source, target) {
                return target.target.minLength > source.target.minLength ||
                    !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
            }
            function typesDefinitelyUnrelated(source, target) {
                // Two tuple types with incompatible arities are definitely unrelated.
                // Two object types that each have a property that is unmatched in the other are definitely unrelated.
                return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
                    !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false);
            }
            function getTypeFromInference(inference) {
                return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
                    inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
                        emptyObjectType;
            }
            function inferTypes(inferences, originalSource, originalTarget, priority) {
                if (priority === void 0) {
                    priority = 0;
                }
                var symbolStack;
                var visited;
                var contravariant = false;
                var propagationType;
                inferFromTypes(originalSource, originalTarget);
                function inferFromTypes(source, target) {
                    if (!couldContainTypeVariables(target)) {
                        return;
                    }
                    if (source === wildcardType) {
                        // We are inferring from an 'any' type. We want to infer this type for every type parameter
                        // referenced in the target type, so we record it as the propagation type and infer from the
                        // target to itself. Then, as we find candidates we substitute the propagation type.
                        var savePropagationType = propagationType;
                        propagationType = source;
                        inferFromTypes(target, target);
                        propagationType = savePropagationType;
                        return;
                    }
                    if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
                        // Source and target are types originating in the same generic type alias declaration.
                        // Simply infer from source type arguments to target type arguments.
                        var sourceTypes = source.aliasTypeArguments;
                        var targetTypes = target.aliasTypeArguments;
                        for (var i = 0; i < sourceTypes.length; i++) {
                            inferFromTypes(sourceTypes[i], targetTypes[i]);
                        }
                        return;
                    }
                    if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) ||
                        source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) {
                        // Source and target are both unions or both intersections. If source and target
                        // are the same type, just relate each constituent type to itself.
                        if (source === target) {
                            for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
                                var t = _a[_i];
                                inferFromTypes(t, t);
                            }
                            return;
                        }
                        // Find each source constituent type that has an identically matching target constituent
                        // type, and for each such type infer from the type to itself. When inferring from a
                        // type to itself we effectively find all type parameter occurrences within that type
                        // and infer themselves as their type arguments. We have special handling for numeric
                        // and string literals because the number and string types are not represented as unions
                        // of all their possible values.
                        var matchingTypes = void 0;
                        for (var _b = 0, _c = source.types; _b < _c.length; _b++) {
                            var t = _c[_b];
                            if (typeIdenticalToSomeType(t, target.types)) {
                                (matchingTypes || (matchingTypes = [])).push(t);
                                inferFromTypes(t, t);
                            }
                            else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) {
                                var b = getBaseTypeOfLiteralType(t);
                                if (typeIdenticalToSomeType(b, target.types)) {
                                    (matchingTypes || (matchingTypes = [])).push(t, b);
                                }
                            }
                        }
                        // Next, to improve the quality of inferences, reduce the source and target types by
                        // removing the identically matched constituents. For example, when inferring from
                        // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'.
                        if (matchingTypes) {
                            source = removeTypesFromUnionOrIntersection(source, matchingTypes);
                            target = removeTypesFromUnionOrIntersection(target, matchingTypes);
                        }
                    }
                    if (target.flags & 2162688 /* TypeVariable */) {
                        // If target is a type parameter, make an inference, unless the source type contains
                        // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
                        // Because the anyFunctionType is internal, it should not be exposed to the user by adding
                        // it as an inference candidate. Hopefully, a better candidate will come along that does
                        // not contain anyFunctionType when we come back to this argument for its second round
                        // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
                        // when constructing types from type parameters that had no inference candidates).
                        if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) {
                            return;
                        }
                        var inference = getInferenceInfoForType(target);
                        if (inference) {
                            if (!inference.isFixed) {
                                if (inference.priority === undefined || priority < inference.priority) {
                                    inference.candidates = undefined;
                                    inference.contraCandidates = undefined;
                                    inference.priority = priority;
                                }
                                if (priority === inference.priority) {
                                    var candidate = propagationType || source;
                                    if (contravariant) {
                                        inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
                                    }
                                    else {
                                        inference.candidates = ts.append(inference.candidates, candidate);
                                    }
                                }
                                if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
                                    inference.topLevel = false;
                                }
                            }
                            return;
                        }
                    }
                    if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
                        // If source and target are references to the same generic type, infer from type arguments
                        var sourceTypes = source.typeArguments || ts.emptyArray;
                        var targetTypes = target.typeArguments || ts.emptyArray;
                        var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
                        var variances = getVariances(source.target);
                        for (var i = 0; i < count; i++) {
                            if (i < variances.length && variances[i] === 2 /* Contravariant */) {
                                inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
                            }
                            else {
                                inferFromTypes(sourceTypes[i], targetTypes[i]);
                            }
                        }
                    }
                    else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) {
                        contravariant = !contravariant;
                        inferFromTypes(source.type, target.type);
                        contravariant = !contravariant;
                    }
                    else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) {
                        var empty = createEmptyObjectTypeFromStringLiteral(source);
                        contravariant = !contravariant;
                        var savePriority = priority;
                        priority |= 16 /* LiteralKeyof */;
                        inferFromTypes(empty, target.type);
                        priority = savePriority;
                        contravariant = !contravariant;
                    }
                    else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) {
                        inferFromTypes(source.objectType, target.objectType);
                        inferFromTypes(source.indexType, target.indexType);
                    }
                    else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) {
                        inferFromTypes(source.checkType, target.checkType);
                        inferFromTypes(source.extendsType, target.extendsType);
                        inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
                        inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
                    }
                    else if (target.flags & 4194304 /* Conditional */) {
                        inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
                    }
                    else if (target.flags & 786432 /* UnionOrIntersection */) {
                        var targetTypes = target.types;
                        var typeVariableCount = 0;
                        var typeVariable = void 0;
                        // First infer to each type in union or intersection that isn't a type variable
                        for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
                            var t = targetTypes_3[_d];
                            if (getInferenceInfoForType(t)) {
                                typeVariable = t;
                                typeVariableCount++;
                            }
                            else {
                                inferFromTypes(source, t);
                            }
                        }
                        // Next, if target containings a single naked type variable, make a secondary inference to that type
                        // variable. This gives meaningful results for union types in co-variant positions and intersection
                        // types in contra-variant positions (such as callback parameters).
                        if (typeVariableCount === 1) {
                            var savePriority = priority;
                            priority |= 1 /* NakedTypeVariable */;
                            inferFromTypes(source, typeVariable);
                            priority = savePriority;
                        }
                    }
                    else if (source.flags & 262144 /* Union */) {
                        // Source is a union or intersection type, infer from each constituent type
                        var sourceTypes = source.types;
                        for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
                            var sourceType = sourceTypes_3[_e];
                            inferFromTypes(sourceType, target);
                        }
                    }
                    else {
                        if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) {
                            var apparentSource = getApparentType(source);
                            // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
                            // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
                            // with the simplified source.
                            if (apparentSource !== source && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) {
                                return inferFromTypes(apparentSource, target);
                            }
                            source = apparentSource;
                        }
                        if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) {
                            var key = source.id + "," + target.id;
                            if (visited && visited.get(key)) {
                                return;
                            }
                            (visited || (visited = ts.createMap())).set(key, true);
                            // If we are already processing another target type with the same associated symbol (such as
                            // an instantiation of the same generic type), we do not explore this target as it would yield
                            // no further inferences. We exclude the static side of classes from this check since it shares
                            // its symbol with the instance side which would lead to false positives.
                            var isNonConstructorObject = target.flags & 131072 /* Object */ &&
                                !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
                            var symbol = isNonConstructorObject ? target.symbol : undefined;
                            if (symbol) {
                                if (ts.contains(symbolStack, symbol)) {
                                    return;
                                }
                                (symbolStack || (symbolStack = [])).push(symbol);
                                inferFromObjectTypes(source, target);
                                symbolStack.pop();
                            }
                            else {
                                inferFromObjectTypes(source, target);
                            }
                        }
                    }
                }
                function inferFromContravariantTypes(source, target) {
                    if (strictFunctionTypes || priority & 64 /* AlwaysStrict */) {
                        contravariant = !contravariant;
                        inferFromTypes(source, target);
                        contravariant = !contravariant;
                    }
                    else {
                        inferFromTypes(source, target);
                    }
                }
                function getInferenceInfoForType(type) {
                    if (type.flags & 2162688 /* TypeVariable */) {
                        for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
                            var inference = inferences_1[_i];
                            if (type === inference.typeParameter) {
                                return inference;
                            }
                        }
                    }
                    return undefined;
                }
                function inferFromObjectTypes(source, target) {
                    if (isGenericMappedType(source) && isGenericMappedType(target)) {
                        // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
                        // from S to T and from X to Y.
                        inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
                        inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
                    }
                    if (ts.getObjectFlags(target) & 32 /* Mapped */) {
                        var constraintType = getConstraintTypeFromMappedType(target);
                        if (constraintType.flags & 1048576 /* Index */) {
                            // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
                            // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
                            // type and then make a secondary inference from that type to T. We make a secondary inference
                            // such that direct inferences to T get priority over inferences to Partial<T>, for example.
                            var inference = getInferenceInfoForType(constraintType.type);
                            if (inference && !inference.isFixed) {
                                var inferredType = inferTypeForHomomorphicMappedType(source, target);
                                if (inferredType) {
                                    var savePriority = priority;
                                    priority |= 2 /* HomomorphicMappedType */;
                                    inferFromTypes(inferredType, inference.typeParameter);
                                    priority = savePriority;
                                }
                            }
                            return;
                        }
                        if (constraintType.flags & 65536 /* TypeParameter */) {
                            // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
                            // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
                            var savePriority = priority;
                            priority |= 4 /* MappedTypeConstraint */;
                            inferFromTypes(getIndexType(source), constraintType);
                            priority = savePriority;
                            inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target));
                            return;
                        }
                    }
                    // Infer from the members of source and target only if the two types are possibly related
                    if (!typesDefinitelyUnrelated(source, target)) {
                        inferFromProperties(source, target);
                        inferFromSignatures(source, target, 0 /* Call */);
                        inferFromSignatures(source, target, 1 /* Construct */);
                        inferFromIndexTypes(source, target);
                    }
                }
                function inferFromProperties(source, target) {
                    if (isTupleType(source)) {
                        if (isTupleType(target)) {
                            var sourceLength = getLengthOfTupleType(source);
                            var targetLength = getLengthOfTupleType(target);
                            var sourceRestType = getRestTypeOfTupleType(source);
                            var targetRestType = getRestTypeOfTupleType(target);
                            var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
                            for (var i = 0; i < fixedLength; i++) {
                                inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]);
                            }
                            if (targetRestType) {
                                var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : [];
                                if (sourceRestType) {
                                    types.push(sourceRestType);
                                }
                                if (types.length) {
                                    inferFromTypes(getUnionType(types), targetRestType);
                                }
                            }
                            return;
                        }
                        if (isArrayType(target)) {
                            inferFromIndexTypes(source, target);
                            return;
                        }
                    }
                    var properties = getPropertiesOfObjectType(target);
                    for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
                        var targetProp = properties_6[_i];
                        var sourceProp = getPropertyOfType(source, targetProp.escapedName);
                        if (sourceProp) {
                            inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
                        }
                    }
                }
                function inferFromSignatures(source, target, kind) {
                    var sourceSignatures = getSignaturesOfType(source, kind);
                    var targetSignatures = getSignaturesOfType(target, kind);
                    var sourceLen = sourceSignatures.length;
                    var targetLen = targetSignatures.length;
                    var len = sourceLen < targetLen ? sourceLen : targetLen;
                    var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
                    for (var i = 0; i < len; i++) {
                        inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
                    }
                }
                function inferFromSignature(source, target, skipParameters) {
                    if (!skipParameters) {
                        forEachMatchingParameterType(source, target, inferFromContravariantTypes);
                    }
                    var sourceTypePredicate = getTypePredicateOfSignature(source);
                    var targetTypePredicate = getTypePredicateOfSignature(target);
                    if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
                        inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
                    }
                    else {
                        inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
                    }
                }
                function inferFromIndexTypes(source, target) {
                    var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
                    if (targetStringIndexType) {
                        var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
                            getImplicitIndexTypeOfType(source, 0 /* String */);
                        if (sourceIndexType) {
                            inferFromTypes(sourceIndexType, targetStringIndexType);
                        }
                    }
                    var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
                    if (targetNumberIndexType) {
                        var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
                            getIndexTypeOfType(source, 0 /* String */) ||
                            getImplicitIndexTypeOfType(source, 1 /* Number */);
                        if (sourceIndexType) {
                            inferFromTypes(sourceIndexType, targetNumberIndexType);
                        }
                    }
                }
            }
            function typeIdenticalToSomeType(type, types) {
                for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
                    var t = types_10[_i];
                    if (isTypeIdenticalTo(t, type)) {
                        return true;
                    }
                }
                return false;
            }
            /**
             * Return a new union or intersection type computed by removing a given set of types
             * from a given union or intersection type.
             */
            function removeTypesFromUnionOrIntersection(type, typesToRemove) {
                var reducedTypes = [];
                for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
                    var t = _a[_i];
                    if (!typeIdenticalToSomeType(t, typesToRemove)) {
                        reducedTypes.push(t);
                    }
                }
                return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes);
            }
            function hasPrimitiveConstraint(type) {
                var constraint = getConstraintOfTypeParameter(type);
                return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */);
            }
            function isObjectLiteralType(type) {
                return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
            }
            function widenObjectLiteralCandidates(candidates) {
                if (candidates.length > 1) {
                    var objectLiterals = ts.filter(candidates, isObjectLiteralType);
                    if (objectLiterals.length) {
                        var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */));
                        return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]);
                    }
                }
                return candidates;
            }
            function getContravariantInference(inference) {
                return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
            }
            function getCovariantInference(inference, signature) {
                // Extract all object literal types and replace them with a single widened and normalized type.
                var candidates = widenObjectLiteralCandidates(inference.candidates);
                // We widen inferred literal types if
                // all inferences were made to top-level occurrences of the type parameter, and
                // the type parameter has no constraint or its constraint includes no primitive or literal types, and
                // the type parameter was fixed during inference or does not occur at top-level in the return type.
                var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
                var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
                    (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
                var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
                    widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
                        candidates;
                // If all inferences were made from a position that implies a combined result, infer a union type.
                // Otherwise, infer a common supertype.
                var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ?
                    getUnionType(baseCandidates, 2 /* Subtype */) :
                    getCommonSupertype(baseCandidates);
                return getWidenedType(unwidenedType);
            }
            function getInferredType(context, index) {
                var inference = context.inferences[index];
                var inferredType = inference.inferredType;
                if (!inferredType) {
                    var signature = context.signature;
                    if (signature) {
                        if (inference.contraCandidates && (!inference.candidates || inference.candidates.length === 1 && inference.candidates[0].flags & 32768 /* Never */)) {
                            // If we have contravariant inferences, but no covariant inferences or a single
                            // covariant inference of 'never', we find the best common subtype and treat that
                            // as a single covariant candidate.
                            inference.candidates = [getContravariantInference(inference)];
                            inference.contraCandidates = undefined;
                        }
                        if (inference.candidates) {
                            inferredType = getCovariantInference(inference, signature);
                        }
                        else if (context.flags & 1 /* NoDefault */) {
                            // We use silentNeverType as the wildcard that signals no inferences.
                            inferredType = silentNeverType;
                        }
                        else {
                            // Infer either the default or the empty object type when no inferences were
                            // made. It is important to remember that in this case, inference still
                            // succeeds, meaning there is no error for not having inference candidates. An
                            // inference error only occurs when there are *conflicting* candidates, i.e.
                            // candidates with no common supertype.
                            var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
                            if (defaultType) {
                                // Instantiate the default type. Any forward reference to a type
                                // parameter should be instantiated to the empty object type.
                                inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
                            }
                            else {
                                inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
                            }
                        }
                    }
                    else {
                        inferredType = getTypeFromInference(inference);
                    }
                    inference.inferredType = inferredType;
                    var constraint = getConstraintOfTypeParameter(inference.typeParameter);
                    if (constraint) {
                        var instantiatedConstraint = instantiateType(constraint, context);
                        if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
                            inference.inferredType = inferredType = instantiatedConstraint;
                        }
                    }
                }
                return inferredType;
            }
            function getDefaultTypeArgumentType(isInJavaScriptFile) {
                return isInJavaScriptFile ? anyType : emptyObjectType;
            }
            function getInferredTypes(context) {
                var result = [];
                for (var i = 0; i < context.inferences.length; i++) {
                    result.push(getInferredType(context, i));
                }
                return result;
            }
            // EXPRESSION TYPE CHECKING
            function getCannotFindNameDiagnosticForName(name) {
                switch (name) {
                    case "document":
                    case "console":
                        return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
                    case "$":
                        return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
                    case "describe":
                    case "suite":
                    case "it":
                    case "test":
                        return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
                    case "process":
                    case "require":
                    case "Buffer":
                    case "module":
                        return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
                    case "Map":
                    case "Set":
                    case "Promise":
                    case "Symbol":
                    case "WeakMap":
                    case "WeakSet":
                    case "Iterator":
                    case "AsyncIterator":
                        return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later;
                    default: return ts.Diagnostics.Cannot_find_name_0;
                }
            }
            function getResolvedSymbol(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedSymbol) {
                    links.resolvedSymbol = !ts.nodeIsMissing(node) &&
                        resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), 
                        /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
                }
                return links.resolvedSymbol;
            }
            function isInTypeQuery(node) {
                // TypeScript 1.0 spec (April 2014): 3.6.3
                // A type query consists of the keyword typeof followed by an expression.
                // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
                return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; });
            }
            // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
            // separated by dots). The key consists of the id of the symbol referenced by the
            // leftmost identifier followed by zero or more property names separated by dots.
            // The result is undefined if the reference isn't a dotted name. We prefix nodes
            // occurring in an apparent type position with '@' because the control flow type
            // of such nodes may be based on the apparent type instead of the declared type.
            function getFlowCacheKey(node) {
                if (node.kind === 71 /* Identifier */) {
                    var symbol = getResolvedSymbol(node);
                    return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
                }
                if (node.kind === 99 /* ThisKeyword */) {
                    return "0";
                }
                if (node.kind === 187 /* PropertyAccessExpression */) {
                    var key = getFlowCacheKey(node.expression);
                    return key && key + "." + ts.idText(node.name);
                }
                if (node.kind === 184 /* BindingElement */) {
                    var container = node.parent.parent;
                    var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer));
                    var text = getBindingElementNameText(node);
                    var result = key && text && (key + "." + text);
                    return result;
                }
                return undefined;
            }
            function getBindingElementNameText(element) {
                var parent = element.parent;
                if (parent.kind === 182 /* ObjectBindingPattern */) {
                    var name = element.propertyName || element.name;
                    switch (name.kind) {
                        case 71 /* Identifier */:
                            return ts.idText(name);
                        case 147 /* ComputedPropertyName */:
                            return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined;
                        case 9 /* StringLiteral */:
                        case 8 /* NumericLiteral */:
                            return name.text;
                        default:
                            // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined
                            ts.Debug.fail("Unexpected name kind for binding element name");
                    }
                }
                else {
                    return "" + parent.elements.indexOf(element);
                }
            }
            function isMatchingReference(source, target) {
                switch (source.kind) {
                    case 71 /* Identifier */:
                        return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
                            (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) &&
                                getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
                    case 99 /* ThisKeyword */:
                        return target.kind === 99 /* ThisKeyword */;
                    case 97 /* SuperKeyword */:
                        return target.kind === 97 /* SuperKeyword */;
                    case 187 /* PropertyAccessExpression */:
                    case 188 /* ElementAccessExpression */:
                        return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) &&
                            getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
                            isMatchingReference(source.expression, target.expression);
                    case 184 /* BindingElement */:
                        if (target.kind !== 187 /* PropertyAccessExpression */)
                            return false;
                        var t = target;
                        if (t.name.escapedText !== getBindingElementNameText(source))
                            return false;
                        if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) {
                            return true;
                        }
                        if (source.parent.parent.kind === 235 /* VariableDeclaration */) {
                            var maybeId = source.parent.parent.initializer;
                            return !!maybeId && isMatchingReference(maybeId, t.expression);
                        }
                }
                return false;
            }
            function getAccessedPropertyName(access) {
                return ts.isPropertyAccessExpression(access) ? access.name.escapedText :
                    ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
                        undefined;
            }
            function containsMatchingReference(source, target) {
                while (source.kind === 187 /* PropertyAccessExpression */) {
                    source = source.expression;
                    if (isMatchingReference(source, target)) {
                        return true;
                    }
                }
                return false;
            }
            // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared
            // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property
            // a possible discriminant if its type differs in the constituents of containing union type, and if every
            // choice is a unit type or a union of unit types.
            function containsMatchingReferenceDiscriminant(source, target) {
                return target.kind === 187 /* PropertyAccessExpression */ &&
                    containsMatchingReference(source, target.expression) &&
                    isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText);
            }
            function getDeclaredTypeOfReference(expr) {
                if (expr.kind === 71 /* Identifier */) {
                    return getTypeOfSymbol(getResolvedSymbol(expr));
                }
                if (expr.kind === 187 /* PropertyAccessExpression */) {
                    var type = getDeclaredTypeOfReference(expr.expression);
                    return type && getTypeOfPropertyOfType(type, expr.name.escapedText);
                }
                return undefined;
            }
            function isDiscriminantProperty(type, name) {
                if (type && type.flags & 262144 /* Union */) {
                    var prop = getUnionOrIntersectionProperty(type, name);
                    if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
                        if (prop.isDiscriminantProperty === undefined) {
                            prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop));
                        }
                        return prop.isDiscriminantProperty;
                    }
                }
                return false;
            }
            function findDiscriminantProperties(sourceProperties, target) {
                var result;
                for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
                    var sourceProperty = sourceProperties_2[_i];
                    if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
                        if (result) {
                            result.push(sourceProperty);
                            continue;
                        }
                        result = [sourceProperty];
                    }
                }
                return result;
            }
            function isOrContainsMatchingReference(source, target) {
                return isMatchingReference(source, target) || containsMatchingReference(source, target);
            }
            function hasMatchingArgument(callExpression, reference) {
                if (callExpression.arguments) {
                    for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
                        var argument = _a[_i];
                        if (isOrContainsMatchingReference(reference, argument)) {
                            return true;
                        }
                    }
                }
                if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ &&
                    isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
                    return true;
                }
                return false;
            }
            function getFlowNodeId(flow) {
                if (!flow.id) {
                    flow.id = nextFlowId;
                    nextFlowId++;
                }
                return flow.id;
            }
            function typeMaybeAssignableTo(source, target) {
                if (!(source.flags & 262144 /* Union */)) {
                    return isTypeAssignableTo(source, target);
                }
                for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
                    var t = _a[_i];
                    if (isTypeAssignableTo(t, target)) {
                        return true;
                    }
                }
                return false;
            }
            // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
            // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
            // we remove type string.
            function getAssignmentReducedType(declaredType, assignedType) {
                if (declaredType !== assignedType) {
                    if (assignedType.flags & 32768 /* Never */) {
                        return assignedType;
                    }
                    var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
                    if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) {
                        reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
                    }
                    // Our crude heuristic produces an invalid result in some cases: see GH#26130.
                    // For now, when that happens, we give up and don't narrow at all.  (This also
                    // means we'll never narrow for erroneous assignments where the assigned type
                    // is not assignable to the declared type.)
                    if (isTypeAssignableTo(assignedType, reducedType)) {
                        return reducedType;
                    }
                }
                return declaredType;
            }
            function getTypeFactsOfTypes(types) {
                var result = 0 /* None */;
                for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
                    var t = types_11[_i];
                    result |= getTypeFacts(t);
                }
                return result;
            }
            function isFunctionObjectType(type) {
                // We do a quick check for a "bind" property before performing the more expensive subtype
                // check. This gives us a quicker out in the common case where an object type is not a function.
                var resolved = resolveStructuredTypeMembers(type);
                return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
                    resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
            }
            function getTypeFacts(type) {
                var flags = type.flags;
                if (flags & 4 /* String */) {
                    return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */;
                }
                if (flags & 64 /* StringLiteral */) {
                    var isEmpty = type.value === "";
                    return strictNullChecks ?
                        isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ :
                        isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */;
                }
                if (flags & (8 /* Number */ | 32 /* Enum */)) {
                    return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */;
                }
                if (flags & 128 /* NumberLiteral */) {
                    var isZero = type.value === 0;
                    return strictNullChecks ?
                        isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ :
                        isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */;
                }
                if (flags & 16 /* Boolean */) {
                    return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */;
                }
                if (flags & 272 /* BooleanLike */) {
                    return strictNullChecks ?
                        (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ :
                        (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */;
                }
                if (flags & 131072 /* Object */) {
                    return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
                        strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ :
                        isFunctionObjectType(type) ?
                            strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ :
                            strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
                }
                if (flags & (4096 /* Void */ | 8192 /* Undefined */)) {
                    return 2457472 /* UndefinedFacts */;
                }
                if (flags & 16384 /* Null */) {
                    return 2340752 /* NullFacts */;
                }
                if (flags & 3072 /* ESSymbolLike */) {
                    return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */;
                }
                if (flags & 16777216 /* NonPrimitive */) {
                    return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */;
                }
                if (flags & 15794176 /* Instantiable */) {
                    return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
                }
                if (flags & 786432 /* UnionOrIntersection */) {
                    return getTypeFactsOfTypes(type.types);
                }
                return 4194303 /* All */;
            }
            function getTypeWithFacts(type, include) {
                return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
            }
            function getTypeWithDefault(type, defaultExpression) {
                if (defaultExpression) {
                    var defaultType = getTypeOfExpression(defaultExpression);
                    return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]);
                }
                return type;
            }
            function getTypeOfDestructuredProperty(type, name) {
                var text = ts.getTextOfPropertyName(name);
                return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
                    isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
                    getIndexTypeOfType(type, 0 /* String */) ||
                    errorType;
            }
            function getTypeOfDestructuredArrayElement(type, index) {
                return isTupleLikeType(type) && getTupleElementType(type, index) ||
                    checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) ||
                    errorType;
            }
            function getTypeOfDestructuredSpreadExpression(type) {
                return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType);
            }
            function getAssignedTypeOfBinaryExpression(node) {
                var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
                    node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
                return isDestructuringDefaultAssignment ?
                    getTypeWithDefault(getAssignedType(node), node.right) :
                    getTypeOfExpression(node.right);
            }
            function isDestructuringAssignmentTarget(parent) {
                return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent ||
                    parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent;
            }
            function getAssignedTypeOfArrayLiteralElement(node, element) {
                return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
            }
            function getAssignedTypeOfSpreadExpression(node) {
                return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
            }
            function getAssignedTypeOfPropertyAssignment(node) {
                return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
            }
            function getAssignedTypeOfShorthandPropertyAssignment(node) {
                return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
            }
            function getAssignedType(node) {
                var parent = node.parent;
                switch (parent.kind) {
                    case 224 /* ForInStatement */:
                        return stringType;
                    case 225 /* ForOfStatement */:
                        return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType;
                    case 202 /* BinaryExpression */:
                        return getAssignedTypeOfBinaryExpression(parent);
                    case 196 /* DeleteExpression */:
                        return undefinedType;
                    case 185 /* ArrayLiteralExpression */:
                        return getAssignedTypeOfArrayLiteralElement(parent, node);
                    case 206 /* SpreadElement */:
                        return getAssignedTypeOfSpreadExpression(parent);
                    case 273 /* PropertyAssignment */:
                        return getAssignedTypeOfPropertyAssignment(parent);
                    case 274 /* ShorthandPropertyAssignment */:
                        return getAssignedTypeOfShorthandPropertyAssignment(parent);
                }
                return errorType;
            }
            function getInitialTypeOfBindingElement(node) {
                var pattern = node.parent;
                var parentType = getInitialType(pattern.parent);
                var type = pattern.kind === 182 /* ObjectBindingPattern */ ?
                    getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
                    !node.dotDotDotToken ?
                        getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
                        getTypeOfDestructuredSpreadExpression(parentType);
                return getTypeWithDefault(type, node.initializer);
            }
            function getTypeOfInitializer(node) {
                // Return the cached type if one is available. If the type of the variable was inferred
                // from its initializer, we'll already have cached the type. Otherwise we compute it now
                // without caching such that transient types are reflected.
                var links = getNodeLinks(node);
                return links.resolvedType || getTypeOfExpression(node);
            }
            function getInitialTypeOfVariableDeclaration(node) {
                if (node.initializer) {
                    return getTypeOfInitializer(node.initializer);
                }
                if (node.parent.parent.kind === 224 /* ForInStatement */) {
                    return stringType;
                }
                if (node.parent.parent.kind === 225 /* ForOfStatement */) {
                    return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType;
                }
                return errorType;
            }
            function getInitialType(node) {
                return node.kind === 235 /* VariableDeclaration */ ?
                    getInitialTypeOfVariableDeclaration(node) :
                    getInitialTypeOfBindingElement(node);
            }
            function getInitialOrAssignedType(node, reference) {
                return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ?
                    getInitialType(node) :
                    getAssignedType(node), reference);
            }
            function isEmptyArrayAssignment(node) {
                return node.kind === 235 /* VariableDeclaration */ && node.initializer &&
                    isEmptyArrayLiteral(node.initializer) ||
                    node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ &&
                        isEmptyArrayLiteral(node.parent.right);
            }
            function getReferenceCandidate(node) {
                switch (node.kind) {
                    case 193 /* ParenthesizedExpression */:
                        return getReferenceCandidate(node.expression);
                    case 202 /* BinaryExpression */:
                        switch (node.operatorToken.kind) {
                            case 58 /* EqualsToken */:
                                return getReferenceCandidate(node.left);
                            case 26 /* CommaToken */:
                                return getReferenceCandidate(node.right);
                        }
                }
                return node;
            }
            function getReferenceRoot(node) {
                var parent = node.parent;
                return parent.kind === 193 /* ParenthesizedExpression */ ||
                    parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node ||
                    parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ?
                    getReferenceRoot(parent) : node;
            }
            function getTypeOfSwitchClause(clause) {
                if (clause.kind === 269 /* CaseClause */) {
                    return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
                }
                return neverType;
            }
            function getSwitchClauseTypes(switchStatement) {
                var links = getNodeLinks(switchStatement);
                if (!links.switchTypes) {
                    links.switchTypes = [];
                    for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
                        var clause = _a[_i];
                        links.switchTypes.push(getTypeOfSwitchClause(clause));
                    }
                }
                return links.switchTypes;
            }
            // Get the types from all cases in a switch on `typeof`. An
            // `undefined` element denotes an explicit `default` clause.
            function getSwitchClauseTypeOfWitnesses(switchStatement) {
                var witnesses = [];
                for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
                    var clause = _a[_i];
                    if (clause.kind === 269 /* CaseClause */) {
                        if (clause.expression.kind === 9 /* StringLiteral */) {
                            witnesses.push(clause.expression.text);
                            continue;
                        }
                        return ts.emptyArray;
                    }
                    witnesses.push(/*explicitDefaultStatement*/ undefined);
                }
                return witnesses;
            }
            function eachTypeContainedIn(source, types) {
                return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
            }
            function isTypeSubsetOf(source, target) {
                return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target);
            }
            function isTypeSubsetOfUnion(source, target) {
                if (source.flags & 262144 /* Union */) {
                    for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
                        var t = _a[_i];
                        if (!containsType(target.types, t)) {
                            return false;
                        }
                    }
                    return true;
                }
                if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
                    return true;
                }
                return containsType(target.types, source);
            }
            function forEachType(type, f) {
                return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type);
            }
            function filterType(type, f) {
                if (type.flags & 262144 /* Union */) {
                    var types = type.types;
                    var filtered = ts.filter(types, f);
                    return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */);
                }
                return f(type) ? type : neverType;
            }
            function mapType(type, mapper, noReductions) {
                if (type.flags & 32768 /* Never */) {
                    return type;
                }
                if (!(type.flags & 262144 /* Union */)) {
                    return mapper(type);
                }
                var types = type.types;
                var mappedType;
                var mappedTypes;
                for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
                    var current = types_12[_i];
                    var t = mapper(current);
                    if (t) {
                        if (!mappedType) {
                            mappedType = t;
                        }
                        else if (!mappedTypes) {
                            mappedTypes = [mappedType, t];
                        }
                        else {
                            mappedTypes.push(t);
                        }
                    }
                }
                return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType;
            }
            function extractTypesOfKind(type, kind) {
                return filterType(type, function (t) { return (t.flags & kind) !== 0; });
            }
            // Return a new type in which occurrences of the string and number primitive types in
            // typeWithPrimitives have been replaced with occurrences of string literals and numeric
            // literals in typeWithLiterals, respectively.
            function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
                if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) ||
                    isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) {
                    return mapType(typeWithPrimitives, function (t) {
                        return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) :
                            t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) :
                                t;
                    });
                }
                return typeWithPrimitives;
            }
            function isIncomplete(flowType) {
                return flowType.flags === 0;
            }
            function getTypeFromFlowType(flowType) {
                return flowType.flags === 0 ? flowType.type : flowType;
            }
            function createFlowType(type, incomplete) {
                return incomplete ? { flags: 0, type: type } : type;
            }
            // An evolving array type tracks the element types that have so far been seen in an
            // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
            // array types are ultimately converted into manifest array types (using getFinalArrayType)
            // and never escape the getFlowTypeOfReference function.
            function createEvolvingArrayType(elementType) {
                var result = createObjectType(256 /* EvolvingArray */);
                result.elementType = elementType;
                return result;
            }
            function getEvolvingArrayType(elementType) {
                return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
            }
            // When adding evolving array element types we do not perform subtype reduction. Instead,
            // we defer subtype reduction until the evolving array type is finalized into a manifest
            // array type.
            function addEvolvingArrayElementType(evolvingArrayType, node) {
                var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
                return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
            }
            function createFinalArrayType(elementType) {
                return elementType.flags & 32768 /* Never */ ?
                    autoArrayType :
                    createArrayType(elementType.flags & 262144 /* Union */ ?
                        getUnionType(elementType.types, 2 /* Subtype */) :
                        elementType);
            }
            // We perform subtype reduction upon obtaining the final array type from an evolving array type.
            function getFinalArrayType(evolvingArrayType) {
                return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
            }
            function finalizeEvolvingArrayType(type) {
                return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
            }
            function getElementTypeOfEvolvingArrayType(type) {
                return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
            }
            function isEvolvingArrayTypeList(types) {
                var hasEvolvingArrayType = false;
                for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
                    var t = types_13[_i];
                    if (!(t.flags & 32768 /* Never */)) {
                        if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
                            return false;
                        }
                        hasEvolvingArrayType = true;
                    }
                }
                return hasEvolvingArrayType;
            }
            // At flow control branch or loop junctions, if the type along every antecedent code path
            // is an evolving array type, we construct a combined evolving array type. Otherwise we
            // finalize all evolving array types.
            function getUnionOrEvolvingArrayType(types, subtypeReduction) {
                return isEvolvingArrayTypeList(types) ?
                    getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
                    getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
            }
            // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
            // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
            function isEvolvingArrayOperationTarget(node) {
                var root = getReferenceRoot(node);
                var parent = root.parent;
                var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" ||
                    parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name));
                var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ &&
                    parent.expression === root &&
                    parent.parent.kind === 202 /* BinaryExpression */ &&
                    parent.parent.operatorToken.kind === 58 /* EqualsToken */ &&
                    parent.parent.left === parent &&
                    !ts.isAssignmentTarget(parent.parent) &&
                    isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */);
                return isLengthPushOrUnshift || isElementAssignment;
            }
            function maybeTypePredicateCall(node) {
                var links = getNodeLinks(node);
                if (links.maybeTypePredicate === undefined) {
                    links.maybeTypePredicate = getMaybeTypePredicate(node);
                }
                return links.maybeTypePredicate;
            }
            function getMaybeTypePredicate(node) {
                if (node.expression.kind !== 97 /* SuperKeyword */) {
                    var funcType = checkNonNullExpression(node.expression);
                    if (funcType !== silentNeverType) {
                        var apparentType = getApparentType(funcType);
                        return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate);
                    }
                }
                return false;
            }
            function reportFlowControlError(node) {
                var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
                var sourceFile = ts.getSourceFileOfNode(node);
                var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
                diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
            }
            function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
                if (initialType === void 0) {
                    initialType = declaredType;
                }
                var key;
                var flowDepth = 0;
                if (flowAnalysisDisabled) {
                    return errorType;
                }
                if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) {
                    return declaredType;
                }
                var sharedFlowStart = sharedFlowCount;
                var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
                sharedFlowCount = sharedFlowStart;
                // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
                // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
                // on empty arrays are possible without implicit any errors and new element types can be inferred without
                // type mismatch errors.
                var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType);
                if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) {
                    return declaredType;
                }
                return resultType;
                function getTypeAtFlowNode(flow) {
                    if (flowDepth === 2000) {
                        // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
                        // and disable further control flow analysis in the containing function or module body.
                        flowAnalysisDisabled = true;
                        reportFlowControlError(reference);
                        return errorType;
                    }
                    flowDepth++;
                    while (true) {
                        var flags = flow.flags;
                        if (flags & 1024 /* Shared */) {
                            // We cache results of flow type resolution for shared nodes that were previously visited in
                            // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
                            // antecedent of more than one node.
                            for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
                                if (sharedFlowNodes[i] === flow) {
                                    flowDepth--;
                                    return sharedFlowTypes[i];
                                }
                            }
                        }
                        var type = void 0;
                        if (flags & 4096 /* AfterFinally */) {
                            // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement
                            flow.locked = true;
                            type = getTypeAtFlowNode(flow.antecedent);
                            flow.locked = false;
                        }
                        else if (flags & 2048 /* PreFinally */) {
                            // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel
                            // so here just redirect to antecedent
                            flow = flow.antecedent;
                            continue;
                        }
                        else if (flags & 16 /* Assignment */) {
                            type = getTypeAtFlowAssignment(flow);
                            if (!type) {
                                flow = flow.antecedent;
                                continue;
                            }
                        }
                        else if (flags & 96 /* Condition */) {
                            type = getTypeAtFlowCondition(flow);
                        }
                        else if (flags & 128 /* SwitchClause */) {
                            type = getTypeAtSwitchClause(flow);
                        }
                        else if (flags & 12 /* Label */) {
                            if (flow.antecedents.length === 1) {
                                flow = flow.antecedents[0];
                                continue;
                            }
                            type = flags & 4 /* BranchLabel */ ?
                                getTypeAtFlowBranchLabel(flow) :
                                getTypeAtFlowLoopLabel(flow);
                        }
                        else if (flags & 256 /* ArrayMutation */) {
                            type = getTypeAtFlowArrayMutation(flow);
                            if (!type) {
                                flow = flow.antecedent;
                                continue;
                            }
                        }
                        else if (flags & 2 /* Start */) {
                            // Check if we should continue with the control flow of the containing function.
                            var container = flow.container;
                            if (container && container !== flowContainer &&
                                reference.kind !== 187 /* PropertyAccessExpression */ &&
                                reference.kind !== 188 /* ElementAccessExpression */ &&
                                reference.kind !== 99 /* ThisKeyword */) {
                                flow = container.flowNode;
                                continue;
                            }
                            // At the top of the flow we have the initial type.
                            type = initialType;
                        }
                        else {
                            // Unreachable code errors are reported in the binding phase. Here we
                            // simply return the non-auto declared type to reduce follow-on errors.
                            type = convertAutoToAny(declaredType);
                        }
                        if (flags & 1024 /* Shared */) {
                            // Record visited node and the associated type in the cache.
                            sharedFlowNodes[sharedFlowCount] = flow;
                            sharedFlowTypes[sharedFlowCount] = type;
                            sharedFlowCount++;
                        }
                        flowDepth--;
                        return type;
                    }
                }
                function getTypeAtFlowAssignment(flow) {
                    var node = flow.node;
                    // Assignments only narrow the computed type if the declared type is a union type. Thus, we
                    // only need to evaluate the assigned type if the declared type is a union type.
                    if (isMatchingReference(reference, node)) {
                        if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
                            var flowType = getTypeAtFlowNode(flow.antecedent);
                            return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
                        }
                        if (declaredType === autoType || declaredType === autoArrayType) {
                            if (isEmptyArrayAssignment(node)) {
                                return getEvolvingArrayType(neverType);
                            }
                            var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference));
                            return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
                        }
                        if (declaredType.flags & 262144 /* Union */) {
                            return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference));
                        }
                        return declaredType;
                    }
                    // We didn't have a direct match. However, if the reference is a dotted name, this
                    // may be an assignment to a left hand part of the reference. For example, for a
                    // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
                    // return the declared type.
                    if (containsMatchingReference(reference, node)) {
                        // A matching dotted name might also be an expando property on a function *expression*,
                        // in which case we continue control flow analysis back to the function's declaration
                        if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
                            var init = ts.getDeclaredExpandoInitializer(node);
                            if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) {
                                return getTypeAtFlowNode(flow.antecedent);
                            }
                        }
                        return declaredType;
                    }
                    // Assignment doesn't affect reference
                    return undefined;
                }
                function getTypeAtFlowArrayMutation(flow) {
                    if (declaredType === autoType || declaredType === autoArrayType) {
                        var node = flow.node;
                        var expr = node.kind === 189 /* CallExpression */ ?
                            node.expression.expression :
                            node.left.expression;
                        if (isMatchingReference(reference, getReferenceCandidate(expr))) {
                            var flowType = getTypeAtFlowNode(flow.antecedent);
                            var type = getTypeFromFlowType(flowType);
                            if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
                                var evolvedType_1 = type;
                                if (node.kind === 189 /* CallExpression */) {
                                    for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
                                        var arg = _a[_i];
                                        evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
                                    }
                                }
                                else {
                                    // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time)
                                    var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
                                    if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) {
                                        evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
                                    }
                                }
                                return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
                            }
                            return flowType;
                        }
                    }
                    return undefined;
                }
                function getTypeAtFlowCondition(flow) {
                    var flowType = getTypeAtFlowNode(flow.antecedent);
                    var type = getTypeFromFlowType(flowType);
                    if (type.flags & 32768 /* Never */) {
                        return flowType;
                    }
                    // If we have an antecedent type (meaning we're reachable in some way), we first
                    // attempt to narrow the antecedent type. If that produces the never type, and if
                    // the antecedent type is incomplete (i.e. a transient type in a loop), then we
                    // take the type guard as an indication that control *could* reach here once we
                    // have the complete type. We proceed by switching to the silent never type which
                    // doesn't report errors when operators are applied to it. Note that this is the
                    // *only* place a silent never type is ever generated.
                    var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
                    var nonEvolvingType = finalizeEvolvingArrayType(type);
                    var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue);
                    if (narrowedType === nonEvolvingType) {
                        return flowType;
                    }
                    var incomplete = isIncomplete(flowType);
                    var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType;
                    return createFlowType(resultType, incomplete);
                }
                function getTypeAtSwitchClause(flow) {
                    var flowType = getTypeAtFlowNode(flow.antecedent);
                    var type = getTypeFromFlowType(flowType);
                    var expr = flow.switchStatement.expression;
                    if (isMatchingReference(reference, expr)) {
                        type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
                    }
                    else if (isMatchingReferenceDiscriminant(expr, type)) {
                        type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
                    }
                    else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
                        type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
                    }
                    return createFlowType(type, isIncomplete(flowType));
                }
                function getTypeAtFlowBranchLabel(flow) {
                    var antecedentTypes = [];
                    var subtypeReduction = false;
                    var seenIncomplete = false;
                    for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
                        var antecedent = _a[_i];
                        if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) {
                            // if flow correspond to branch from pre-try to finally and this branch is locked - this means that
                            // we initially have started following the flow outside the finally block.
                            // in this case we should ignore this branch.
                            continue;
                        }
                        var flowType = getTypeAtFlowNode(antecedent);
                        var type = getTypeFromFlowType(flowType);
                        // If the type at a particular antecedent path is the declared type and the
                        // reference is known to always be assigned (i.e. when declared and initial types
                        // are the same), there is no reason to process more antecedents since the only
                        // possible outcome is subtypes that will be removed in the final union type anyway.
                        if (type === declaredType && declaredType === initialType) {
                            return type;
                        }
                        ts.pushIfUnique(antecedentTypes, type);
                        // If an antecedent type is not a subset of the declared type, we need to perform
                        // subtype reduction. This happens when a "foreign" type is injected into the control
                        // flow using the instanceof operator or a user defined type predicate.
                        if (!isTypeSubsetOf(type, declaredType)) {
                            subtypeReduction = true;
                        }
                        if (isIncomplete(flowType)) {
                            seenIncomplete = true;
                        }
                    }
                    return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
                }
                function getTypeAtFlowLoopLabel(flow) {
                    // If we have previously computed the control flow type for the reference at
                    // this flow loop junction, return the cached type.
                    var id = getFlowNodeId(flow);
                    var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
                    if (!key) {
                        key = getFlowCacheKey(reference);
                        // No cache key is generated when binding patterns are in unnarrowable situations
                        if (!key) {
                            return declaredType;
                        }
                    }
                    var cached = cache.get(key);
                    if (cached) {
                        return cached;
                    }
                    // If this flow loop junction and reference are already being processed, return
                    // the union of the types computed for each branch so far, marked as incomplete.
                    // It is possible to see an empty array in cases where loops are nested and the
                    // back edge of the outer loop reaches an inner loop that is already being analyzed.
                    // In such cases we restart the analysis of the inner loop, which will then see
                    // a non-empty in-process array for the outer loop and eventually terminate because
                    // the first antecedent of a loop junction is always the non-looping control flow
                    // path that leads to the top.
                    for (var i = flowLoopStart; i < flowLoopCount; i++) {
                        if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
                            return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
                        }
                    }
                    // Add the flow loop junction and reference to the in-process stack and analyze
                    // each antecedent code path.
                    var antecedentTypes = [];
                    var subtypeReduction = false;
                    var firstAntecedentType;
                    flowLoopNodes[flowLoopCount] = flow;
                    flowLoopKeys[flowLoopCount] = key;
                    flowLoopTypes[flowLoopCount] = antecedentTypes;
                    for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
                        var antecedent = _a[_i];
                        flowLoopCount++;
                        var flowType = getTypeAtFlowNode(antecedent);
                        flowLoopCount--;
                        if (!firstAntecedentType) {
                            firstAntecedentType = flowType;
                        }
                        var type = getTypeFromFlowType(flowType);
                        // If we see a value appear in the cache it is a sign that control flow analysis
                        // was restarted and completed by checkExpressionCached. We can simply pick up
                        // the resulting type and bail out.
                        var cached_1 = cache.get(key);
                        if (cached_1) {
                            return cached_1;
                        }
                        ts.pushIfUnique(antecedentTypes, type);
                        // If an antecedent type is not a subset of the declared type, we need to perform
                        // subtype reduction. This happens when a "foreign" type is injected into the control
                        // flow using the instanceof operator or a user defined type predicate.
                        if (!isTypeSubsetOf(type, declaredType)) {
                            subtypeReduction = true;
                        }
                        // If the type at a particular antecedent path is the declared type there is no
                        // reason to process more antecedents since the only possible outcome is subtypes
                        // that will be removed in the final union type anyway.
                        if (type === declaredType) {
                            break;
                        }
                    }
                    // The result is incomplete if the first antecedent (the non-looping control flow path)
                    // is incomplete.
                    var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
                    if (isIncomplete(firstAntecedentType)) {
                        return createFlowType(result, /*incomplete*/ true);
                    }
                    cache.set(key, result);
                    return result;
                }
                function isMatchingReferenceDiscriminant(expr, computedType) {
                    if (!(computedType.flags & 262144 /* Union */) ||
                        expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) {
                        return false;
                    }
                    var access = expr;
                    var name = getAccessedPropertyName(access);
                    if (!name) {
                        return false;
                    }
                    return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name);
                }
                function narrowTypeByDiscriminant(type, access, narrowType) {
                    var propName = getAccessedPropertyName(access);
                    if (!propName) {
                        return type;
                    }
                    var propType = getTypeOfPropertyOfType(type, propName);
                    var narrowedPropType = propType && narrowType(propType);
                    return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); });
                }
                function narrowTypeByTruthiness(type, expr, assumeTrue) {
                    if (isMatchingReference(reference, expr)) {
                        return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */);
                    }
                    if (isMatchingReferenceDiscriminant(expr, declaredType)) {
                        return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); });
                    }
                    if (containsMatchingReferenceDiscriminant(reference, expr)) {
                        return declaredType;
                    }
                    return type;
                }
                function isTypePresencePossible(type, propName, assumeTrue) {
                    if (getIndexInfoOfType(type, 0 /* String */)) {
                        return true;
                    }
                    var prop = getPropertyOfType(type, propName);
                    if (prop) {
                        return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
                    }
                    return !assumeTrue;
                }
                function narrowByInKeyword(type, literal, assumeTrue) {
                    if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) {
                        var propName_1 = ts.escapeLeadingUnderscores(literal.text);
                        return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
                    }
                    return type;
                }
                function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
                    switch (expr.operatorToken.kind) {
                        case 58 /* EqualsToken */:
                            return narrowTypeByTruthiness(type, expr.left, assumeTrue);
                        case 32 /* EqualsEqualsToken */:
                        case 33 /* ExclamationEqualsToken */:
                        case 34 /* EqualsEqualsEqualsToken */:
                        case 35 /* ExclamationEqualsEqualsToken */:
                            var operator_1 = expr.operatorToken.kind;
                            var left_1 = getReferenceCandidate(expr.left);
                            var right_1 = getReferenceCandidate(expr.right);
                            if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
                                return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
                            }
                            if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
                                return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
                            }
                            if (isMatchingReference(reference, left_1)) {
                                return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
                            }
                            if (isMatchingReference(reference, right_1)) {
                                return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
                            }
                            if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
                                return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
                            }
                            if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
                                return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
                            }
                            if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) {
                                return declaredType;
                            }
                            break;
                        case 93 /* InstanceOfKeyword */:
                            return narrowTypeByInstanceof(type, expr, assumeTrue);
                        case 92 /* InKeyword */:
                            var target = getReferenceCandidate(expr.right);
                            if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
                                return narrowByInKeyword(type, expr.left, assumeTrue);
                            }
                            break;
                        case 26 /* CommaToken */:
                            return narrowType(type, expr.right, assumeTrue);
                    }
                    return type;
                }
                function narrowTypeByEquality(type, operator, value, assumeTrue) {
                    if (type.flags & 1 /* Any */) {
                        return type;
                    }
                    if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) {
                        assumeTrue = !assumeTrue;
                    }
                    var valueType = getTypeOfExpression(value);
                    if (valueType.flags & 24576 /* Nullable */) {
                        if (!strictNullChecks) {
                            return type;
                        }
                        var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */;
                        var facts = doubleEquals ?
                            assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ :
                            valueType.flags & 16384 /* Null */ ?
                                assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ :
                                assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */;
                        return getTypeWithFacts(type, facts);
                    }
                    if (type.flags & 16909315 /* NotUnionOrUnit */) {
                        return type;
                    }
                    if (assumeTrue) {
                        var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); });
                        return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
                    }
                    if (isUnitType(valueType)) {
                        var regularType_1 = getRegularTypeOfLiteralType(valueType);
                        return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; });
                    }
                    return type;
                }
                function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
                    // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
                    var target = getReferenceCandidate(typeOfExpr.expression);
                    if (!isMatchingReference(reference, target)) {
                        // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
                        // narrowed type of 'y' to its declared type.
                        if (containsMatchingReference(reference, target)) {
                            return declaredType;
                        }
                        return type;
                    }
                    if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) {
                        assumeTrue = !assumeTrue;
                    }
                    if (type.flags & 1 /* Any */ && literal.text === "function") {
                        return type;
                    }
                    var facts = assumeTrue ?
                        typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ :
                        typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */;
                    return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
                    function narrowTypeForTypeof(type) {
                        if (type.flags & 2 /* Unknown */ && literal.text === "object") {
                            return getUnionType([nonPrimitiveType, nullType]);
                        }
                        // We narrow a non-union type to an exact primitive type if the non-union type
                        // is a supertype of that primitive type. For example, type 'any' can be narrowed
                        // to one of the primitive types.
                        var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
                        if (targetType) {
                            if (isTypeSubtypeOf(type, targetType)) {
                                return type;
                            }
                            if (isTypeSubtypeOf(targetType, type)) {
                                return targetType;
                            }
                            if (type.flags & 15794176 /* Instantiable */) {
                                var constraint = getBaseConstraintOfType(type) || anyType;
                                if (isTypeSubtypeOf(targetType, constraint)) {
                                    return getIntersectionType([type, targetType]);
                                }
                            }
                        }
                        return type;
                    }
                }
                function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
                    // We only narrow if all case expressions specify values with unit types
                    var switchTypes = getSwitchClauseTypes(switchStatement);
                    if (!switchTypes.length) {
                        return type;
                    }
                    var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
                    var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
                    var discriminantType = getUnionType(clauseTypes);
                    var caseType = discriminantType.flags & 32768 /* Never */ ? neverType :
                        replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
                    if (!hasDefaultClause) {
                        return caseType;
                    }
                    var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
                    return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
                }
                function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
                    var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement);
                    if (!switchWitnesses.length) {
                        return type;
                    }
                    //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
                    var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
                    var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
                    var clauseWitnesses;
                    var switchFacts;
                    if (defaultCaseLocation > -1) {
                        // We no longer need the undefined denoting an
                        // explicit default case. Remove the undefined and
                        // fix-up clauseStart and clauseEnd.  This means
                        // that we don't have to worry about undefined
                        // in the witness array.
                        var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
                        // The adjust clause start and end after removing the `default` statement.
                        var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
                        var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
                        clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
                        switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
                    }
                    else {
                        clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
                        switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
                    }
                    /*
                      The implied type is the raw type suggested by a
                      value being caught in this clause.
    
                      When the clause contains a default case we ignore
                      the implied type and try to narrow using any facts
                      we can learn: see `switchFacts`.
    
                      Example:
                      switch (typeof x) {
                          case 'number':
                          case 'string': break;
                          default: break;
                          case 'number':
                          case 'boolean': break
                      }
    
                      In the first clause (case `number` and `string`) the
                      implied type is number | string.
    
                      In the default clause we de not compute an implied type.
    
                      In the third clause (case `number` and `boolean`)
                      the naive implied type is number | boolean, however
                      we use the type facts to narrow the implied type to
                      boolean. We know that number cannot be selected
                      because it is caught in the first clause.
                    */
                    if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) {
                        var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts);
                        if (impliedType.flags & 262144 /* Union */) {
                            impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type);
                        }
                        if (!(impliedType.flags & 32768 /* Never */)) {
                            if (isTypeSubtypeOf(impliedType, type)) {
                                return impliedType;
                            }
                            if (type.flags & 15794176 /* Instantiable */) {
                                var constraint = getBaseConstraintOfType(type) || anyType;
                                if (isTypeSubtypeOf(impliedType, constraint)) {
                                    return getIntersectionType([type, impliedType]);
                                }
                            }
                        }
                    }
                    return hasDefaultClause ?
                        filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) :
                        getTypeWithFacts(type, switchFacts);
                }
                function narrowTypeByInstanceof(type, expr, assumeTrue) {
                    var left = getReferenceCandidate(expr.left);
                    if (!isMatchingReference(reference, left)) {
                        // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
                        // narrowed type of 'y' to its declared type.
                        if (containsMatchingReference(reference, left)) {
                            return declaredType;
                        }
                        return type;
                    }
                    // Check that right operand is a function type with a prototype property
                    var rightType = getTypeOfExpression(expr.right);
                    if (!isTypeSubtypeOf(rightType, globalFunctionType)) {
                        return type;
                    }
                    var targetType;
                    var prototypeProperty = getPropertyOfType(rightType, "prototype");
                    if (prototypeProperty) {
                        // Target type is type of the prototype property
                        var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
                        if (!isTypeAny(prototypePropertyType)) {
                            targetType = prototypePropertyType;
                        }
                    }
                    // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
                    if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
                        return type;
                    }
                    if (!targetType) {
                        // Target type is type of construct signature
                        var constructSignatures = void 0;
                        if (ts.getObjectFlags(rightType) & 2 /* Interface */) {
                            constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures;
                        }
                        else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) {
                            constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
                        }
                        if (constructSignatures && constructSignatures.length) {
                            targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); }));
                        }
                    }
                    if (targetType) {
                        return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
                    }
                    return type;
                }
                function getNarrowedType(type, candidate, assumeTrue, isRelated) {
                    if (!assumeTrue) {
                        return filterType(type, function (t) { return !isRelated(t, candidate); });
                    }
                    // If the current type is a union type, remove all constituents that couldn't be instances of
                    // the candidate type. If one or more constituents remain, return a union of those.
                    if (type.flags & 262144 /* Union */) {
                        var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
                        if (!(assignableType.flags & 32768 /* Never */)) {
                            return assignableType;
                        }
                    }
                    // If the candidate type is a subtype of the target type, narrow to the candidate type.
                    // Otherwise, if the target type is assignable to the candidate type, keep the target type.
                    // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
                    // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
                    // two types.
                    return isTypeSubtypeOf(candidate, type) ? candidate :
                        isTypeAssignableTo(type, candidate) ? type :
                            isTypeAssignableTo(candidate, type) ? candidate :
                                getIntersectionType([type, candidate]);
                }
                function narrowTypeByTypePredicate(type, callExpression, assumeTrue) {
                    if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) {
                        return type;
                    }
                    var signature = getResolvedSignature(callExpression);
                    var predicate = getTypePredicateOfSignature(signature);
                    if (!predicate) {
                        return type;
                    }
                    // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
                    if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) {
                        return type;
                    }
                    if (ts.isIdentifierTypePredicate(predicate)) {
                        var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
                        if (predicateArgument) {
                            if (isMatchingReference(reference, predicateArgument)) {
                                return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
                            }
                            if (containsMatchingReference(reference, predicateArgument)) {
                                return declaredType;
                            }
                        }
                    }
                    else {
                        var invokedExpression = ts.skipParentheses(callExpression.expression);
                        if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) {
                            var accessExpression = invokedExpression;
                            var possibleReference = ts.skipParentheses(accessExpression.expression);
                            if (isMatchingReference(reference, possibleReference)) {
                                return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
                            }
                            if (containsMatchingReference(reference, possibleReference)) {
                                return declaredType;
                            }
                        }
                    }
                    return type;
                }
                // Narrow the given type based on the given expression having the assumed boolean value. The returned type
                // will be a subtype or the same type as the argument.
                function narrowType(type, expr, assumeTrue) {
                    switch (expr.kind) {
                        case 71 /* Identifier */:
                        case 99 /* ThisKeyword */:
                        case 97 /* SuperKeyword */:
                        case 187 /* PropertyAccessExpression */:
                        case 188 /* ElementAccessExpression */:
                            return narrowTypeByTruthiness(type, expr, assumeTrue);
                        case 189 /* CallExpression */:
                            return narrowTypeByTypePredicate(type, expr, assumeTrue);
                        case 193 /* ParenthesizedExpression */:
                            return narrowType(type, expr.expression, assumeTrue);
                        case 202 /* BinaryExpression */:
                            return narrowTypeByBinaryExpression(type, expr, assumeTrue);
                        case 200 /* PrefixUnaryExpression */:
                            if (expr.operator === 51 /* ExclamationToken */) {
                                return narrowType(type, expr.operand, !assumeTrue);
                            }
                            break;
                    }
                    return type;
                }
            }
            function getTypeOfSymbolAtLocation(symbol, location) {
                symbol = symbol.exportSymbol || symbol;
                // If we have an identifier or a property access at the given location, if the location is
                // an dotted name expression, and if the location is not an assignment target, obtain the type
                // of the expression (which will reflect control flow analysis). If the expression indeed
                // resolved to the given symbol, return the narrowed type.
                if (location.kind === 71 /* Identifier */) {
                    if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
                        location = location.parent;
                    }
                    if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
                        var type = getTypeOfExpression(location);
                        if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
                            return type;
                        }
                    }
                }
                // The location isn't a reference to the given symbol, meaning we're being asked
                // a hypothetical question of what type the symbol would have if there was a reference
                // to it at the given location. Since we have no control flow information for the
                // hypothetical reference (control flow information is created and attached by the
                // binder), we simply return the declared type of the symbol.
                return getTypeOfSymbol(symbol);
            }
            function getControlFlowContainer(node) {
                return ts.findAncestor(node.parent, function (node) {
                    return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
                        node.kind === 243 /* ModuleBlock */ ||
                        node.kind === 277 /* SourceFile */ ||
                        node.kind === 152 /* PropertyDeclaration */;
                });
            }
            // Check if a parameter is assigned anywhere within its declaring function.
            function isParameterAssigned(symbol) {
                var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
                var links = getNodeLinks(func);
                if (!(links.flags & 4194304 /* AssignmentsMarked */)) {
                    links.flags |= 4194304 /* AssignmentsMarked */;
                    if (!hasParentWithAssignmentsMarked(func)) {
                        markParameterAssignments(func);
                    }
                }
                return symbol.isAssigned || false;
            }
            function hasParentWithAssignmentsMarked(node) {
                return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); });
            }
            function markParameterAssignments(node) {
                if (node.kind === 71 /* Identifier */) {
                    if (ts.isAssignmentTarget(node)) {
                        var symbol = getResolvedSymbol(node);
                        if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) {
                            symbol.isAssigned = true;
                        }
                    }
                }
                else {
                    ts.forEachChild(node, markParameterAssignments);
                }
            }
            function isConstVariable(symbol) {
                return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
            }
            /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
            function removeOptionalityFromDeclaredType(declaredType, declaration) {
                var annotationIncludesUndefined = strictNullChecks &&
                    declaration.kind === 149 /* Parameter */ &&
                    declaration.initializer &&
                    getFalsyFlags(declaredType) & 8192 /* Undefined */ &&
                    !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */);
                return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType;
            }
            function isConstraintPosition(node) {
                var parent = node.parent;
                return parent.kind === 187 /* PropertyAccessExpression */ ||
                    parent.kind === 189 /* CallExpression */ && parent.expression === node ||
                    parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node ||
                    parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer;
            }
            function typeHasNullableConstraint(type) {
                return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */);
            }
            function getConstraintForLocation(type, node) {
                // When a node is the left hand expression of a property access, element access, or call expression,
                // and the type of the node includes type variables with constraints that are nullable, we fetch the
                // apparent type of the node *before* performing control flow analysis such that narrowings apply to
                // the constraint type.
                if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
                    return mapType(getWidenedType(type), getBaseConstraintOrType);
                }
                return type;
            }
            function markAliasReferenced(symbol, location) {
                if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
                    markAliasSymbolAsReferenced(symbol);
                }
            }
            function checkIdentifier(node) {
                var symbol = getResolvedSymbol(node);
                if (symbol === unknownSymbol) {
                    return errorType;
                }
                // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
                // Although in down-level emit of arrow function, we emit it using function expression which means that
                // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
                // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
                // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
                // can explicitly bound arguments objects
                if (symbol === argumentsSymbol) {
                    var container = ts.getContainingFunction(node);
                    if (languageVersion < 2 /* ES2015 */) {
                        if (container.kind === 195 /* ArrowFunction */) {
                            error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
                        }
                        else if (ts.hasModifier(container, 256 /* Async */)) {
                            error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method);
                        }
                    }
                    getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
                    return getTypeOfSymbol(symbol);
                }
                // We should only mark aliases as referenced if there isn't a local value declaration
                // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
                if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
                    markAliasReferenced(symbol, node);
                }
                var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
                var declaration = localOrExportSymbol.valueDeclaration;
                if (localOrExportSymbol.flags & 32 /* Class */) {
                    // Due to the emit for class decorators, any reference to the class from inside of the class body
                    // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
                    // behavior of class names in ES6.
                    if (declaration.kind === 238 /* ClassDeclaration */
                        && ts.nodeIsDecorated(declaration)) {
                        var container = ts.getContainingClass(node);
                        while (container !== undefined) {
                            if (container === declaration && container.name !== node) {
                                getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */;
                                getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */;
                                break;
                            }
                            container = ts.getContainingClass(container);
                        }
                    }
                    else if (declaration.kind === 207 /* ClassExpression */) {
                        // When we emit a class expression with static members that contain a reference
                        // to the constructor in the initializer, we will need to substitute that
                        // binding with an alias as the class name is not in scope.
                        var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
                        while (container.kind !== 277 /* SourceFile */) {
                            if (container.parent === declaration) {
                                if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
                                    getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */;
                                    getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */;
                                }
                                break;
                            }
                            container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
                        }
                    }
                }
                checkNestedBlockScopedBinding(node, symbol);
                var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
                var assignmentKind = ts.getAssignmentTargetKind(node);
                if (assignmentKind) {
                    if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
                        !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
                        error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
                        return errorType;
                    }
                    if (isReadonlySymbol(localOrExportSymbol)) {
                        error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol));
                        return errorType;
                    }
                }
                var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
                // We only narrow variables and parameters occurring in a non-assignment position. For all other
                // entities we simply return the declared type.
                if (localOrExportSymbol.flags & 3 /* Variable */) {
                    if (assignmentKind === 1 /* Definite */) {
                        return type;
                    }
                }
                else if (isAlias) {
                    declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
                }
                else {
                    return type;
                }
                if (!declaration) {
                    return type;
                }
                // The declaration container is the innermost function that encloses the declaration of the variable
                // or parameter. The flow container is the innermost function starting with which we analyze the control
                // flow graph to determine the control flow based type.
                var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */;
                var declarationContainer = getControlFlowContainer(declaration);
                var flowContainer = getControlFlowContainer(node);
                var isOuterVariable = flowContainer !== declarationContainer;
                var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
                var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
                // When the control flow originates in a function expression or arrow function and we are referencing
                // a const variable or parameter from an outer function, we extend the origin of the control flow
                // analysis to include the immediately enclosing function.
                while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ ||
                    flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
                    (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
                    flowContainer = getControlFlowContainer(flowContainer);
                }
                // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
                // the entire control flow graph from the variable's declaration (i.e. when the flow container and
                // declaration container are the same).
                var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports ||
                    type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 ||
                        isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) ||
                    node.parent.kind === 211 /* NonNullExpression */ ||
                    declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken ||
                    declaration.flags & 4194304 /* Ambient */;
                var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
                    type === autoType || type === autoArrayType ? undefinedType :
                        getOptionalType(type);
                var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
                // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
                // from declaration to use, and when the variable's declared type doesn't include undefined but the
                // control flow based type does include undefined.
                if (type === autoType || type === autoArrayType) {
                    if (flowType === autoType || flowType === autoArrayType) {
                        if (noImplicitAny) {
                            error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
                            error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
                        }
                        return convertAutoToAny(flowType);
                    }
                }
                else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) {
                    error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
                    // Return the declared type to reduce follow-on errors
                    return type;
                }
                return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
            }
            function isInsideFunction(node, threshold) {
                return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
            }
            function checkNestedBlockScopedBinding(node, symbol) {
                if (languageVersion >= 2 /* ES2015 */ ||
                    (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
                    symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) {
                    return;
                }
                // 1. walk from the use site up to the declaration and check
                // if there is anything function like between declaration and use-site (is binding/class is captured in function).
                // 2. walk from the declaration up to the boundary of lexical environment and check
                // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
                var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
                var usedInFunction = isInsideFunction(node.parent, container);
                var current = container;
                var containedInIterationStatement = false;
                while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
                    if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
                        containedInIterationStatement = true;
                        break;
                    }
                    current = current.parent;
                }
                if (containedInIterationStatement) {
                    if (usedInFunction) {
                        // mark iteration statement as containing block-scoped binding captured in some function
                        getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
                    }
                    // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
                    // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
                    if (container.kind === 223 /* ForStatement */ &&
                        ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container &&
                        isAssignedInBodyOfForStatement(node, container)) {
                        getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */;
                    }
                    // set 'declared inside loop' bit on the block-scoped binding
                    getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */;
                }
                if (usedInFunction) {
                    getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */;
                }
            }
            function isAssignedInBodyOfForStatement(node, container) {
                // skip parenthesized nodes
                var current = node;
                while (current.parent.kind === 193 /* ParenthesizedExpression */) {
                    current = current.parent;
                }
                // check if node is used as LHS in some assignment expression
                var isAssigned = false;
                if (ts.isAssignmentTarget(current)) {
                    isAssigned = true;
                }
                else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) {
                    var expr = current.parent;
                    isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */;
                }
                if (!isAssigned) {
                    return false;
                }
                // at this point we know that node is the target of assignment
                // now check that modification happens inside the statement part of the ForStatement
                return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
            }
            function captureLexicalThis(node, container) {
                getNodeLinks(node).flags |= 2 /* LexicalThis */;
                if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) {
                    var classNode = container.parent;
                    getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
                }
                else {
                    getNodeLinks(container).flags |= 4 /* CaptureThis */;
                }
            }
            function findFirstSuperCall(n) {
                if (ts.isSuperCall(n)) {
                    return n;
                }
                else if (ts.isFunctionLike(n)) {
                    return undefined;
                }
                return ts.forEachChild(n, findFirstSuperCall);
            }
            /**
             * Return a cached result if super-statement is already found.
             * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
             *
             * @param constructor constructor-function to look for super statement
             */
            function getSuperCallInConstructor(constructor) {
                var links = getNodeLinks(constructor);
                // Only trying to find super-call if we haven't yet tried to find one.  Once we try, we will record the result
                if (links.hasSuperCall === undefined) {
                    links.superCall = findFirstSuperCall(constructor.body);
                    links.hasSuperCall = links.superCall ? true : false;
                }
                return links.superCall;
            }
            /**
             * Check if the given class-declaration extends null then return true.
             * Otherwise, return false
             * @param classDecl a class declaration to check if it extends null
             */
            function classDeclarationExtendsNull(classDecl) {
                var classSymbol = getSymbolOfNode(classDecl);
                var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
                var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
                return baseConstructorType === nullWideningType;
            }
            function checkThisBeforeSuper(node, container, diagnosticMessage) {
                var containingClassDecl = container.parent;
                var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl);
                // If a containing class does not have extends clause or the class extends null
                // skip checking whether super statement is called before "this" accessing.
                if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
                    var superCall = getSuperCallInConstructor(container);
                    // We should give an error in the following cases:
                    //      - No super-call
                    //      - "this" is accessing before super-call.
                    //          i.e super(this)
                    //              this.x; super();
                    // We want to make sure that super-call is done before accessing "this" so that
                    // "this" is not accessed as a parameter of the super-call.
                    if (!superCall || superCall.end > node.pos) {
                        // In ES6, super inside constructor of class-declaration has to precede "this" accessing
                        error(node, diagnosticMessage);
                    }
                }
            }
            function checkThisExpression(node) {
                // Stop at the first arrow function so that we can
                // tell whether 'this' needs to be captured.
                var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
                var capturedByArrowFunction = false;
                if (container.kind === 155 /* Constructor */) {
                    checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
                }
                // Now skip arrow functions to get the "real" owner of 'this'.
                if (container.kind === 195 /* ArrowFunction */) {
                    container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
                    capturedByArrowFunction = true;
                }
                switch (container.kind) {
                    case 242 /* ModuleDeclaration */:
                        error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
                        // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
                        break;
                    case 241 /* EnumDeclaration */:
                        error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
                        // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
                        break;
                    case 155 /* Constructor */:
                        if (isInConstructorArgumentInitializer(node, container)) {
                            error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
                            // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
                        }
                        break;
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                        if (ts.hasModifier(container, 32 /* Static */)) {
                            error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
                            // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
                        }
                        break;
                    case 147 /* ComputedPropertyName */:
                        error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
                        break;
                }
                // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
                if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
                    captureLexicalThis(node, container);
                }
                var type = tryGetThisTypeAt(node, container);
                if (!type && noImplicitThis) {
                    // With noImplicitThis, functions may not reference 'this' if it has type 'any'
                    error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ?
                        ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any :
                        ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
                }
                return type || anyType;
            }
            function tryGetThisTypeAt(node, container) {
                if (container === void 0) {
                    container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
                }
                var isInJS = ts.isInJSFile(node);
                if (ts.isFunctionLike(container) &&
                    (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
                    // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
                    // If this is a function in a JS file, it might be a class method.
                    var className = getClassNameFromPrototypeMethod(container);
                    if (isInJS && className) {
                        var classSymbol = checkExpression(className).symbol;
                        if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
                            var classType = getJSClassType(classSymbol);
                            if (classType) {
                                return getFlowTypeOfReference(node, classType);
                            }
                        }
                    }
                    // Check if it's a constructor definition, can be either a variable decl or function decl
                    // i.e.
                    //   * /** @constructor */ function [name]() { ... }
                    //   * /** @constructor */ var x = function() { ... }
                    else if (isInJS &&
                        (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) &&
                        ts.getJSDocClassTag(container)) {
                        var classType = getJSClassType(container.symbol);
                        if (classType) {
                            return getFlowTypeOfReference(node, classType);
                        }
                    }
                    var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
                    if (thisType) {
                        return getFlowTypeOfReference(node, thisType);
                    }
                }
                if (ts.isClassLike(container.parent)) {
                    var symbol = getSymbolOfNode(container.parent);
                    var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
                    return getFlowTypeOfReference(node, type);
                }
                if (isInJS) {
                    var type = getTypeForThisExpressionFromJSDoc(container);
                    if (type && type !== errorType) {
                        return getFlowTypeOfReference(node, type);
                    }
                }
            }
            function getClassNameFromPrototypeMethod(container) {
                // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
                if (container.kind === 194 /* FunctionExpression */ &&
                    ts.isBinaryExpression(container.parent) &&
                    ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
                    // Get the 'x' of 'x.prototype.y = container'
                    return container.parent // x.prototype.y = container
                        .left // x.prototype.y
                        .expression // x.prototype
                        .expression; // x
                }
                // x.prototype = { method() { } }
                else if (container.kind === 154 /* MethodDeclaration */ &&
                    container.parent.kind === 186 /* ObjectLiteralExpression */ &&
                    ts.isBinaryExpression(container.parent.parent) &&
                    ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
                    return container.parent.parent.left.expression;
                }
                // x.prototype = { method: function() { } }
                else if (container.kind === 194 /* FunctionExpression */ &&
                    container.parent.kind === 273 /* PropertyAssignment */ &&
                    container.parent.parent.kind === 186 /* ObjectLiteralExpression */ &&
                    ts.isBinaryExpression(container.parent.parent.parent) &&
                    ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
                    return container.parent.parent.parent.left.expression;
                }
            }
            function getTypeForThisExpressionFromJSDoc(node) {
                var jsdocType = ts.getJSDocType(node);
                if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) {
                    var jsDocFunctionType = jsdocType;
                    if (jsDocFunctionType.parameters.length > 0 &&
                        jsDocFunctionType.parameters[0].name &&
                        jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
                        return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
                    }
                }
                var thisTag = ts.getJSDocThisTag(node);
                if (thisTag && thisTag.typeExpression) {
                    return getTypeFromTypeNode(thisTag.typeExpression);
                }
            }
            function isInConstructorArgumentInitializer(node, constructorDecl) {
                return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; });
            }
            function checkSuperExpression(node) {
                var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node;
                var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
                var needToCaptureLexicalThis = false;
                // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
                if (!isCallExpression) {
                    while (container && container.kind === 195 /* ArrowFunction */) {
                        container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
                        needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
                    }
                }
                var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
                var nodeCheckFlag = 0;
                if (!canUseSuperExpression) {
                    // issue more specific error if super is used in computed property name
                    // class A { foo() { return "1" }}
                    // class B {
                    //     [super.foo()]() {}
                    // }
                    var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; });
                    if (current && current.kind === 147 /* ComputedPropertyName */) {
                        error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
                    }
                    else if (isCallExpression) {
                        error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
                    }
                    else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */)) {
                        error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
                    }
                    else {
                        error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
                    }
                    return errorType;
                }
                if (!isCallExpression && container.kind === 155 /* Constructor */) {
                    checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
                }
                if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
                    nodeCheckFlag = 512 /* SuperStatic */;
                }
                else {
                    nodeCheckFlag = 256 /* SuperInstance */;
                }
                getNodeLinks(node).flags |= nodeCheckFlag;
                // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
                // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
                // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
                // uses an arrow function, which is permitted to reference `super`.
                //
                // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
                // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
                // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
                //
                // The simplest case is reading a value, in which case we will emit something like the following:
                //
                //  // ts
                //  ...
                //  async asyncMethod() {
                //    let x = await super.asyncMethod();
                //    return x;
                //  }
                //  ...
                //
                //  // js
                //  ...
                //  asyncMethod() {
                //      const _super = name => super[name];
                //      return __awaiter(this, arguments, Promise, function *() {
                //          let x = yield _super("asyncMethod").call(this);
                //          return x;
                //      });
                //  }
                //  ...
                //
                // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
                // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios:
                //
                //  // ts
                //  ...
                //  async asyncMethod(ar: Promise<any[]>) {
                //      [super.a, super.b] = await ar;
                //  }
                //  ...
                //
                //  // js
                //  ...
                //  asyncMethod(ar) {
                //      const _super = (function (geti, seti) {
                //          const cache = Object.create(null);
                //          return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });
                //      })(name => super[name], (name, value) => super[name] = value);
                //      return __awaiter(this, arguments, Promise, function *() {
                //          [_super("a").value, _super("b").value] = yield ar;
                //      });
                //  }
                //  ...
                //
                // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set.
                // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment
                // while a property access can.
                if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
                    if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
                        getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
                    }
                    else {
                        getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
                    }
                }
                if (needToCaptureLexicalThis) {
                    // call expressions are allowed only in constructors so they should always capture correct 'this'
                    // super property access expressions can also appear in arrow functions -
                    // in this case they should also use correct lexical this
                    captureLexicalThis(node.parent, container);
                }
                if (container.parent.kind === 186 /* ObjectLiteralExpression */) {
                    if (languageVersion < 2 /* ES2015 */) {
                        error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
                        return errorType;
                    }
                    else {
                        // for object literal assume that type of 'super' is 'any'
                        return anyType;
                    }
                }
                // at this point the only legal case for parent is ClassLikeDeclaration
                var classLikeDeclaration = container.parent;
                if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) {
                    error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
                    return errorType;
                }
                var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
                var baseClassType = classType && getBaseTypes(classType)[0];
                if (!baseClassType) {
                    return errorType;
                }
                if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
                    // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
                    error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
                    return errorType;
                }
                return nodeCheckFlag === 512 /* SuperStatic */
                    ? getBaseConstructorTypeOfClass(classType)
                    : getTypeWithThisArgument(baseClassType, classType.thisType);
                function isLegalUsageOfSuperExpression(container) {
                    if (!container) {
                        return false;
                    }
                    if (isCallExpression) {
                        // TS 1.0 SPEC (April 2014): 4.8.1
                        // Super calls are only permitted in constructors of derived classes
                        return container.kind === 155 /* Constructor */;
                    }
                    else {
                        // TS 1.0 SPEC (April 2014)
                        // 'super' property access is allowed
                        // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
                        // - In a static member function or static member accessor
                        // topmost container must be something that is directly nested in the class declaration\object literal expression
                        if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) {
                            if (ts.hasModifier(container, 32 /* Static */)) {
                                return container.kind === 154 /* MethodDeclaration */ ||
                                    container.kind === 153 /* MethodSignature */ ||
                                    container.kind === 156 /* GetAccessor */ ||
                                    container.kind === 157 /* SetAccessor */;
                            }
                            else {
                                return container.kind === 154 /* MethodDeclaration */ ||
                                    container.kind === 153 /* MethodSignature */ ||
                                    container.kind === 156 /* GetAccessor */ ||
                                    container.kind === 157 /* SetAccessor */ ||
                                    container.kind === 152 /* PropertyDeclaration */ ||
                                    container.kind === 151 /* PropertySignature */ ||
                                    container.kind === 155 /* Constructor */;
                            }
                        }
                    }
                    return false;
                }
            }
            function getContainingObjectLiteral(func) {
                return (func.kind === 154 /* MethodDeclaration */ ||
                    func.kind === 156 /* GetAccessor */ ||
                    func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent :
                    func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent :
                        undefined;
            }
            function getThisTypeArgument(type) {
                return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined;
            }
            function getThisTypeFromContextualType(type) {
                return mapType(type, function (t) {
                    return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
                });
            }
            function getContextualThisParameterType(func) {
                if (func.kind === 195 /* ArrowFunction */) {
                    return undefined;
                }
                if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
                    var contextualSignature = getContextualSignature(func);
                    if (contextualSignature) {
                        var thisParameter = contextualSignature.thisParameter;
                        if (thisParameter) {
                            return getTypeOfSymbol(thisParameter);
                        }
                    }
                }
                var inJs = ts.isInJSFile(func);
                if (noImplicitThis || inJs) {
                    var containingLiteral = getContainingObjectLiteral(func);
                    if (containingLiteral) {
                        // We have an object literal method. Check if the containing object literal has a contextual type
                        // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
                        // any directly enclosing object literals.
                        var contextualType = getApparentTypeOfContextualType(containingLiteral);
                        var literal = containingLiteral;
                        var type = contextualType;
                        while (type) {
                            var thisType = getThisTypeFromContextualType(type);
                            if (thisType) {
                                return instantiateType(thisType, getContextualMapper(containingLiteral));
                            }
                            if (literal.parent.kind !== 273 /* PropertyAssignment */) {
                                break;
                            }
                            literal = literal.parent.parent;
                            type = getApparentTypeOfContextualType(literal);
                        }
                        // There was no contextual ThisType<T> for the containing object literal, so the contextual type
                        // for 'this' is the non-null form of the contextual type for the containing object literal or
                        // the type of the object literal itself.
                        return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral);
                    }
                    // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
                    // contextual type for 'this' is 'obj'.
                    var parent = func.parent;
                    if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) {
                        var target = parent.left;
                        if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) {
                            var expression = target.expression;
                            // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
                            if (inJs && ts.isIdentifier(expression)) {
                                var sourceFile = ts.getSourceFileOfNode(parent);
                                if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
                                    return undefined;
                                }
                            }
                            return checkExpressionCached(expression);
                        }
                    }
                }
                return undefined;
            }
            // Return contextual type of parameter or undefined if no contextual type is available
            function getContextuallyTypedParameterType(parameter) {
                var func = parameter.parent;
                if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
                    return undefined;
                }
                var iife = ts.getImmediatelyInvokedFunctionExpression(func);
                if (iife && iife.arguments) {
                    var args = getEffectiveCallArguments(iife);
                    var indexOfParameter = func.parameters.indexOf(parameter);
                    if (parameter.dotDotDotToken) {
                        return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
                    }
                    var links = getNodeLinks(iife);
                    var cached = links.resolvedSignature;
                    links.resolvedSignature = anySignature;
                    var type = indexOfParameter < args.length ?
                        getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
                        parameter.initializer ? undefined : undefinedWideningType;
                    links.resolvedSignature = cached;
                    return type;
                }
                var contextualSignature = getContextualSignature(func);
                if (contextualSignature) {
                    var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
                    return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
                        getRestTypeAtPosition(contextualSignature, index) :
                        tryGetTypeAtPosition(contextualSignature, index);
                }
            }
            // In a variable, parameter or property declaration with a type annotation,
            //   the contextual type of an initializer expression is the type of the variable, parameter or property.
            // Otherwise, in a parameter declaration of a contextually typed function expression,
            //   the contextual type of an initializer expression is the contextual type of the parameter.
            // Otherwise, in a variable or parameter declaration with a binding pattern name,
            //   the contextual type of an initializer expression is the type implied by the binding pattern.
            // Otherwise, in a binding pattern inside a variable or parameter declaration,
            //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
            function getContextualTypeForInitializerExpression(node) {
                var declaration = node.parent;
                if (ts.hasInitializer(declaration) && node === declaration.initializer) {
                    var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
                    if (typeNode) {
                        return getTypeFromTypeNode(typeNode);
                    }
                    if (declaration.kind === 149 /* Parameter */) {
                        var type = getContextuallyTypedParameterType(declaration);
                        if (type) {
                            return type;
                        }
                    }
                    if (ts.isBindingPattern(declaration.name)) {
                        return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
                    }
                    if (ts.isBindingPattern(declaration.parent)) {
                        var parentDeclaration = declaration.parent.parent;
                        var name = declaration.propertyName || declaration.name;
                        if (parentDeclaration.kind !== 184 /* BindingElement */) {
                            var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration);
                            if (parentTypeNode && !ts.isBindingPattern(name)) {
                                var text = ts.getTextOfPropertyName(name);
                                if (text) {
                                    return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text);
                                }
                            }
                        }
                    }
                }
                return undefined;
            }
            function getContextualTypeForReturnExpression(node) {
                var func = ts.getContainingFunction(node);
                if (func) {
                    var functionFlags = ts.getFunctionFlags(func);
                    if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
                        return undefined;
                    }
                    var contextualReturnType = getContextualReturnType(func);
                    return functionFlags & 2 /* Async */
                        ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function
                        : contextualReturnType; // Regular function
                }
                return undefined;
            }
            function getContextualTypeForYieldOperand(node) {
                var func = ts.getContainingFunction(node);
                if (func) {
                    var functionFlags = ts.getFunctionFlags(func);
                    var contextualReturnType = getContextualReturnType(func);
                    if (contextualReturnType) {
                        return node.asteriskToken
                            ? contextualReturnType
                            : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
                    }
                }
                return undefined;
            }
            function isInParameterInitializerBeforeContainingFunction(node) {
                var inBindingInitializer = false;
                while (node.parent && !ts.isFunctionLike(node.parent)) {
                    if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
                        return true;
                    }
                    if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
                        inBindingInitializer = true;
                    }
                    node = node.parent;
                }
                return false;
            }
            function getContextualReturnType(functionDecl) {
                // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
                // corresponding set accessor has a type annotation, return statements in the function are contextually typed
                var returnType = getReturnTypeFromAnnotation(functionDecl);
                if (returnType) {
                    return returnType;
                }
                // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
                // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
                var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
                if (signature && !isResolvingReturnTypeOfSignature(signature)) {
                    return getReturnTypeOfSignature(signature);
                }
                return undefined;
            }
            // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
            function getContextualTypeForArgument(callTarget, arg) {
                var args = getEffectiveCallArguments(callTarget);
                var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
                return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
            }
            function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
                // If we're already in the process of resolving the given signature, don't resolve again as
                // that could cause infinite recursion. Instead, return anySignature.
                var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
                return getTypeAtPosition(signature, argIndex);
            }
            function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
                if (template.parent.kind === 191 /* TaggedTemplateExpression */) {
                    return getContextualTypeForArgument(template.parent, substitutionExpression);
                }
                return undefined;
            }
            function getContextualTypeForBinaryOperand(node) {
                var binaryExpression = node.parent;
                var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
                switch (operatorToken.kind) {
                    case 58 /* EqualsToken */:
                        if (node !== right) {
                            return undefined;
                        }
                        var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
                        if (!contextSensitive) {
                            return undefined;
                        }
                        return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
                    case 54 /* BarBarToken */:
                        // When an || expression has a contextual type, the operands are contextually typed by that type. When an ||
                        // expression has no contextual type, the right operand is contextually typed by the type of the left operand,
                        // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}`
                        var type = getContextualType(binaryExpression);
                        return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ?
                            getTypeOfExpression(left) : type;
                    case 53 /* AmpersandAmpersandToken */:
                    case 26 /* CommaToken */:
                        return node === right ? getContextualType(binaryExpression) : undefined;
                    default:
                        return undefined;
                }
            }
            // In an assignment expression, the right operand is contextually typed by the type of the left operand.
            // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
            function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
                var kind = ts.getAssignmentDeclarationKind(binaryExpression);
                switch (kind) {
                    case 0 /* None */:
                        return true;
                    case 5 /* Property */:
                    case 1 /* ExportsProperty */:
                    case 6 /* Prototype */:
                    case 3 /* PrototypeProperty */:
                        // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
                        // See `bindStaticPropertyAssignment` in `binder.ts`.
                        if (!binaryExpression.left.symbol) {
                            return true;
                        }
                        else {
                            var decl = binaryExpression.left.symbol.valueDeclaration;
                            if (!decl) {
                                return false;
                            }
                            var lhs = binaryExpression.left;
                            var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
                            if (overallAnnotation) {
                                return getTypeFromTypeNode(overallAnnotation);
                            }
                            else if (ts.isIdentifier(lhs.expression)) {
                                var id = lhs.expression;
                                var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true);
                                if (parentSymbol) {
                                    var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
                                    if (annotated) {
                                        var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText);
                                        return type || false;
                                    }
                                    return false;
                                }
                            }
                            return !ts.isInJSFile(decl);
                        }
                    case 2 /* ModuleExports */:
                    case 4 /* ThisProperty */:
                        if (!binaryExpression.symbol)
                            return true;
                        if (binaryExpression.symbol.valueDeclaration) {
                            var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
                            if (annotated) {
                                var type = getTypeFromTypeNode(annotated);
                                if (type) {
                                    return type;
                                }
                            }
                        }
                        if (kind === 2 /* ModuleExports */)
                            return false;
                        var thisAccess = binaryExpression.left;
                        if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
                            return false;
                        }
                        var thisType = checkThisExpression(thisAccess.expression);
                        return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false;
                    default:
                        return ts.Debug.assertNever(kind);
                }
            }
            function getTypeOfPropertyOfContextualType(type, name) {
                return mapType(type, function (t) {
                    if (t.flags & 917504 /* StructuredType */) {
                        var prop = getPropertyOfType(t, name);
                        if (prop) {
                            return getTypeOfSymbol(prop);
                        }
                        if (isTupleType(t)) {
                            var restType = getRestTypeOfTupleType(t);
                            if (restType && isNumericLiteralName(name) && +name >= 0) {
                                return restType;
                            }
                        }
                    }
                    return undefined;
                }, /*noReductions*/ true);
            }
            function getIndexTypeOfContextualType(type, kind) {
                return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
            }
            // Return true if the given contextual type is a tuple-like type
            function contextualTypeIsTupleLikeType(type) {
                return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type));
            }
            // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
            // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
            // exists. Otherwise, it is the type of the string index signature in T, if one exists.
            function getContextualTypeForObjectLiteralMethod(node) {
                ts.Debug.assert(ts.isObjectLiteralMethod(node));
                if (node.flags & 8388608 /* InWithStatement */) {
                    // We cannot answer semantic questions within a with block, do not proceed any further
                    return undefined;
                }
                return getContextualTypeForObjectLiteralElement(node);
            }
            function getContextualTypeForObjectLiteralElement(element) {
                var objectLiteral = element.parent;
                var type = getApparentTypeOfContextualType(objectLiteral);
                if (type) {
                    if (!hasNonBindableDynamicName(element)) {
                        // For a (non-symbol) computed property, there is no reason to look up the name
                        // in the type. It will just be "__computed", which does not appear in any
                        // SymbolTable.
                        var symbolName_3 = getSymbolOfNode(element).escapedName;
                        var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
                        if (propertyType) {
                            return propertyType;
                        }
                    }
                    return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
                        getIndexTypeOfContextualType(type, 0 /* String */);
                }
                return undefined;
            }
            // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
            // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
            // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
            // type of T.
            function getContextualTypeForElementExpression(arrayContextualType, index) {
                return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
                    || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */)
                    || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false));
            }
            // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
            function getContextualTypeForConditionalOperand(node) {
                var conditional = node.parent;
                return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined;
            }
            function getContextualTypeForChildJsxExpression(node) {
                var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
                // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
                var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
                return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined;
            }
            function getContextualTypeForJsxExpression(node) {
                var exprParent = node.parent;
                return ts.isJsxAttributeLike(exprParent)
                    ? getContextualType(node)
                    : ts.isJsxElement(exprParent)
                        ? getContextualTypeForChildJsxExpression(exprParent)
                        : undefined;
            }
            function getContextualTypeForJsxAttribute(attribute) {
                // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
                // which is a type of the parameter of the signature we are trying out.
                // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
                if (ts.isJsxAttribute(attribute)) {
                    var attributesType = getApparentTypeOfContextualType(attribute.parent);
                    if (!attributesType || isTypeAny(attributesType)) {
                        return undefined;
                    }
                    return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
                }
                else {
                    return getContextualType(attribute.parent);
                }
            }
            // Return true if the given expression is possibly a discriminant value. We limit the kinds of
            // expressions we check to those that don't depend on their contextual type in order not to cause
            // recursive (and possibly infinite) invocations of getContextualType.
            function isPossiblyDiscriminantValue(node) {
                switch (node.kind) {
                    case 9 /* StringLiteral */:
                    case 8 /* NumericLiteral */:
                    case 13 /* NoSubstitutionTemplateLiteral */:
                    case 101 /* TrueKeyword */:
                    case 86 /* FalseKeyword */:
                    case 95 /* NullKeyword */:
                    case 71 /* Identifier */:
                        return true;
                    case 187 /* PropertyAccessExpression */:
                    case 193 /* ParenthesizedExpression */:
                        return isPossiblyDiscriminantValue(node.expression);
                }
                return false;
            }
            // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
            // be "pushed" onto a node using the contextualType property.
            function getApparentTypeOfContextualType(node) {
                var contextualType = getContextualType(node);
                contextualType = contextualType && mapType(contextualType, getApparentType);
                if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) {
                    return contextualType;
                }
                // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType`
                var match;
                propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
                    var prop = _a[_i];
                    if (!prop.symbol)
                        continue;
                    if (prop.kind !== 273 /* PropertyAssignment */)
                        continue;
                    if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) {
                        var discriminatingType = checkExpression(prop.initializer);
                        for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) {
                            var type = _c[_b];
                            var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName);
                            if (targetType && isTypeAssignableTo(discriminatingType, targetType)) {
                                if (match) {
                                    if (type === match)
                                        continue; // Finding multiple fields which discriminate to the same type is fine
                                    match = undefined;
                                    break propLoop;
                                }
                                match = type;
                            }
                        }
                    }
                }
                return match || contextualType;
            }
            /**
             * Woah! Do you really want to use this function?
             *
             * Unless you're trying to get the *non-apparent* type for a
             * value-literal type or you're authoring relevant portions of this algorithm,
             * you probably meant to use 'getApparentTypeOfContextualType'.
             * Otherwise this may not be very useful.
             *
             * In cases where you *are* working on this function, you should understand
             * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
             *
             *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
             *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
             *
             * @param node the expression whose contextual type will be returned.
             * @returns the contextual type of an expression.
             */
            function getContextualType(node) {
                if (node.flags & 8388608 /* InWithStatement */) {
                    // We cannot answer semantic questions within a with block, do not proceed any further
                    return undefined;
                }
                if (node.contextualType) {
                    return node.contextualType;
                }
                var parent = node.parent;
                switch (parent.kind) {
                    case 235 /* VariableDeclaration */:
                    case 149 /* Parameter */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                    case 184 /* BindingElement */:
                        return getContextualTypeForInitializerExpression(node);
                    case 195 /* ArrowFunction */:
                    case 228 /* ReturnStatement */:
                        return getContextualTypeForReturnExpression(node);
                    case 205 /* YieldExpression */:
                        return getContextualTypeForYieldOperand(parent);
                    case 189 /* CallExpression */:
                    case 190 /* NewExpression */:
                        return getContextualTypeForArgument(parent, node);
                    case 192 /* TypeAssertionExpression */:
                    case 210 /* AsExpression */:
                        return getTypeFromTypeNode(parent.type);
                    case 202 /* BinaryExpression */:
                        return getContextualTypeForBinaryOperand(node);
                    case 273 /* PropertyAssignment */:
                    case 274 /* ShorthandPropertyAssignment */:
                        return getContextualTypeForObjectLiteralElement(parent);
                    case 275 /* SpreadAssignment */:
                        return getApparentTypeOfContextualType(parent.parent);
                    case 185 /* ArrayLiteralExpression */: {
                        var arrayLiteral = parent;
                        var type = getApparentTypeOfContextualType(arrayLiteral);
                        return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
                    }
                    case 203 /* ConditionalExpression */:
                        return getContextualTypeForConditionalOperand(node);
                    case 214 /* TemplateSpan */:
                        ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */);
                        return getContextualTypeForSubstitutionExpression(parent.parent, node);
                    case 193 /* ParenthesizedExpression */: {
                        // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
                        var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
                        return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent);
                    }
                    case 268 /* JsxExpression */:
                        return getContextualTypeForJsxExpression(parent);
                    case 265 /* JsxAttribute */:
                    case 267 /* JsxSpreadAttribute */:
                        return getContextualTypeForJsxAttribute(parent);
                    case 260 /* JsxOpeningElement */:
                    case 259 /* JsxSelfClosingElement */:
                        return getContextualJsxElementAttributesType(parent);
                }
                return undefined;
            }
            function getContextualMapper(node) {
                var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
                return ancestor ? ancestor.contextualMapper : identityMapper;
            }
            function getContextualJsxElementAttributesType(node) {
                if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
                    // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
                    // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
                    // (as below) instead!
                    return node.parent.contextualType;
                }
                if (isJsxIntrinsicIdentifier(node.tagName)) {
                    return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
                }
                var valueType = checkExpression(node.tagName);
                if (isTypeAny(valueType)) {
                    // Short-circuit if the class tag is using an element type 'any'
                    return anyType;
                }
                var isJs = ts.isInJSFile(node);
                return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); });
            }
            function getJsxSignaturesParameterTypes(valueType, isJs, context) {
                // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type
                if (valueType.flags & 4 /* String */) {
                    return anyType;
                }
                else if (valueType.flags & 64 /* StringLiteral */) {
                    // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type
                    // For example:
                    //      var CustomTag: "h1" = "h1";
                    //      <CustomTag> Hello World </CustomTag>
                    var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context);
                    if (intrinsicElementsType !== errorType) {
                        var stringLiteralTypeName = valueType.value;
                        var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
                        if (intrinsicProp) {
                            return getTypeOfSymbol(intrinsicProp);
                        }
                        var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
                        if (indexSignatureType) {
                            return indexSignatureType;
                        }
                    }
                    return anyType;
                }
                // Resolve the signatures, preferring constructor
                var signatures = getSignaturesOfType(valueType, 1 /* Construct */);
                var ctor = true;
                if (signatures.length === 0) {
                    // No construct signatures, try call signatures
                    signatures = getSignaturesOfType(valueType, 0 /* Call */);
                    ctor = false;
                    if (signatures.length === 0) {
                        // We found no signatures at all, which is an error
                        return errorType;
                    }
                }
                var links = getNodeLinks(context);
                if (!links.resolvedSignatures) {
                    links.resolvedSignatures = ts.createMap();
                }
                var cacheKey = "" + getTypeId(valueType);
                var cachedResolved = links.resolvedSignatures.get(cacheKey);
                if (cachedResolved && cachedResolved !== resolvingSignaturesArray) {
                    signatures = cachedResolved;
                }
                else if (!cachedResolved) {
                    links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray);
                    links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures));
                }
                return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */);
            }
            function getJsxPropsTypeFromCallSignature(sig, context) {
                var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType);
                propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
                var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
                if (intrinsicAttribs !== errorType) {
                    propsType = intersectTypes(intrinsicAttribs, propsType);
                }
                return propsType;
            }
            function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
                var instanceType = getReturnTypeOfSignature(sig);
                return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
            }
            function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
                var managedSym = getJsxLibraryManagedAttributes(ns);
                if (managedSym) {
                    var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
                    if (ts.length(declaredManagedType.typeParameters) >= 2) {
                        var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
                        return createTypeReference(declaredManagedType, args);
                    }
                    else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
                        var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
                        return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
                    }
                }
                return attributesType;
            }
            function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) {
                var ns = getJsxNamespaceAt(context);
                var forcedLookupLocation = getJsxElementPropertiesName(ns);
                var attributesType = forcedLookupLocation === undefined
                    // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
                    ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType)
                    : forcedLookupLocation === ""
                        // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
                        ? getReturnTypeOfSignature(sig)
                        // Otherwise get the type of the property on the signature return type
                        : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
                if (!attributesType) {
                    // There is no property named 'props' on this instance type
                    if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
                        error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
                    }
                    return emptyObjectType;
                }
                attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
                if (isTypeAny(attributesType)) {
                    // Props is of type 'any' or unknown
                    return attributesType;
                }
                else {
                    // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
                    var apparentAttributesType = attributesType;
                    var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
                    if (intrinsicClassAttribs !== errorType) {
                        var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
                        var hostClassType = getReturnTypeOfSignature(sig);
                        apparentAttributesType = intersectTypes(typeParams
                            ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs))
                            : intrinsicClassAttribs, apparentAttributesType);
                    }
                    var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
                    if (intrinsicAttribs !== errorType) {
                        apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
                    }
                    return apparentAttributesType;
                }
            }
            // If the given type is an object or union type with a single signature, and if that signature has at
            // least as many parameters as the given function, return the signature. Otherwise return undefined.
            function getContextualCallSignature(type, node) {
                var signatures = getSignaturesOfType(type, 0 /* Call */);
                if (signatures.length === 1) {
                    var signature = signatures[0];
                    if (!isAritySmaller(signature, node)) {
                        return signature;
                    }
                }
            }
            /** If the contextual signature has fewer parameters than the function expression, do not use it */
            function isAritySmaller(signature, target) {
                var targetParameterCount = 0;
                for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
                    var param = target.parameters[targetParameterCount];
                    if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
                        break;
                    }
                }
                if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
                    targetParameterCount--;
                }
                return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
            }
            function isFunctionExpressionOrArrowFunction(node) {
                return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */;
            }
            function getContextualSignatureForFunctionLikeDeclaration(node) {
                // Only function expressions, arrow functions, and object literal methods are contextually typed.
                return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
                    ? getContextualSignature(node)
                    : undefined;
            }
            function getContextualTypeForFunctionLikeDeclaration(node) {
                return ts.isObjectLiteralMethod(node) ?
                    getContextualTypeForObjectLiteralMethod(node) :
                    getApparentTypeOfContextualType(node);
            }
            // Return the contextual signature for a given expression node. A contextual type provides a
            // contextual signature if it has a single call signature and if that call signature is non-generic.
            // If the contextual type is a union type, get the signature from each type possible and if they are
            // all identical ignoring their return type, the result is same signature but with return type as
            // union type of return types from these signatures
            function getContextualSignature(node) {
                ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
                var typeTagSignature = getSignatureOfTypeTag(node);
                if (typeTagSignature) {
                    return typeTagSignature;
                }
                var type = getContextualTypeForFunctionLikeDeclaration(node);
                if (!type) {
                    return undefined;
                }
                if (!(type.flags & 262144 /* Union */)) {
                    return getContextualCallSignature(type, node);
                }
                var signatureList;
                var types = type.types;
                for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
                    var current = types_14[_i];
                    var signature = getContextualCallSignature(current, node);
                    if (signature) {
                        if (!signatureList) {
                            // This signature will contribute to contextual union signature
                            signatureList = [signature];
                        }
                        else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
                            // Signatures aren't identical, do not use
                            return undefined;
                        }
                        else {
                            // Use this signature for contextual union signature
                            signatureList.push(signature);
                        }
                    }
                }
                // Result is union of signatures collected (return type is union of return types of this signature set)
                var result;
                if (signatureList) {
                    result = cloneSignature(signatureList[0]);
                    result.unionSignatures = signatureList;
                }
                return result;
            }
            function checkSpreadExpression(node, checkMode) {
                if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
                    checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */);
                }
                var arrayOrIterableType = checkExpression(node.expression, checkMode);
                return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false);
            }
            function hasDefaultValue(node) {
                return (node.kind === 184 /* BindingElement */ && !!node.initializer) ||
                    (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */);
            }
            function checkArrayLiteral(node, checkMode, forceTuple) {
                var elements = node.elements;
                var elementCount = elements.length;
                var hasNonEndingSpreadElement = false;
                var elementTypes = [];
                var inDestructuringPattern = ts.isAssignmentTarget(node);
                var contextualType = getApparentTypeOfContextualType(node);
                for (var index = 0; index < elementCount; index++) {
                    var e = elements[index];
                    if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) {
                        // Given the following situation:
                        //    var c: {};
                        //    [...c] = ["", 0];
                        //
                        // c is represented in the tree as a spread element in an array literal.
                        // But c really functions as a rest element, and its purpose is to provide
                        // a contextual type for the right hand side of the assignment. Therefore,
                        // instead of calling checkExpression on "...c", which will give an error
                        // if c is not iterable/array-like, we need to act as if we are trying to
                        // get the contextual element type from it. So we do something similar to
                        // getContextualTypeForElementExpression, which will crucially not error
                        // if there is no index type / iterated type.
                        var restArrayType = checkExpression(e.expression, checkMode, forceTuple);
                        var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) ||
                            getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false);
                        if (restElementType) {
                            elementTypes.push(restElementType);
                        }
                    }
                    else {
                        var elementContextualType = getContextualTypeForElementExpression(contextualType, index);
                        var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
                        elementTypes.push(type);
                    }
                    if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) {
                        hasNonEndingSpreadElement = true;
                    }
                }
                if (!hasNonEndingSpreadElement) {
                    var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */;
                    var minLength = elementCount - (hasRestElement ? 1 : 0);
                    // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
                    // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
                    if (inDestructuringPattern && minLength > 0) {
                        var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement));
                        type.pattern = node;
                        return type;
                    }
                    if (contextualType && contextualTypeIsTupleLikeType(contextualType)) {
                        var pattern = contextualType.pattern;
                        // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
                        // tuple type with the corresponding binding or assignment element types to make the lengths equal.
                        if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) {
                            var patternElements = pattern.elements;
                            for (var i = elementCount; i < patternElements.length; i++) {
                                var e = patternElements[i];
                                if (hasDefaultValue(e)) {
                                    elementTypes.push(contextualType.typeArguments[i]);
                                }
                                else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) {
                                    if (e.kind !== 208 /* OmittedExpression */) {
                                        error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
                                    }
                                    elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType);
                                }
                            }
                        }
                        return createTupleType(elementTypes, minLength, hasRestElement);
                    }
                    else if (forceTuple) {
                        return createTupleType(elementTypes, minLength, hasRestElement);
                    }
                }
                return getArrayLiteralType(elementTypes, 2 /* Subtype */);
            }
            function getArrayLiteralType(elementTypes, unionReduction) {
                if (unionReduction === void 0) {
                    unionReduction = 1 /* Literal */;
                }
                return createArrayType(elementTypes.length ?
                    getUnionType(elementTypes, unionReduction) :
                    strictNullChecks ? implicitNeverType : undefinedWideningType);
            }
            function isNumericName(name) {
                switch (name.kind) {
                    case 147 /* ComputedPropertyName */:
                        return isNumericComputedName(name);
                    case 71 /* Identifier */:
                        return isNumericLiteralName(name.escapedText);
                    case 8 /* NumericLiteral */:
                    case 9 /* StringLiteral */:
                        return isNumericLiteralName(name.text);
                    default:
                        return false;
                }
            }
            function isNumericComputedName(name) {
                // It seems odd to consider an expression of type Any to result in a numeric name,
                // but this behavior is consistent with checkIndexedAccess
                return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */);
            }
            function isInfinityOrNaNString(name) {
                return name === "Infinity" || name === "-Infinity" || name === "NaN";
            }
            function isNumericLiteralName(name) {
                // The intent of numeric names is that
                //     - they are names with text in a numeric form, and that
                //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
                //         acquired by applying the abstract 'ToNumber' operation on the name's text.
                //
                // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
                // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
                //
                // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
                // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
                // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
                // because their 'ToString' representation is not equal to their original text.
                // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
                //
                // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
                // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
                // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
                //
                // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
                // This is desired behavior, because when indexing with them as numeric entities, you are indexing
                // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
                return (+name).toString() === name;
            }
            function checkComputedPropertyName(node) {
                var links = getNodeLinks(node.expression);
                if (!links.resolvedType) {
                    links.resolvedType = checkExpression(node.expression);
                    // This will allow types number, string, symbol or any. It will also allow enums, the unknown
                    // type, and any union of these types (like string | number).
                    if (links.resolvedType.flags & 24576 /* Nullable */ ||
                        !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) &&
                            !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
                        error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
                    }
                    else {
                        checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
                    }
                }
                return links.resolvedType;
            }
            function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
                var propTypes = [];
                for (var i = 0; i < properties.length; i++) {
                    if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) {
                        propTypes.push(getTypeOfSymbol(properties[i]));
                    }
                }
                var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
                return createIndexInfo(unionType, /*isReadonly*/ false);
            }
            function checkObjectLiteral(node, checkMode) {
                var inDestructuringPattern = ts.isAssignmentTarget(node);
                // Grammar checking
                checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
                var propertiesTable;
                var propertiesArray = [];
                var spread = emptyObjectType;
                var propagatedFlags = 33554432 /* FreshLiteral */;
                var contextualType = getApparentTypeOfContextualType(node);
                var contextualTypeHasPattern = contextualType && contextualType.pattern &&
                    (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */);
                var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
                var enumTag = ts.getJSDocEnumTag(node);
                var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
                var typeFlags = 0;
                var patternWithComputedProperties = false;
                var hasComputedStringProperty = false;
                var hasComputedNumberProperty = false;
                propertiesTable = ts.createSymbolTable();
                var offset = 0;
                for (var i = 0; i < node.properties.length; i++) {
                    var memberDecl = node.properties[i];
                    var member = getSymbolOfNode(memberDecl);
                    var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
                        checkComputedPropertyName(memberDecl.name) : undefined;
                    if (memberDecl.kind === 273 /* PropertyAssignment */ ||
                        memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ||
                        ts.isObjectLiteralMethod(memberDecl)) {
                        var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
                            memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
                                checkObjectLiteralMethod(memberDecl, checkMode);
                        if (isInJavascript) {
                            var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
                            if (jsDocType) {
                                checkTypeAssignableTo(type, jsDocType, memberDecl);
                                type = jsDocType;
                            }
                            else if (enumTag && enumTag.typeExpression) {
                                checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
                            }
                        }
                        typeFlags |= type.flags;
                        var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ?
                            computedNameType : undefined;
                        var prop = nameType ?
                            createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) :
                            createSymbol(4 /* Property */ | member.flags, member.escapedName);
                        if (nameType) {
                            prop.nameType = nameType;
                        }
                        if (inDestructuringPattern) {
                            // If object literal is an assignment pattern and if the assignment pattern specifies a default value
                            // for the property, make the property optional.
                            var isOptional = (memberDecl.kind === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
                                (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
                            if (isOptional) {
                                prop.flags |= 16777216 /* Optional */;
                            }
                        }
                        else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
                            // If object literal is contextually typed by the implied type of a binding pattern, and if the
                            // binding pattern specifies a default value for the property, make the property optional.
                            var impliedProp = getPropertyOfType(contextualType, member.escapedName);
                            if (impliedProp) {
                                prop.flags |= impliedProp.flags & 16777216 /* Optional */;
                            }
                            else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
                                error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
                            }
                        }
                        prop.declarations = member.declarations;
                        prop.parent = member.parent;
                        if (member.valueDeclaration) {
                            prop.valueDeclaration = member.valueDeclaration;
                        }
                        prop.type = type;
                        prop.target = member;
                        member = prop;
                    }
                    else if (memberDecl.kind === 275 /* SpreadAssignment */) {
                        if (languageVersion < 2 /* ES2015 */) {
                            checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
                        }
                        if (propertiesArray.length > 0) {
                            spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0);
                            propertiesArray = [];
                            propertiesTable = ts.createSymbolTable();
                            hasComputedStringProperty = false;
                            hasComputedNumberProperty = false;
                            typeFlags = 0;
                        }
                        var type = checkExpression(memberDecl.expression);
                        if (!isValidSpreadType(type)) {
                            error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
                            return errorType;
                        }
                        spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0);
                        offset = i + 1;
                        continue;
                    }
                    else {
                        // TypeScript 1.0 spec (April 2014)
                        // A get accessor declaration is processed in the same manner as
                        // an ordinary function declaration(section 6.1) with no parameters.
                        // A set accessor declaration is processed in the same manner
                        // as an ordinary function declaration with a single parameter and a Void return type.
                        ts.Debug.assert(memberDecl.kind === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */);
                        checkNodeDeferred(memberDecl);
                    }
                    if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) {
                        if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
                            if (isTypeAssignableTo(computedNameType, numberType)) {
                                hasComputedNumberProperty = true;
                            }
                            else {
                                hasComputedStringProperty = true;
                            }
                            if (inDestructuringPattern) {
                                patternWithComputedProperties = true;
                            }
                        }
                    }
                    else {
                        propertiesTable.set(member.escapedName, member);
                    }
                    propertiesArray.push(member);
                }
                // If object literal is contextually typed by the implied type of a binding pattern, augment the result
                // type with those properties for which the binding pattern specifies a default value.
                if (contextualTypeHasPattern) {
                    for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) {
                        var prop = _a[_i];
                        if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) {
                            if (!(prop.flags & 16777216 /* Optional */)) {
                                error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
                            }
                            propertiesTable.set(prop.escapedName, prop);
                            propertiesArray.push(prop);
                        }
                    }
                }
                if (spread !== emptyObjectType) {
                    if (propertiesArray.length > 0) {
                        spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0);
                    }
                    return spread;
                }
                return createObjectLiteralType();
                function createObjectLiteralType() {
                    var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
                    var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
                    var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
                    var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */;
                    result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */);
                    result.objectFlags |= 128 /* ObjectLiteral */;
                    if (isJSObjectLiteral) {
                        result.objectFlags |= 16384 /* JSLiteral */;
                    }
                    if (patternWithComputedProperties) {
                        result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
                    }
                    if (inDestructuringPattern) {
                        result.pattern = node;
                    }
                    if (!(result.flags & 24576 /* Nullable */)) {
                        propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */);
                    }
                    return result;
                }
            }
            function isValidSpreadType(type) {
                return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) ||
                    getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
                    type.flags & 131072 /* Object */ && !isGenericMappedType(type) ||
                    type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
            }
            function checkJsxSelfClosingElementDeferred(node) {
                checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */);
            }
            function checkJsxSelfClosingElement(node, _checkMode) {
                checkNodeDeferred(node);
                return getJsxElementTypeAt(node) || anyType;
            }
            function checkJsxElementDeferred(node) {
                // Check attributes
                checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */);
                // Perform resolution on the closing tag so that rename/go to definition/etc work
                if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
                    getIntrinsicTagSymbol(node.closingElement);
                }
                else {
                    checkExpression(node.closingElement.tagName);
                }
            }
            function checkJsxElement(node, _checkMode) {
                checkNodeDeferred(node);
                return getJsxElementTypeAt(node) || anyType;
            }
            function checkJsxFragment(node, checkMode) {
                checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode);
                if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
                    error(node, compilerOptions.jsxFactory
                        ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
                        : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
                }
                return getJsxElementTypeAt(node) || anyType;
            }
            /**
             * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
             */
            function isUnhyphenatedJsxName(name) {
                // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
                return !ts.stringContains(name, "-");
            }
            /**
             * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
             */
            function isJsxIntrinsicIdentifier(tagName) {
                return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
            }
            function checkJsxAttribute(node, checkMode) {
                return node.initializer
                    ? checkExpressionForMutableLocation(node.initializer, checkMode)
                    : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
            }
            /**
             * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
             *
             * @param openingLikeElement a JSX opening-like element
             * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
             * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
             * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
             * which also calls getSpreadType.
             */
            function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
                var attributes = openingLikeElement.attributes;
                var attributesTable = ts.createSymbolTable();
                var spread = emptyObjectType;
                var hasSpreadAnyType = false;
                var typeToIntersect;
                var explicitlySpecifyChildrenAttribute = false;
                var propagatingFlags = 0;
                var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
                for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
                    var attributeDecl = _a[_i];
                    var member = attributeDecl.symbol;
                    if (ts.isJsxAttribute(attributeDecl)) {
                        var exprType = checkJsxAttribute(attributeDecl, checkMode);
                        propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */);
                        var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
                        attributeSymbol.declarations = member.declarations;
                        attributeSymbol.parent = member.parent;
                        if (member.valueDeclaration) {
                            attributeSymbol.valueDeclaration = member.valueDeclaration;
                        }
                        attributeSymbol.type = exprType;
                        attributeSymbol.target = member;
                        attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
                        if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
                            explicitlySpecifyChildrenAttribute = true;
                        }
                    }
                    else {
                        ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */);
                        if (attributesTable.size > 0) {
                            spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */);
                            attributesTable = ts.createSymbolTable();
                        }
                        var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
                        if (isTypeAny(exprType)) {
                            hasSpreadAnyType = true;
                        }
                        if (isValidSpreadType(exprType)) {
                            spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */);
                        }
                        else {
                            typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
                        }
                    }
                }
                if (!hasSpreadAnyType) {
                    if (attributesTable.size > 0) {
                        spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */);
                    }
                }
                // Handle children attribute
                var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined;
                // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
                if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
                    var childrenTypes = checkJsxChildren(parent, checkMode);
                    if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
                        // Error if there is a attribute named "children" explicitly specified and children element.
                        // This is because children element will overwrite the value from attributes.
                        // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
                        if (explicitlySpecifyChildrenAttribute) {
                            error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
                        }
                        // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process
                        var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
                        childrenPropSymbol.type = childrenTypes.length === 1 ?
                            childrenTypes[0] :
                            createArrayType(getUnionType(childrenTypes));
                        var childPropMap = ts.createSymbolTable();
                        childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
                        spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */);
                    }
                }
                if (hasSpreadAnyType) {
                    return anyType;
                }
                if (typeToIntersect && spread !== emptyObjectType) {
                    return getIntersectionType([typeToIntersect, spread]);
                }
                return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread);
                /**
                 * Create anonymous type from given attributes symbol table.
                 * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
                 * @param attributesTable a symbol table of attributes property
                 */
                function createJsxAttributesType() {
                    var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
                    result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */);
                    result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */;
                    return result;
                }
            }
            function checkJsxChildren(node, checkMode) {
                var childrenTypes = [];
                for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
                    var child = _a[_i];
                    // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
                    // because then type of children property will have constituent of string type.
                    if (child.kind === 10 /* JsxText */) {
                        if (!child.containsOnlyWhiteSpaces) {
                            childrenTypes.push(stringType);
                        }
                    }
                    else {
                        childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
                    }
                }
                return childrenTypes;
            }
            /**
             * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
             * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
             * @param node a JSXAttributes to be resolved of its type
             */
            function checkJsxAttributes(node, checkMode) {
                return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
            }
            function getJsxType(name, location) {
                var namespace = getJsxNamespaceAt(location);
                var exports = namespace && getExportsOfSymbol(namespace);
                var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */);
                return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
            }
            /**
             * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
             * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
             * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
             * May also return unknownSymbol if both of these lookups fail.
             */
            function getIntrinsicTagSymbol(node) {
                var links = getNodeLinks(node);
                if (!links.resolvedSymbol) {
                    var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
                    if (intrinsicElementsType !== errorType) {
                        // Property case
                        if (!ts.isIdentifier(node.tagName))
                            return ts.Debug.fail();
                        var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
                        if (intrinsicProp) {
                            links.jsxFlags |= 1 /* IntrinsicNamedElement */;
                            return links.resolvedSymbol = intrinsicProp;
                        }
                        // Intrinsic string indexer case
                        var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
                        if (indexSignatureType) {
                            links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
                            return links.resolvedSymbol = intrinsicElementsType.symbol;
                        }
                        // Wasn't found
                        error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
                        return links.resolvedSymbol = unknownSymbol;
                    }
                    else {
                        if (noImplicitAny) {
                            error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
                        }
                        return links.resolvedSymbol = unknownSymbol;
                    }
                }
                return links.resolvedSymbol;
            }
            function instantiateJsxSignatures(node, signatures) {
                var instantiatedSignatures = [];
                var candidateForTypeArgumentError;
                var hasTypeArgumentError = !!node.typeArguments;
                for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
                    var signature = signatures_3[_i];
                    if (signature.typeParameters) {
                        var isJavascript = ts.isInJSFile(node);
                        var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false);
                        if (typeArgumentInstantiated) {
                            hasTypeArgumentError = false;
                            instantiatedSignatures.push(typeArgumentInstantiated);
                        }
                        else {
                            if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) {
                                candidateForTypeArgumentError = signature;
                            }
                            var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */);
                            var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext);
                            instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript));
                        }
                    }
                    else {
                        instantiatedSignatures.push(signature);
                    }
                }
                if (node.typeArguments && hasTypeArgumentError) {
                    if (candidateForTypeArgumentError) {
                        checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true);
                    }
                    // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine
                    else if (node.typeArguments.length !== 0) {
                        diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments));
                    }
                }
                return instantiatedSignatures;
            }
            function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) {
                if (reportErrors === void 0) {
                    reportErrors = false;
                }
                if (!node.typeArguments) {
                    return;
                }
                if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) {
                    return;
                }
                var args = checkTypeArguments(signature, node.typeArguments, reportErrors);
                if (!args) {
                    return;
                }
                return getSignatureInstantiation(signature, args, isJavascript);
            }
            function getJsxNamespaceAt(location) {
                var links = location && getNodeLinks(location);
                if (links && links.jsxNamespace) {
                    return links.jsxNamespace;
                }
                if (!links || links.jsxNamespace !== false) {
                    var namespaceName = getJsxNamespace(location);
                    var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
                    if (resolvedNamespace) {
                        var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */);
                        if (candidate) {
                            if (links) {
                                links.jsxNamespace = candidate;
                            }
                            return candidate;
                        }
                        if (links) {
                            links.jsxNamespace = false;
                        }
                    }
                }
                // JSX global fallback
                return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
            }
            /**
             * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
             * Get a single property from that container if existed. Report an error if there are more than one property.
             *
             * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
             *          if other string is given or the container doesn't exist, return undefined.
             */
            function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
                // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
                var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */);
                // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
                var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
                // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
                var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
                if (propertiesOfJsxElementAttribPropInterface) {
                    // Element Attributes has zero properties, so the element attributes type will be the class instance type
                    if (propertiesOfJsxElementAttribPropInterface.length === 0) {
                        return "";
                    }
                    // Element Attributes has one property, so the element attributes type will be the type of the corresponding
                    // property of the class instance type
                    else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
                        return propertiesOfJsxElementAttribPropInterface[0].escapedName;
                    }
                    else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
                        // More than one property on ElementAttributesProperty is an error
                        error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
                    }
                }
                return undefined;
            }
            function getJsxLibraryManagedAttributes(jsxNamespace) {
                // JSX.LibraryManagedAttributes [symbol]
                return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */);
            }
            /// e.g. "props" for React.d.ts,
            /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
            ///     non-intrinsic elements' attributes type is 'any'),
            /// or '' if it has 0 properties (which means every
            ///     non-intrinsic elements' attributes type is the element instance type)
            function getJsxElementPropertiesName(jsxNamespace) {
                return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
            }
            function getJsxElementChildrenPropertyName(jsxNamespace) {
                return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
            }
            function getApparentTypeOfJsxPropsType(propsType) {
                if (!propsType) {
                    return undefined;
                }
                if (propsType.flags & 524288 /* Intersection */) {
                    var propsApparentType = [];
                    for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) {
                        var t = _a[_i];
                        propsApparentType.push(getApparentType(t));
                    }
                    return getIntersectionType(propsApparentType);
                }
                return getApparentType(propsType);
            }
            /**
             * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component.
             * Return only attributes type of successfully resolved call signature.
             * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component)
             * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers.
             * @param openingLikeElement a JSX opening-like element to find attributes type
             * @param elementType a type of the opening-like element. This elementType can't be an union type
             * @param elemInstanceType an element instance type (the result of newing or invoking this tag)
             * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global
             */
            function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
                ts.Debug.assert(!(elementType.flags & 262144 /* Union */));
                if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
                    var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
                    if (jsxStatelessElementType) {
                        // We don't call getResolvedSignature here because we have already resolve the type of JSX Element.
                        var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false);
                        if (callSignature !== unknownSignature) {
                            var callReturnType = callSignature && getReturnTypeOfSignature(callSignature);
                            var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
                            paramType = getApparentTypeOfJsxPropsType(paramType);
                            if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
                                // Intersect in JSX.IntrinsicAttributes if it exists
                                var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
                                if (intrinsicAttributes !== errorType) {
                                    paramType = intersectTypes(intrinsicAttributes, paramType);
                                }
                                return paramType;
                            }
                        }
                    }
                }
                return undefined;
            }
            /**
             * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component.
             * Return all attributes type of resolved call signature including candidate signatures.
             * This function assumes that the caller handled other possible element type of the JSX element.
             * This function is a behavior used by language service when looking up completion in JSX element.
             * @param openingLikeElement a JSX opening-like element to find attributes type
             * @param elementType a type of the opening-like element. This elementType can't be an union type
             * @param elemInstanceType an element instance type (the result of newing or invoking this tag)
             * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global
             */
            function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
                ts.Debug.assert(!(elementType.flags & 262144 /* Union */));
                if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
                    // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type
                    var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement);
                    if (jsxStatelessElementType) {
                        // We don't call getResolvedSignature because here we have already resolve the type of JSX Element.
                        var candidatesOutArray = [];
                        getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false);
                        var result = void 0;
                        var allMatchingAttributesType = void 0;
                        for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) {
                            var candidate = candidatesOutArray_1[_i];
                            var callReturnType = getReturnTypeOfSignature(candidate);
                            // TODO: GH#18217: callReturnType should always be defined...
                            var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0]));
                            paramType = getApparentTypeOfJsxPropsType(paramType);
                            if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
                                var shouldBeCandidate = true;
                                for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) {
                                    var attribute = _b[_a];
                                    if (ts.isJsxAttribute(attribute) &&
                                        isUnhyphenatedJsxName(attribute.name.escapedText) &&
                                        !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217
                                        shouldBeCandidate = false;
                                        break;
                                    }
                                }
                                if (shouldBeCandidate) {
                                    result = intersectTypes(result, paramType);
                                }
                                allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType);
                            }
                        }
                        // If we can't find any matching, just return everything.
                        if (!result) {
                            result = allMatchingAttributesType;
                        }
                        // Intersect in JSX.IntrinsicAttributes if it exists
                        var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement);
                        if (intrinsicAttributes !== errorType) {
                            result = intersectTypes(intrinsicAttributes, result);
                        }
                        return result;
                    }
                }
                return undefined;
            }
            function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) {
                var links = getNodeLinks(openingLikeElement);
                if (!links.resolvedSignatures) {
                    links.resolvedSignatures = ts.createMap();
                }
                var cacheKey = "" + getTypeId(elementType);
                if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) {
                    return;
                }
                else if (links.resolvedSignatures.get(cacheKey)) {
                    return links.resolvedSignatures.get(cacheKey);
                }
                links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray);
                // Resolve the signatures, preferring constructor
                var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
                if (signatures.length === 0) {
                    // No construct signatures, try call signatures
                    signatures = getSignaturesOfType(elementType, 0 /* Call */);
                    if (signatures.length === 0) {
                        // We found no signatures at all, which is an error
                        if (reportErrors) {
                            error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName));
                        }
                        return;
                    }
                }
                // Instantiate in context of source type
                var results = instantiateJsxSignatures(openingLikeElement, signatures);
                links.resolvedSignatures.set(cacheKey, results);
                return results;
            }
            /**
             * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType.
             * For instance:
             *      declare function Foo(attr: { p1: string}): JSX.Element;
             *      <Foo p1={10} />;  // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }"
             *
             * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element..
             * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component
             *
             * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement
             * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature
             * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present
             * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname.
             * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts)
             * @return attributes type if able to resolve the type of node
             *         anyType if there is no type ElementAttributesProperty or there is an error
             *         emptyObjectType if there is no "prop" in the element instance type
             */
            function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) {
                if (elementType.flags & 262144 /* Union */) {
                    var types = elementType.types;
                    return getUnionType(types.map(function (type) {
                        return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType);
                    }), 2 /* Subtype */);
                }
                // Shortcircuit any
                if (isTypeAny(elementType)) {
                    return elementType;
                }
                // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type
                else if (elementType.flags & 4 /* String */) {
                    return anyType;
                }
                else if (elementType.flags & 64 /* StringLiteral */) {
                    // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type
                    // For example:
                    //      var CustomTag: "h1" = "h1";
                    //      <CustomTag> Hello World </CustomTag>
                    var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement);
                    if (intrinsicElementsType !== errorType) {
                        var stringLiteralTypeName = elementType.value;
                        var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
                        if (intrinsicProp) {
                            return getTypeOfSymbol(intrinsicProp);
                        }
                        var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
                        if (indexSignatureType) {
                            return indexSignatureType;
                        }
                        error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements);
                    }
                    // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
                    return anyType;
                }
                // Get the element instance type (the result of newing or invoking this tag)
                var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true);
                if (!ts.length(instantiatedSignatures)) {
                    return errorType;
                }
                var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */);
                // If we should include all stateless attributes type, then get all attributes type from all stateless function signature.
                // Otherwise get only attributes type from the signature picked by choose-overload logic.
                var statelessAttributesType = shouldIncludeAllStatelessAttributesType ?
                    tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) :
                    defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType);
                if (statelessAttributesType) {
                    return statelessAttributesType;
                }
                // Issue an error if this return type isn't assignable to JSX.ElementClass
                if (elementClassType) {
                    checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
                }
                var isJs = ts.isInJSFile(openingLikeElement);
                return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); }));
            }
            /**
             * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
             * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
             * @param node an intrinsic JSX opening-like element
             */
            function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
                ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
                var links = getNodeLinks(node);
                if (!links.resolvedJsxElementAttributesType) {
                    var symbol = getIntrinsicTagSymbol(node);
                    if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
                        return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
                    }
                    else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
                        return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type;
                    }
                    else {
                        return links.resolvedJsxElementAttributesType = errorType;
                    }
                }
                return links.resolvedJsxElementAttributesType;
            }
            /**
             * Get attributes type of the given custom opening-like JSX element.
             * This function is intended to be called from a caller that handles intrinsic JSX element already.
             * @param node a custom JSX opening-like element
             * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component
             */
            function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) {
                return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node));
            }
            /**
             * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element.
             * This function is called by language service (see: completions-tryGetGlobalSymbols).
             * @param node a JSX opening-like element to get attributes type for
             */
            function getAllAttributesTypeFromJsxOpeningLikeElement(node) {
                if (isJsxIntrinsicIdentifier(node.tagName)) {
                    return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
                }
                else {
                    // Because in language service, the given JSX opening-like element may be incomplete and therefore,
                    // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads.
                    return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true);
                }
            }
            /**
             * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement.
             * @param node a JSXOpeningLikeElement node
             * @return an attributes type of the given node
             */
            function getAttributesTypeFromJsxOpeningLikeElement(node) {
                if (isJsxIntrinsicIdentifier(node.tagName)) {
                    return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
                }
                else {
                    return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false);
                }
            }
            /**
             * Given a JSX attribute, returns the symbol for the corresponds property
             * of the element attributes type. Will return unknownSymbol for attributes
             * that have no matching element attributes type property.
             */
            function getJsxAttributePropertySymbol(attrib) {
                var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent);
                var prop = getPropertyOfType(attributesType, attrib.name.escapedText);
                return prop || unknownSymbol;
            }
            function getJsxElementClassTypeAt(location) {
                var type = getJsxType(JsxNames.ElementClass, location);
                if (type === errorType)
                    return undefined;
                return type;
            }
            function getJsxElementTypeAt(location) {
                return getJsxType(JsxNames.Element, location);
            }
            function getJsxStatelessElementTypeAt(location) {
                var jsxElementType = getJsxElementTypeAt(location);
                if (jsxElementType) {
                    return getUnionType([jsxElementType, nullType]);
                }
            }
            /**
             * Returns all the properties of the Jsx.IntrinsicElements interface
             */
            function getJsxIntrinsicTagNamesAt(location) {
                var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
                return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
            }
            function checkJsxPreconditions(errorNode) {
                // Preconditions for using JSX
                if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
                    error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
                }
                if (getJsxElementTypeAt(errorNode) === undefined) {
                    if (noImplicitAny) {
                        error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
                    }
                }
            }
            function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) {
                var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
                if (isNodeOpeningLikeElement) {
                    checkGrammarJsxElement(node);
                }
                checkJsxPreconditions(node);
                // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
                // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
                var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
                var reactNamespace = getJsxNamespace(node);
                var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
                var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
                if (reactSym) {
                    // Mark local symbol as referenced here because it might not have been marked
                    // if jsx emit was not react as there wont be error being emitted
                    reactSym.isReferenced = 67108863 /* All */;
                    // If react symbol is alias, mark it as refereced
                    if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
                        markAliasSymbolAsReferenced(reactSym);
                    }
                }
                if (isNodeOpeningLikeElement) {
                    checkJsxAttributesAssignableToTagNameAttributes(node, checkMode);
                }
                else {
                    checkJsxChildren(node.parent);
                }
            }
            /**
             * Check if a property with the given name is known anywhere in the given type. In an object type, a property
             * is considered known if
             * 1. the object type is empty and the check is for assignability, or
             * 2. if the object type has index signatures, or
             * 3. if the property is actually declared in the object type
             *    (this means that 'toString', for example, is not usually a known property).
             * 4. In a union or intersection type,
             *    a property is considered known if it is known in any constituent type.
             * @param targetType a type to search a given name in
             * @param name a property name to search
             * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
             */
            function isKnownProperty(targetType, name, isComparingJsxAttributes) {
                if (targetType.flags & 131072 /* Object */) {
                    var resolved = resolveStructuredTypeMembers(targetType);
                    if (resolved.stringIndexInfo ||
                        resolved.numberIndexInfo && isNumericLiteralName(name) ||
                        getPropertyOfObjectType(targetType, name) ||
                        isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
                        // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
                        return true;
                    }
                }
                else if (targetType.flags & 786432 /* UnionOrIntersection */) {
                    for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
                        var t = _a[_i];
                        if (isKnownProperty(t, name, isComparingJsxAttributes)) {
                            return true;
                        }
                    }
                }
                else if (targetType.flags & 4194304 /* Conditional */) {
                    return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) ||
                        isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes);
                }
                return false;
            }
            /**
             * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes.
             *      Get the attributes type of the opening-like element through resolving the tagName, "target attributes"
             *      Check assignablity between given attributes property, "source attributes", and the "target attributes"
             * @param openingLikeElement an opening-like JSX element to check its JSXAttributes
             */
            function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) {
                // The function involves following steps:
                //      1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType.
                //         During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order)
                //      2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element.
                //      3. Check if the two are assignable to each other
                // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element.
                var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ?
                    getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) :
                    getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false);
                // sourceAttributesType is a type of an attributes properties.
                // i.e <div attr1={10} attr2="string" />
                //     attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes".
                var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode);
                // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties
                var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType);
                // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType.
                // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method.
                if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) {
                    for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) {
                        var attribute = _a[_i];
                        if (!ts.isJsxAttribute(attribute)) {
                            continue;
                        }
                        var attrName = attribute.name;
                        var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText)));
                        if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) {
                            error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType));
                            // We break here so that errors won't be cascading
                            break;
                        }
                    }
                }
                else if (!isSourceAttributeTypeAssignableToTarget) {
                    checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes);
                }
            }
            function checkJsxExpression(node, checkMode) {
                if (node.expression) {
                    var type = checkExpression(node.expression, checkMode);
                    if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
                        error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
                    }
                    return type;
                }
                else {
                    return errorType;
                }
            }
            function getDeclarationNodeFlagsFromSymbol(s) {
                return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
            }
            /**
             * Return whether this symbol is a member of a prototype somewhere
             * Note that this is not tracked well within the compiler, so the answer may be incorrect.
             */
            function isPrototypeProperty(symbol) {
                if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
                    return true;
                }
                if (ts.isInJSFile(symbol.valueDeclaration)) {
                    var parent = symbol.valueDeclaration.parent;
                    return parent && ts.isBinaryExpression(parent) &&
                        ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
                }
            }
            /**
             * Check whether the requested property access is valid.
             * Returns true if node is a valid property access, and false otherwise.
             * @param node The node to be checked.
             * @param isSuper True if the access is from `super.`.
             * @param type The type of the object whose property is being accessed. (Not the type of the property.)
             * @param prop The symbol for the property being accessed.
             */
            function checkPropertyAccessibility(node, isSuper, type, prop) {
                var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
                var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name;
                if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) {
                    // Synthetic property with private constituent property
                    error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type));
                    return false;
                }
                if (isSuper) {
                    // TS 1.0 spec (April 2014): 4.8.2
                    // - In a constructor, instance member function, instance member accessor, or
                    //   instance member variable initializer where this references a derived class instance,
                    //   a super property access is permitted and must specify a public instance member function of the base class.
                    // - In a static member function or static member accessor
                    //   where this references the constructor function object of a derived class,
                    //   a super property access is permitted and must specify a public static member function of the base class.
                    if (languageVersion < 2 /* ES2015 */) {
                        if (symbolHasNonMethodDeclaration(prop)) {
                            error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
                            return false;
                        }
                    }
                    if (flags & 128 /* Abstract */) {
                        // A method cannot be accessed in a super property access if the method is abstract.
                        // This error could mask a private property access error. But, a member
                        // cannot simultaneously be private and abstract, so this will trigger an
                        // additional error elsewhere.
                        error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
                        return false;
                    }
                }
                // Referencing abstract properties within their own constructors is not allowed
                if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
                    var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
                    if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
                        error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217
                        return false;
                    }
                }
                // Public properties are otherwise accessible.
                if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
                    return true;
                }
                // Property is known to be private or protected at this point
                // Private property is accessible if the property is within the declaring class
                if (flags & 8 /* Private */) {
                    var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
                    if (!isNodeWithinClass(node, declaringClassDeclaration)) {
                        error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
                        return false;
                    }
                    return true;
                }
                // Property is known to be protected at this point
                // All protected properties of a supertype are accessible in a super access
                if (isSuper) {
                    return true;
                }
                // Find the first enclosing class that has the declaring classes of the protected constituents
                // of the property as base classes
                var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
                    var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
                    return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
                });
                // A protected property is accessible if the property is within the declaring class or classes derived from it
                if (!enclosingClass) {
                    // allow PropertyAccessibility if context is in function with this parameter
                    // static member access is disallow
                    var thisParameter = void 0;
                    if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
                        error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
                        return false;
                    }
                    var thisType = getTypeFromTypeNode(thisParameter.type);
                    enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType);
                }
                // No further restrictions for static properties
                if (flags & 32 /* Static */) {
                    return true;
                }
                if (type.flags & 65536 /* TypeParameter */) {
                    // get the original type -- represented as the type constraint of the 'this' type
                    type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
                }
                if (!type || !hasBaseType(type, enclosingClass)) {
                    error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
                    return false;
                }
                return true;
            }
            function getThisParameterFromNodeContext(node) {
                var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
                return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
            }
            function symbolHasNonMethodDeclaration(symbol) {
                return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
            }
            function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) {
                return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic);
            }
            function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) {
                if (type.flags & 2 /* Unknown */) {
                    error(node, ts.Diagnostics.Object_is_of_type_unknown);
                    return errorType;
                }
                var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */;
                if (kind) {
                    error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ?
                        (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) :
                        (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) :
                        (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null));
                    var t = getNonNullableType(type);
                    return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t;
                }
                return type;
            }
            function checkPropertyAccessExpression(node) {
                return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name);
            }
            function checkQualifiedName(node) {
                return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right);
            }
            function checkPropertyAccessExpressionOrQualifiedName(node, left, right) {
                var propType;
                var leftType = checkNonNullExpression(left);
                var parentSymbol = getNodeLinks(left).resolvedSymbol;
                var apparentType = getApparentType(getWidenedType(leftType));
                if (isTypeAny(apparentType) || apparentType === silentNeverType) {
                    if (ts.isIdentifier(left) && parentSymbol) {
                        markAliasReferenced(parentSymbol, node);
                    }
                    return apparentType;
                }
                var assignmentKind = ts.getAssignmentTargetKind(node);
                var prop = getPropertyOfType(apparentType, right.escapedText);
                if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
                    markAliasReferenced(parentSymbol, node);
                }
                if (!prop) {
                    var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */);
                    if (!(indexInfo && indexInfo.type)) {
                        if (isJSLiteralType(leftType)) {
                            return anyType;
                        }
                        if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
                            reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
                        }
                        return errorType;
                    }
                    if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
                        error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
                    }
                    propType = indexInfo.type;
                }
                else {
                    checkPropertyNotUsedBeforeDeclaration(prop, node, right);
                    markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */);
                    getNodeLinks(node).resolvedSymbol = prop;
                    checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop);
                    if (assignmentKind) {
                        if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) {
                            error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right));
                            return errorType;
                        }
                    }
                    propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
                }
                // Only compute control flow type if this is a property access expression that isn't an
                // assignment target, and the referenced property was declared as a variable, property,
                // accessor, or optional method.
                if (node.kind !== 187 /* PropertyAccessExpression */ ||
                    assignmentKind === 1 /* Definite */ ||
                    prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) {
                    return propType;
                }
                // If strict null checks and strict property initialization checks are enabled, if we have
                // a this.xxx property access, if the property is an instance property without an initializer,
                // and if we are in a constructor of the same class as the property declaration, assume that
                // the property is uninitialized at the top of the control flow.
                var assumeUninitialized = false;
                if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) {
                    var declaration = prop && prop.valueDeclaration;
                    if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
                        var flowContainer = getControlFlowContainer(node);
                        if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) {
                            assumeUninitialized = true;
                        }
                    }
                }
                else if (strictNullChecks && prop && prop.valueDeclaration &&
                    ts.isPropertyAccessExpression(prop.valueDeclaration) &&
                    ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
                    getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
                    assumeUninitialized = true;
                }
                var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
                if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) {
                    error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
                    // Return the declared type to reduce follow-on errors
                    return propType;
                }
                return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
            }
            function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
                var valueDeclaration = prop.valueDeclaration;
                if (!valueDeclaration) {
                    return;
                }
                var diagnosticMessage;
                var declarationName = ts.idText(right);
                if (isInPropertyInitializer(node) &&
                    !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
                    && !isPropertyDeclaredInAncestorClass(prop)) {
                    diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
                }
                else if (valueDeclaration.kind === 238 /* ClassDeclaration */ &&
                    node.parent.kind !== 162 /* TypeReference */ &&
                    !(valueDeclaration.flags & 4194304 /* Ambient */) &&
                    !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
                    diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
                }
                if (diagnosticMessage) {
                    addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
                }
            }
            function isInPropertyInitializer(node) {
                return !!ts.findAncestor(node, function (node) {
                    switch (node.kind) {
                        case 152 /* PropertyDeclaration */:
                            return true;
                        case 273 /* PropertyAssignment */:
                            // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
                            return false;
                        default:
                            return ts.isExpressionNode(node) ? false : "quit";
                    }
                });
            }
            /**
             * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
             * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
             */
            function isPropertyDeclaredInAncestorClass(prop) {
                if (!(prop.parent.flags & 32 /* Class */)) {
                    return false;
                }
                var classType = getTypeOfSymbol(prop.parent);
                while (true) {
                    classType = classType.symbol && getSuperClass(classType);
                    if (!classType) {
                        return false;
                    }
                    var superProperty = getPropertyOfType(classType, prop.escapedName);
                    if (superProperty && superProperty.valueDeclaration) {
                        return true;
                    }
                }
            }
            function getSuperClass(classType) {
                var x = getBaseTypes(classType);
                if (x.length === 0) {
                    return undefined;
                }
                return getIntersectionType(x);
            }
            function reportNonexistentProperty(propNode, containingType) {
                var errorInfo;
                var relatedInfo;
                if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) {
                    for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
                        var subtype = _a[_i];
                        if (!getPropertyOfType(subtype, propNode.escapedText)) {
                            errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
                            break;
                        }
                    }
                }
                if (typeHasStaticProperty(propNode.escapedText, containingType)) {
                    errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
                }
                else {
                    var promisedType = getPromisedTypeOfPromise(containingType);
                    if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
                        errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType));
                    }
                    else {
                        var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
                        if (suggestion !== undefined) {
                            var suggestedName = ts.symbolName(suggestion);
                            errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
                            relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
                        }
                        else {
                            errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
                        }
                    }
                }
                var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
                if (relatedInfo) {
                    addRelatedInfo(resultDiagnostic, relatedInfo);
                }
                diagnostics.add(resultDiagnostic);
            }
            function typeHasStaticProperty(propName, containingType) {
                var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
                return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
            }
            function getSuggestedSymbolForNonexistentProperty(name, containingType) {
                return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */);
            }
            function getSuggestionForNonexistentProperty(name, containingType) {
                var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
                return suggestion && ts.symbolName(suggestion);
            }
            function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
                ts.Debug.assert(outerName !== undefined, "outername should always be defined");
                var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
                    ts.Debug.assertEqual(outerName, name, "name should equal outerName");
                    var symbol = getSymbol(symbols, name, meaning);
                    // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function
                    // So the table *contains* `x` but `x` isn't actually in scope.
                    // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
                    return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
                });
                return result;
            }
            function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
                var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
                return symbolResult && ts.symbolName(symbolResult);
            }
            function getSuggestedSymbolForNonexistentModule(name, targetModule) {
                return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
            }
            function getSuggestionForNonexistentExport(name, targetModule) {
                var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
                return suggestion && ts.symbolName(suggestion);
            }
            /**
             * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough.
             * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
             *
             * If there is a candidate that's the same except for case, return that.
             * If there is a candidate that's within one edit of the name, return that.
             * Otherwise, return the candidate with the smallest Levenshtein distance,
             *    except for candidates:
             *      * With no name
             *      * Whose meaning doesn't match the `meaning` parameter.
             *      * Whose length differs from the target name by more than 0.34 of the length of the name.
             *      * Whose levenshtein distance is more than 0.4 of the length of the name
             *        (0.4 allows 1 substitution/transposition for every 5 characters,
             *         and 1 insertion/deletion at 3 characters)
             */
            function getSpellingSuggestionForName(name, symbols, meaning) {
                return ts.getSpellingSuggestion(name, symbols, getCandidateName);
                function getCandidateName(candidate) {
                    var candidateName = ts.symbolName(candidate);
                    return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined;
                }
            }
            function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
                if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) {
                    return;
                }
                if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) {
                    return;
                }
                if (isThisAccess) {
                    // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
                    var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
                    if (containingMethod && containingMethod.symbol === prop) {
                        return;
                    }
                }
                (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
            }
            function isValidPropertyAccess(node, propertyName) {
                switch (node.kind) {
                    case 187 /* PropertyAccessExpression */:
                        return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
                    case 146 /* QualifiedName */:
                        return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
                    case 181 /* ImportType */:
                        return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
                }
            }
            function isValidPropertyAccessForCompletions(node, type, property) {
                return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type)
                    && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type));
            }
            function isValidMethodAccess(method, actualThisType) {
                var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName);
                var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */);
                ts.Debug.assert(signatures.length !== 0);
                return signatures.some(function (sig) {
                    var signatureThisType = getThisTypeOfSignature(sig);
                    return !signatureThisType || isTypeAssignableTo(actualThisType, getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType));
                });
            }
            function getInstantiatedSignatureThisType(sig, signatureThisType, actualThisType) {
                if (!sig.typeParameters) {
                    return signatureThisType;
                }
                var context = createInferenceContext(sig.typeParameters, sig, 0 /* None */);
                inferTypes(context.inferences, actualThisType, signatureThisType);
                return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context)));
            }
            function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
                if (type === errorType || isTypeAny(type)) {
                    return true;
                }
                var prop = getPropertyOfType(type, propertyName);
                return prop ? checkPropertyAccessibility(node, isSuper, type, prop)
                    // In js files properties of unions are allowed in completion
                    : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
            }
            /**
             * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
             */
            function getForInVariableSymbol(node) {
                var initializer = node.initializer;
                if (initializer.kind === 236 /* VariableDeclarationList */) {
                    var variable = initializer.declarations[0];
                    if (variable && !ts.isBindingPattern(variable.name)) {
                        return getSymbolOfNode(variable);
                    }
                }
                else if (initializer.kind === 71 /* Identifier */) {
                    return getResolvedSymbol(initializer);
                }
                return undefined;
            }
            /**
             * Return true if the given type is considered to have numeric property names.
             */
            function hasNumericPropertyNames(type) {
                return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
            }
            /**
             * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
             * that references a for-in variable for an object with numeric property names.
             */
            function isForInVariableForNumericPropertyNames(expr) {
                var e = ts.skipParentheses(expr);
                if (e.kind === 71 /* Identifier */) {
                    var symbol = getResolvedSymbol(e);
                    if (symbol.flags & 3 /* Variable */) {
                        var child = expr;
                        var node = expr.parent;
                        while (node) {
                            if (node.kind === 224 /* ForInStatement */ &&
                                child === node.statement &&
                                getForInVariableSymbol(node) === symbol &&
                                hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
                                return true;
                            }
                            child = node;
                            node = node.parent;
                        }
                    }
                }
                return false;
            }
            function checkIndexedAccess(node) {
                var objectType = checkNonNullExpression(node.expression);
                var indexExpression = node.argumentExpression;
                if (!indexExpression) {
                    var sourceFile = ts.getSourceFileOfNode(node);
                    if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) {
                        var start = ts.skipTrivia(sourceFile.text, node.expression.end);
                        var end = node.end;
                        grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead);
                    }
                    else {
                        var start = node.end - "]".length;
                        var end = node.end;
                        grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected);
                    }
                    return errorType;
                }
                var indexType = checkExpression(indexExpression);
                if (objectType === errorType || objectType === silentNeverType) {
                    return objectType;
                }
                if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) {
                    error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
                    return errorType;
                }
                if (isTupleType(objectType) && !objectType.target.hasRestElement && ts.isNumericLiteral(indexExpression)) {
                    var index = +indexExpression.text;
                    var maximumIndex = ts.length(objectType.target.typeParameters);
                    if (index >= maximumIndex) {
                        error(indexExpression, ts.Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex);
                    }
                }
                return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node);
            }
            function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
                if (expressionType === errorType) {
                    // There is already an error, so no need to report one.
                    return false;
                }
                if (!ts.isWellKnownSymbolSyntactically(expression)) {
                    return false;
                }
                // Make sure the property type is the primitive symbol type
                if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) {
                    if (reportError) {
                        error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
                    }
                    return false;
                }
                // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
                // global Symbol object
                var leftHandSide = expression.expression;
                var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
                if (!leftHandSideSymbol) {
                    return false;
                }
                var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
                if (!globalESSymbol) {
                    // Already errored when we tried to look up the symbol
                    return false;
                }
                if (leftHandSideSymbol !== globalESSymbol) {
                    if (reportError) {
                        error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
                    }
                    return false;
                }
                return true;
            }
            function callLikeExpressionMayHaveTypeArguments(node) {
                // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947)
                return ts.isCallOrNewExpression(node);
            }
            function resolveUntypedCall(node) {
                if (callLikeExpressionMayHaveTypeArguments(node)) {
                    // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
                    // This gets us diagnostics for the type arguments and marks them as referenced.
                    ts.forEach(node.typeArguments, checkSourceElement);
                }
                if (node.kind === 191 /* TaggedTemplateExpression */) {
                    checkExpression(node.template);
                }
                else if (node.kind !== 150 /* Decorator */) {
                    ts.forEach(node.arguments, function (argument) {
                        checkExpression(argument);
                    });
                }
                return anySignature;
            }
            function resolveErrorCall(node) {
                resolveUntypedCall(node);
                return unknownSignature;
            }
            // Re-order candidate signatures into the result array. Assumes the result array to be empty.
            // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
            // A nit here is that we reorder only signatures that belong to the same symbol,
            // so order how inherited signatures are processed is still preserved.
            // interface A { (x: string): void }
            // interface B extends A { (x: 'foo'): string }
            // const b: B;
            // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
            function reorderCandidates(signatures, result) {
                var lastParent;
                var lastSymbol;
                var cutoffIndex = 0;
                var index;
                var specializedIndex = -1;
                var spliceIndex;
                ts.Debug.assert(!result.length);
                for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
                    var signature = signatures_4[_i];
                    var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
                    var parent = signature.declaration && signature.declaration.parent;
                    if (!lastSymbol || symbol === lastSymbol) {
                        if (lastParent && parent === lastParent) {
                            index = index + 1;
                        }
                        else {
                            lastParent = parent;
                            index = cutoffIndex;
                        }
                    }
                    else {
                        // current declaration belongs to a different symbol
                        // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
                        index = cutoffIndex = result.length;
                        lastParent = parent;
                    }
                    lastSymbol = symbol;
                    // specialized signatures always need to be placed before non-specialized signatures regardless
                    // of the cutoff position; see GH#1133
                    if (signature.hasLiteralTypes) {
                        specializedIndex++;
                        spliceIndex = specializedIndex;
                        // The cutoff index always needs to be greater than or equal to the specialized signature index
                        // in order to prevent non-specialized signatures from being added before a specialized
                        // signature.
                        cutoffIndex++;
                    }
                    else {
                        spliceIndex = index;
                    }
                    result.splice(spliceIndex, 0, signature);
                }
            }
            function isSpreadArgument(arg) {
                return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread);
            }
            function getSpreadArgumentIndex(args) {
                return ts.findIndex(args, isSpreadArgument);
            }
            function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
                if (signatureHelpTrailingComma === void 0) {
                    signatureHelpTrailingComma = false;
                }
                if (ts.isJsxOpeningLikeElement(node)) {
                    // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement".
                    return true;
                }
                var argCount;
                var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
                if (node.kind === 191 /* TaggedTemplateExpression */) {
                    argCount = args.length;
                    if (node.template.kind === 204 /* TemplateExpression */) {
                        // If a tagged template expression lacks a tail literal, the call is incomplete.
                        // Specifically, a template only can end in a TemplateTail or a Missing literal.
                        var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
                        callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
                    }
                    else {
                        // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
                        // then this might actually turn out to be a TemplateHead in the future;
                        // so we consider the call to be incomplete.
                        var templateLiteral = node.template;
                        ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */);
                        callIsIncomplete = !!templateLiteral.isUnterminated;
                    }
                }
                else if (node.kind === 150 /* Decorator */) {
                    argCount = getDecoratorArgumentCount(node, signature);
                }
                else {
                    if (!node.arguments) {
                        // This only happens when we have something of the form: 'new C'
                        ts.Debug.assert(node.kind === 190 /* NewExpression */);
                        return getMinArgumentCount(signature) === 0;
                    }
                    argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
                    // If we are missing the close parenthesis, the call is incomplete.
                    callIsIncomplete = node.arguments.end === node.end;
                    // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
                    var spreadArgIndex = getSpreadArgumentIndex(args);
                    if (spreadArgIndex >= 0) {
                        return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
                    }
                }
                // Too many arguments implies incorrect arity.
                if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) {
                    return false;
                }
                // If the call is incomplete, we should skip the lower bound check.
                var hasEnoughArguments = argCount >= getMinArgumentCount(signature);
                return callIsIncomplete || hasEnoughArguments;
            }
            function hasCorrectTypeArgumentArity(signature, typeArguments) {
                // If the user supplied type arguments, but the number of type arguments does not match
                // the declared number of type parameters, the call has an incorrect arity.
                var numTypeParameters = ts.length(signature.typeParameters);
                var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
                return !typeArguments ||
                    (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
            }
            // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
            function getSingleCallSignature(type) {
                if (type.flags & 131072 /* Object */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 &&
                        resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
                        return resolved.callSignatures[0];
                    }
                }
                return undefined;
            }
            // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
            function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
                var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
                var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
                forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
                    // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
                    inferTypes(context.inferences, source, target);
                });
                if (!contextualMapper) {
                    inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
                }
                return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
            }
            function inferJsxTypeArguments(signature, node, context) {
                // Skip context sensitive pass
                var skipContextParamType = getTypeAtPosition(signature, 0);
                var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper);
                inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType);
                // Standard pass
                var paramType = getTypeAtPosition(signature, 0);
                var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context);
                inferTypes(context.inferences, checkAttrType, paramType);
                return getInferredTypes(context);
            }
            function inferTypeArguments(node, signature, args, excludeArgument, context) {
                // Clear out all the inference results from the last time inferTypeArguments was called on this context
                for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
                    var inference = _a[_i];
                    // As an optimization, we don't have to clear (and later recompute) inferred types
                    // for type parameters that have already been fixed on the previous call to inferTypeArguments.
                    // It would be just as correct to reset all of them. But then we'd be repeating the same work
                    // for the type parameters that were fixed, namely the work done by getInferredType.
                    if (!inference.isFixed) {
                        inference.inferredType = undefined;
                    }
                }
                // If a contextual type is available, infer from that type to the return type of the call expression. For
                // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
                // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
                // return type of 'wrap'.
                if (node.kind !== 150 /* Decorator */) {
                    var contextualType = getContextualType(node);
                    if (contextualType) {
                        // We clone the contextual mapper to avoid disturbing a resolution in progress for an
                        // outer call expression. Effectively we just want a snapshot of whatever has been
                        // inferred for any outer call expression so far.
                        var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
                        // If the contextual type is a generic function type with a single call signature, we
                        // instantiate the type with its own type parameters and type arguments. This ensures that
                        // the type parameters are not erased to type any during type inference such that they can
                        // be inferred as actual types from the contextual type. For example:
                        //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
                        //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
                        // Above, the type of the 'value' parameter is inferred to be 'A'.
                        var contextualSignature = getSingleCallSignature(instantiatedType);
                        var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
                            getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
                            instantiatedType;
                        var inferenceTargetType = getReturnTypeOfSignature(signature);
                        // Inferences made from return types have lower priority than all other inferences.
                        inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
                    }
                }
                var thisType = getThisTypeOfSignature(signature);
                if (thisType) {
                    var thisArgumentNode = getThisArgumentOfCall(node);
                    var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
                    inferTypes(context.inferences, thisArgumentType, thisType);
                }
                var restType = getNonArrayRestType(signature);
                var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
                for (var i = 0; i < argCount; i++) {
                    var arg = args[i];
                    if (arg.kind !== 208 /* OmittedExpression */) {
                        var paramType = getTypeAtPosition(signature, i);
                        // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
                        // context sensitive function expressions as wildcards
                        var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
                        var argType = checkExpressionWithContextualType(arg, paramType, mapper);
                        inferTypes(context.inferences, argType, paramType);
                    }
                }
                if (restType) {
                    var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
                    inferTypes(context.inferences, spreadType, restType);
                }
                return getInferredTypes(context);
            }
            function getArrayifiedType(type) {
                if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) {
                    return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType);
                }
                return type;
            }
            function getSpreadArgumentType(args, index, argCount, restType, context) {
                if (index >= argCount - 1) {
                    var arg = args[argCount - 1];
                    if (isSpreadArgument(arg)) {
                        // We are inferring from a spread expression in the last argument position, i.e. both the parameter
                        // and the argument are ...x forms.
                        return arg.kind === 213 /* SyntheticExpression */ ?
                            createArrayType(arg.type) :
                            getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
                    }
                }
                var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
                var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */);
                var types = [];
                var spreadIndex = -1;
                for (var i = index; i < argCount; i++) {
                    var argType = checkExpressionWithContextualType(args[i], contextualType, context);
                    if (spreadIndex < 0 && isSpreadArgument(args[i])) {
                        spreadIndex = i - index;
                    }
                    types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
                }
                return spreadIndex < 0 ?
                    createTupleType(types) :
                    createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
            }
            function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
                var isJavascript = ts.isInJSFile(signature.declaration);
                var typeParameters = signature.typeParameters;
                var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
                var mapper;
                for (var i = 0; i < typeArgumentNodes.length; i++) {
                    ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
                    var constraint = getConstraintOfTypeParameter(typeParameters[i]);
                    if (constraint) {
                        var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
                        var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
                        if (!mapper) {
                            mapper = createTypeMapper(typeParameters, typeArgumentTypes);
                        }
                        var typeArgument = typeArgumentTypes[i];
                        if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
                            return undefined;
                        }
                    }
                }
                return typeArgumentTypes;
            }
            /**
             * Check if the given signature can possibly be a signature called by the JSX opening-like element.
             * @param node a JSX opening-like element we are trying to figure its call signature
             * @param signature a candidate signature we are trying whether it is a call signature
             * @param relation a relationship to check parameter and argument type
             * @param excludeArgument
             */
            function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) {
                // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true:
                //      1. callIsIncomplete
                //      2. attributes property has same number of properties as the parameter object type.
                //         We can figure that out by resolving attributes property and check number of properties in the resolved type
                // If the call has correct arity, we will then check if the argument type and parameter type is assignable
                var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete
                if (callIsIncomplete) {
                    return true;
                }
                var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
                // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
                // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
                // can be specified by users through attributes property.
                var paramType = getTypeAtPosition(signature, 0);
                var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined);
                var argProperties = getPropertiesOfType(attributesType);
                for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) {
                    var arg = argProperties_1[_i];
                    if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) {
                        return false;
                    }
                }
                return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage);
            }
            function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
                if (ts.isJsxOpeningLikeElement(node)) {
                    return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation);
                }
                var thisType = getThisTypeOfSignature(signature);
                if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) {
                    // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
                    // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
                    // If the expression is a new expression, then the check is skipped.
                    var thisArgumentNode = getThisArgumentOfCall(node);
                    var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
                    var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
                    var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
                    if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) {
                        return false;
                    }
                }
                var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
                var restType = getNonArrayRestType(signature);
                var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
                for (var i = 0; i < argCount; i++) {
                    var arg = args[i];
                    if (arg.kind !== 208 /* OmittedExpression */) {
                        var paramType = getTypeAtPosition(signature, i);
                        var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
                        // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
                        // we obtain the regular type of any object literal arguments because we may not have inferred complete
                        // parameter types yet and therefore excess property checks may yield false positives (see #17041).
                        var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
                        if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
                            return false;
                        }
                    }
                }
                if (restType) {
                    var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
                    var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
                    return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage);
                }
                return true;
            }
            /**
             * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
             */
            function getThisArgumentOfCall(node) {
                if (node.kind === 189 /* CallExpression */) {
                    var callee = ts.skipOuterExpressions(node.expression);
                    if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) {
                        return callee.expression;
                    }
                }
            }
            function createSyntheticExpression(parent, type, isSpread) {
                var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end);
                result.parent = parent;
                result.type = type;
                result.isSpread = isSpread || false;
                return result;
            }
            /**
             * Returns the effective arguments for an expression that works like a function invocation.
             */
            function getEffectiveCallArguments(node) {
                if (node.kind === 191 /* TaggedTemplateExpression */) {
                    var template = node.template;
                    var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
                    if (template.kind === 204 /* TemplateExpression */) {
                        ts.forEach(template.templateSpans, function (span) {
                            args_4.push(span.expression);
                        });
                    }
                    return args_4;
                }
                if (node.kind === 150 /* Decorator */) {
                    return getEffectiveDecoratorArguments(node);
                }
                if (ts.isJsxOpeningLikeElement(node)) {
                    return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray;
                }
                var args = node.arguments || ts.emptyArray;
                var length = args.length;
                if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
                    // We have a spread argument in the last position and no other spread arguments. If the type
                    // of the argument is a tuple type, spread the tuple elements into the argument list. We can
                    // call checkExpressionCached because spread expressions never have a contextual type.
                    var spreadArgument_1 = args[length - 1];
                    var type = checkExpressionCached(spreadArgument_1.expression);
                    if (isTupleType(type)) {
                        var typeArguments = type.typeArguments || ts.emptyArray;
                        var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
                        var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
                        return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
                    }
                }
                return args;
            }
            /**
             * Returns the synthetic argument list for a decorator invocation.
             */
            function getEffectiveDecoratorArguments(node) {
                var parent = node.parent;
                var expr = node.expression;
                switch (parent.kind) {
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                        // For a class decorator, the `target` is the type of the class (e.g. the
                        // "static" or "constructor" side of the class).
                        return [
                            createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
                        ];
                    case 149 /* Parameter */:
                        // A parameter declaration decorator will have three arguments (see
                        // `ParameterDecorator` in core.d.ts).
                        var func = parent.parent;
                        return [
                            createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
                            createSyntheticExpression(expr, anyType),
                            createSyntheticExpression(expr, numberType)
                        ];
                    case 152 /* PropertyDeclaration */:
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        // A method or accessor declaration decorator will have two or three arguments (see
                        // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
                        // for ES3, we will only pass two arguments.
                        var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
                        return [
                            createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
                            createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
                            createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
                        ];
                }
                return ts.Debug.fail();
            }
            /**
             * Returns the argument count for a decorator node that works like a function invocation.
             */
            function getDecoratorArgumentCount(node, signature) {
                switch (node.parent.kind) {
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                        return 1;
                    case 152 /* PropertyDeclaration */:
                        return 2;
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        // For ES3 or decorators with only two parameters we supply only two arguments
                        return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
                    case 149 /* Parameter */:
                        return 3;
                    default:
                        return ts.Debug.fail();
                }
            }
            function getArgumentArityError(node, signatures, args) {
                var min = Number.POSITIVE_INFINITY;
                var max = Number.NEGATIVE_INFINITY;
                var belowArgCount = Number.NEGATIVE_INFINITY;
                var aboveArgCount = Number.POSITIVE_INFINITY;
                var argCount = args.length;
                var closestSignature;
                for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) {
                    var sig = signatures_5[_i];
                    var minCount = getMinArgumentCount(sig);
                    var maxCount = getParameterCount(sig);
                    if (minCount < argCount && minCount > belowArgCount)
                        belowArgCount = minCount;
                    if (argCount < maxCount && maxCount < aboveArgCount)
                        aboveArgCount = maxCount;
                    if (minCount < min) {
                        min = minCount;
                        closestSignature = sig;
                    }
                    max = Math.max(max, maxCount);
                }
                var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
                var paramRange = hasRestParameter ? min :
                    min < max ? min + "-" + max :
                        min;
                var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
                if (argCount <= max && hasSpreadArgument) {
                    argCount--;
                }
                var related;
                if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
                    var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
                    if (paramDecl) {
                        related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
                    }
                }
                if (hasRestParameter || hasSpreadArgument) {
                    var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
                        hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
                            ts.Diagnostics.Expected_0_arguments_but_got_1_or_more;
                    var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
                    return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
                }
                if (min < argCount && argCount < max) {
                    return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
                }
                var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
                return related ? addRelatedInfo(diagnostic, related) : diagnostic;
            }
            function getTypeArgumentArityError(node, signatures, typeArguments) {
                var min = Infinity;
                var max = -Infinity;
                for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
                    var sig = signatures_6[_i];
                    min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters));
                    max = Math.max(max, ts.length(sig.typeParameters));
                }
                var paramCount = min === max ? min : min + "-" + max;
                return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length);
            }
            function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
                var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */;
                var isDecorator = node.kind === 150 /* Decorator */;
                var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
                var typeArguments;
                if (!isDecorator) {
                    typeArguments = node.typeArguments;
                    // We already perform checking on the type arguments on the class declaration itself.
                    if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) {
                        ts.forEach(typeArguments, checkSourceElement);
                    }
                }
                var candidates = candidatesOutArray || [];
                // reorderCandidates fills up the candidates array directly
                reorderCandidates(signatures, candidates);
                if (!candidates.length) {
                    diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
                    return resolveErrorCall(node);
                }
                var args = getEffectiveCallArguments(node);
                // The excludeArgument array contains true for each context sensitive argument (an argument
                // is context sensitive it is susceptible to a one-time permanent contextual typing).
                //
                // The idea is that we will perform type argument inference & assignability checking once
                // without using the susceptible parameters that are functions, and once more for those
                // parameters, contextually typing each as we go along.
                //
                // For a tagged template, then the first argument be 'undefined' if necessary because it
                // represents a TemplateStringsArray.
                //
                // For a decorator, no arguments are susceptible to contextual typing due to the fact
                // decorators are applied to a declaration by the emitter, and not to an expression.
                var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
                var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
                // The following variables are captured and modified by calls to chooseOverload.
                // If overload resolution or type argument inference fails, we want to report the
                // best error possible. The best error is one which says that an argument was not
                // assignable to a parameter. This implies that everything else about the overload
                // was fine. So if there is any overload that is only incorrect because of an
                // argument, we will report an error on that one.
                //
                //     function foo(s: string): void;
                //     function foo(n: number): void; // Report argument error on this overload
                //     function foo(): void;
                //     foo(true);
                //
                // If none of the overloads even made it that far, there are two possibilities.
                // There was a problem with type arguments for some overload, in which case
                // report an error on that. Or none of the overloads even had correct arity,
                // in which case give an arity error.
                //
                //     function foo<T extends string>(x: T): void; // Report type argument error
                //     function foo(): void;
                //     foo<number>(0);
                //
                var candidateForArgumentError;
                var candidateForArgumentArityError;
                var candidateForTypeArgumentError;
                var result;
                // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
                // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
                var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma;
                // Section 4.12.1:
                // if the candidate list contains one or more signatures for which the type of each argument
                // expression is a subtype of each corresponding parameter type, the return type of the first
                // of those signatures becomes the return type of the function call.
                // Otherwise, the return type of the first signature in the candidate list becomes the return
                // type of the function call.
                //
                // Whether the call is an error is determined by assignability of the arguments. The subtype pass
                // is just important for choosing the best signature. So in the case where there is only one
                // signature, the subtype pass is useless. So skipping it is an optimization.
                if (candidates.length > 1) {
                    result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
                }
                if (!result) {
                    result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
                }
                if (result) {
                    return result;
                }
                // No signatures were applicable. Now report errors based on the last applicable signature with
                // no arguments excluded from assignability checks.
                // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
                // skip the checkApplicableSignature check.
                if (candidateForArgumentError) {
                    if (isJsxOpeningOrSelfClosingElement) {
                        // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType".
                        return candidateForArgumentError;
                    }
                    // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
                    // The importance of excludeArgument is to prevent us from typing function expression parameters
                    // in arguments too early. If possible, we'd like to only type them once we know the correct
                    // overload. However, this matters for the case where the call is correct. When the call is
                    // an error, we don't need to exclude any arguments, although it would cause no harm to do so.
                    checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true);
                }
                else if (candidateForArgumentArityError) {
                    diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
                }
                else if (candidateForTypeArgumentError) {
                    checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
                }
                else {
                    var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
                    if (signaturesWithCorrectTypeArgumentArity.length === 0) {
                        diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
                    }
                    else if (!isDecorator) {
                        diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
                    }
                    else if (fallbackError) {
                        diagnostics.add(ts.createDiagnosticForNode(node, fallbackError));
                    }
                }
                return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
                function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
                    if (signatureHelpTrailingComma === void 0) {
                        signatureHelpTrailingComma = false;
                    }
                    candidateForArgumentError = undefined;
                    candidateForArgumentArityError = undefined;
                    candidateForTypeArgumentError = undefined;
                    if (isSingleNonGenericCandidate) {
                        var candidate = candidates[0];
                        if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
                            return undefined;
                        }
                        if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
                            candidateForArgumentError = candidate;
                            return undefined;
                        }
                        return candidate;
                    }
                    for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
                        var candidate = candidates[candidateIndex];
                        if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
                            continue;
                        }
                        var checkCandidate = void 0;
                        var inferenceContext = void 0;
                        if (candidate.typeParameters) {
                            var typeArgumentTypes = void 0;
                            if (typeArguments) {
                                typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
                                if (!typeArgumentTypes) {
                                    candidateForTypeArgumentError = candidate;
                                    continue;
                                }
                            }
                            else {
                                inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
                                typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
                            }
                            checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
                            // If the original signature has a generic rest type, instantiation may produce a
                            // signature with different arity and we need to perform another arity check.
                            if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
                                candidateForArgumentArityError = checkCandidate;
                                continue;
                            }
                        }
                        else {
                            checkCandidate = candidate;
                        }
                        if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
                            candidateForArgumentError = checkCandidate;
                            continue;
                        }
                        if (excludeArgument) {
                            // If one or more context sensitive arguments were excluded, we start including
                            // them now (and keeping do so for any subsequent candidates) and perform a second
                            // round of type inference and applicability checking for this particular candidate.
                            excludeArgument = undefined;
                            if (inferenceContext) {
                                var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
                                checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
                            }
                            if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
                                candidateForArgumentError = checkCandidate;
                                continue;
                            }
                        }
                        candidates[candidateIndex] = checkCandidate;
                        return checkCandidate;
                    }
                    return undefined;
                }
            }
            function getExcludeArgument(args) {
                var excludeArgument;
                // We do not need to call `getEffectiveArgumentCount` here as it only
                // applies when calculating the number of arguments for a decorator.
                for (var i = 0; i < args.length; i++) {
                    if (isContextSensitive(args[i])) {
                        if (!excludeArgument) {
                            excludeArgument = new Array(args.length);
                        }
                        excludeArgument[i] = true;
                    }
                }
                return excludeArgument;
            }
            // No signature was applicable. We have already reported the errors for the invalid signature.
            // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
            function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
                ts.Debug.assert(candidates.length > 0); // Else should not have called this.
                // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
                // Don't do this if there is a `candidatesOutArray`,
                // because then we want the chosen best candidate to be one of the overloads, not a combination.
                return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
                    ? pickLongestCandidateSignature(node, candidates, args)
                    : createUnionOfSignaturesForOverloadFailure(candidates);
            }
            function createUnionOfSignaturesForOverloadFailure(candidates) {
                var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
                var thisParameter;
                if (thisParameters.length) {
                    thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
                }
                var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
                var parameters = [];
                var _loop_6 = function (i) {
                    var symbols = ts.mapDefined(candidates, function (_a) {
                        var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter;
                        return hasRestParameter ?
                            i < parameters.length - 1 ? parameters[i] : ts.last(parameters) :
                            i < parameters.length ? parameters[i] : undefined;
                    });
                    ts.Debug.assert(symbols.length !== 0);
                    parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
                };
                for (var i = 0; i < maxNonRestParam; i++) {
                    _loop_6(i);
                }
                var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; });
                var hasRestParameter = restParameterSymbols.length !== 0;
                if (hasRestParameter) {
                    var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
                    parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
                }
                return createSignature(candidates[0].declaration, 
                /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
                thisParameter, parameters, 
                /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
                /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, 
                /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; }));
            }
            function getNumNonRestParameters(signature) {
                var numParams = signature.parameters.length;
                return signature.hasRestParameter ? numParams - 1 : numParams;
            }
            function createCombinedSymbolFromTypes(sources, types) {
                return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
            }
            function createCombinedSymbolForOverloadFailure(sources, type) {
                // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
                return createSymbolWithType(ts.first(sources), type);
            }
            function pickLongestCandidateSignature(node, candidates, args) {
                // Pick the longest signature. This way we can get a contextual type for cases like:
                //     declare function f(a: { xa: number; xb: number; }, b: number);
                //     f({ |
                // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
                //     declare function f<T>(k: keyof T);
                //     f<Foo>("
                var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
                var candidate = candidates[bestIndex];
                var typeParameters = candidate.typeParameters;
                if (!typeParameters) {
                    return candidate;
                }
                var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
                var instantiated = typeArgumentNodes
                    ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
                    : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
                candidates[bestIndex] = instantiated;
                return instantiated;
            }
            function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
                var typeArguments = typeArgumentNodes.map(getTypeOfNode);
                while (typeArguments.length > typeParameters.length) {
                    typeArguments.pop();
                }
                while (typeArguments.length < typeParameters.length) {
                    typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
                }
                return typeArguments;
            }
            function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
                var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
                var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
                return createSignatureInstantiation(candidate, typeArgumentTypes);
            }
            function getLongestCandidateIndex(candidates, argsCount) {
                var maxParamsIndex = -1;
                var maxParams = -1;
                for (var i = 0; i < candidates.length; i++) {
                    var candidate = candidates[i];
                    var paramCount = getParameterCount(candidate);
                    if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
                        return i;
                    }
                    if (paramCount > maxParams) {
                        maxParams = paramCount;
                        maxParamsIndex = i;
                    }
                }
                return maxParamsIndex;
            }
            function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
                if (node.expression.kind === 97 /* SuperKeyword */) {
                    var superType = checkSuperExpression(node.expression);
                    if (isTypeAny(superType)) {
                        for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
                            var arg = _a[_i];
                            checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
                        }
                        return anySignature;
                    }
                    if (superType !== errorType) {
                        // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
                        // with the type arguments specified in the extends clause.
                        var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
                        if (baseTypeNode) {
                            var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
                            return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
                        }
                    }
                    return resolveUntypedCall(node);
                }
                var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined);
                if (funcType === silentNeverType) {
                    return silentNeverSignature;
                }
                var apparentType = getApparentType(funcType);
                if (apparentType === errorType) {
                    // Another error has already been reported
                    return resolveErrorCall(node);
                }
                // Technically, this signatures list may be incomplete. We are taking the apparent type,
                // but we are not including call signatures that may have been added to the Object or
                // Function interface, since they have none by default. This is a bit of a leap of faith
                // that the user will not add any.
                var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
                var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */);
                // TS 1.0 Spec: 4.12
                // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
                // types are provided for the argument expressions, and the result is always of type Any.
                if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) {
                    // The unknownType indicates that an error already occurred (and was reported).  No
                    // need to report another error in this case.
                    if (funcType !== errorType && node.typeArguments) {
                        error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
                    }
                    return resolveUntypedCall(node);
                }
                // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
                // TypeScript employs overload resolution in typed function calls in order to support functions
                // with multiple call signatures.
                if (!callSignatures.length) {
                    if (constructSignatures.length) {
                        error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
                    }
                    else {
                        var relatedInformation = void 0;
                        if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) {
                            var text = ts.getSourceFileOfNode(node).text;
                            if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
                                relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon);
                            }
                        }
                        invocationError(node, apparentType, 0 /* Call */, relatedInformation);
                    }
                    return resolveErrorCall(node);
                }
                // If the function is explicitly marked with `@class`, then it must be constructed.
                if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
                    error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
                    return resolveErrorCall(node);
                }
                return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
            }
            /**
             * TS 1.0 spec: 4.12
             * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
             * but is a subtype of the Function interface, the call is an untyped function call.
             */
            function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
                // We exclude union types because we may have a union of function types that happen to have no common signatures.
                return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ ||
                    !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
            }
            function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
                if (node.arguments && languageVersion < 1 /* ES5 */) {
                    var spreadIndex = getSpreadArgumentIndex(node.arguments);
                    if (spreadIndex >= 0) {
                        error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
                    }
                }
                var expressionType = checkNonNullExpression(node.expression);
                if (expressionType === silentNeverType) {
                    return silentNeverSignature;
                }
                // If expressionType's apparent type(section 3.8.1) is an object type with one or
                // more construct signatures, the expression is processed in the same manner as a
                // function call, but using the construct signatures as the initial set of candidate
                // signatures for overload resolution. The result type of the function call becomes
                // the result type of the operation.
                expressionType = getApparentType(expressionType);
                if (expressionType === errorType) {
                    // Another error has already been reported
                    return resolveErrorCall(node);
                }
                // TS 1.0 spec: 4.11
                // If expressionType is of type Any, Args can be any argument
                // list and the result of the operation is of type Any.
                if (isTypeAny(expressionType)) {
                    if (node.typeArguments) {
                        error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
                    }
                    return resolveUntypedCall(node);
                }
                // Technically, this signatures list may be incomplete. We are taking the apparent type,
                // but we are not including construct signatures that may have been added to the Object or
                // Function interface, since they have none by default. This is a bit of a leap of faith
                // that the user will not add any.
                var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
                if (constructSignatures.length) {
                    if (!isConstructorAccessible(node, constructSignatures[0])) {
                        return resolveErrorCall(node);
                    }
                    // If the expression is a class of abstract type, then it cannot be instantiated.
                    // Note, only class declarations can be declared abstract.
                    // In the case of a merged class-module or class-interface declaration,
                    // only the class declaration node will have the Abstract flag set.
                    var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
                    if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
                        error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
                        return resolveErrorCall(node);
                    }
                    return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
                }
                // If expressionType's apparent type is an object type with no construct signatures but
                // one or more call signatures, the expression is processed as a function call. A compile-time
                // error occurs if the result of the function call is not Void. The type of the result of the
                // operation is Any. It is an error to have a Void this type.
                var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
                if (callSignatures.length) {
                    var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
                    if (!noImplicitAny) {
                        if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
                            error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
                        }
                        if (getThisTypeOfSignature(signature) === voidType) {
                            error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
                        }
                    }
                    return signature;
                }
                invocationError(node, expressionType, 1 /* Construct */);
                return resolveErrorCall(node);
            }
            function typeHasProtectedAccessibleBase(target, type) {
                var baseTypes = getBaseTypes(type);
                if (!ts.length(baseTypes)) {
                    return false;
                }
                var firstBase = baseTypes[0];
                if (firstBase.flags & 524288 /* Intersection */) {
                    var types = firstBase.types;
                    var mixinCount = ts.countWhere(types, isMixinConstructorType);
                    var i = 0;
                    for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
                        var intersectionMember = _a[_i];
                        i++;
                        // We want to ignore mixin ctors
                        if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) {
                            if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
                                if (intersectionMember.symbol === target) {
                                    return true;
                                }
                                if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
                                    return true;
                                }
                            }
                        }
                    }
                    return false;
                }
                if (firstBase.symbol === target) {
                    return true;
                }
                return typeHasProtectedAccessibleBase(target, firstBase);
            }
            function isConstructorAccessible(node, signature) {
                if (!signature || !signature.declaration) {
                    return true;
                }
                var declaration = signature.declaration;
                var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
                // Public constructor is accessible.
                if (!modifiers) {
                    return true;
                }
                var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
                var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
                // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
                if (!isNodeWithinClass(node, declaringClassDeclaration)) {
                    var containingClass = ts.getContainingClass(node);
                    if (containingClass && modifiers & 16 /* Protected */) {
                        var containingType = getTypeOfNode(containingClass);
                        if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
                            return true;
                        }
                    }
                    if (modifiers & 8 /* Private */) {
                        error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
                    }
                    if (modifiers & 16 /* Protected */) {
                        error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
                    }
                    return false;
                }
                return true;
            }
            function invocationError(node, apparentType, kind, relatedInformation) {
                var diagnostic = error(node, (kind === 0 /* Call */ ?
                    ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures :
                    ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType));
                invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
            }
            function invocationErrorRecovery(apparentType, kind, diagnostic) {
                if (!apparentType.symbol) {
                    return;
                }
                var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
                // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
                //  An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site
                if (importNode && !ts.isImportCall(importNode)) {
                    var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
                    if (!sigs || !sigs.length)
                        return;
                    addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
                }
            }
            function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
                var tagType = checkExpression(node.tag);
                var apparentType = getApparentType(tagType);
                if (apparentType === errorType) {
                    // Another error has already been reported
                    return resolveErrorCall(node);
                }
                var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
                var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */);
                if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) {
                    return resolveUntypedCall(node);
                }
                if (!callSignatures.length) {
                    invocationError(node, apparentType, 0 /* Call */);
                    return resolveErrorCall(node);
                }
                return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
            }
            /**
             * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
             */
            function getDiagnosticHeadMessageForDecoratorResolution(node) {
                switch (node.parent.kind) {
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                        return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
                    case 149 /* Parameter */:
                        return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
                    case 152 /* PropertyDeclaration */:
                        return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
                    default:
                        return ts.Debug.fail();
                }
            }
            /**
             * Resolves a decorator as if it were a call expression.
             */
            function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
                var funcType = checkExpression(node.expression);
                var apparentType = getApparentType(funcType);
                if (apparentType === errorType) {
                    return resolveErrorCall(node);
                }
                var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
                var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */);
                if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) {
                    return resolveUntypedCall(node);
                }
                if (isPotentiallyUncalledDecorator(node, callSignatures)) {
                    var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
                    error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr);
                    return resolveErrorCall(node);
                }
                var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
                if (!callSignatures.length) {
                    var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType));
                    errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage);
                    var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo);
                    diagnostics.add(diag);
                    invocationErrorRecovery(apparentType, 0 /* Call */, diag);
                    return resolveErrorCall(node);
                }
                return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
            }
            /**
             * Sometimes, we have a decorator that could accept zero arguments,
             * but is receiving too many arguments as part of the decorator invocation.
             * In those cases, a user may have meant to *call* the expression before using it as a decorator.
             */
            function isPotentiallyUncalledDecorator(decorator, signatures) {
                return signatures.length && ts.every(signatures, function (signature) {
                    return signature.minArgumentCount === 0 &&
                        !signature.hasRestParameter &&
                        signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
                });
            }
            /**
             * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component.
             * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName
             * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function)
             * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not.
             * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function
             * @param elementType an element type of the opneing-like element by checking opening-like element's tagname.
             * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
             *                           the function will fill it up with appropriate candidate signatures
             */
            function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) {
                ts.Debug.assert(!(elementType.flags & 262144 /* Union */));
                var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */);
                if (callSignatures && callSignatures.length > 0) {
                    return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp);
                }
                return undefined;
            }
            function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
                switch (node.kind) {
                    case 189 /* CallExpression */:
                        return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
                    case 190 /* NewExpression */:
                        return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
                    case 191 /* TaggedTemplateExpression */:
                        return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
                    case 150 /* Decorator */:
                        return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
                    case 260 /* JsxOpeningElement */:
                    case 259 /* JsxSelfClosingElement */:
                        // This code-path is called by language service
                        var exprTypes = checkExpression(node.tagName);
                        return forEachType(exprTypes, function (exprType) {
                            var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp);
                            if (sfcResult && sfcResult !== unknownSignature) {
                                return sfcResult;
                            }
                            var sigs = getInstantiatedJsxSignatures(node, exprType);
                            if (candidatesOutArray && ts.length(sigs)) {
                                candidatesOutArray.push.apply(candidatesOutArray, sigs);
                            }
                            return ts.length(sigs) ? sigs[0] : unknownSignature;
                        }) || unknownSignature;
                }
                throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
            }
            /**
             * Resolve a signature of a given call-like expression.
             * @param node a call-like expression to try resolve a signature for
             * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
             *                           the function will fill it up with appropriate candidate signatures
             * @return a signature of the call-like expression or undefined if one can't be found
             */
            function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
                if (isForSignatureHelp === void 0) {
                    isForSignatureHelp = false;
                }
                var links = getNodeLinks(node);
                // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
                // However, it is possible that either candidatesOutArray was not passed in the first time,
                // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
                // to correctly fill the candidatesOutArray.
                var cached = links.resolvedSignature;
                if (cached && cached !== resolvingSignature && !candidatesOutArray) {
                    return cached;
                }
                links.resolvedSignature = resolvingSignature;
                var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
                // If signature resolution originated in control flow type analysis (for example to compute the
                // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
                // types from the control flow analysis.
                links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
                return result;
            }
            /**
             * Indicates whether a declaration can be treated as a constructor in a JavaScript
             * file.
             */
            function isJSConstructor(node) {
                if (!node || !ts.isInJSFile(node)) {
                    return false;
                }
                var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
                    ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
                        undefined;
                if (func) {
                    // If the node has a @class tag, treat it like a constructor.
                    if (ts.getJSDocClassTag(node))
                        return true;
                    // If the symbol of the node has members, treat it like a constructor.
                    var symbol = getSymbolOfNode(func);
                    return !!symbol && symbol.members !== undefined;
                }
                return false;
            }
            function isJSConstructorType(type) {
                if (type.flags & 131072 /* Object */) {
                    var resolved = resolveStructuredTypeMembers(type);
                    return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration);
                }
                return false;
            }
            function getJSClassType(symbol) {
                var inferred;
                if (isJSConstructor(symbol.valueDeclaration)) {
                    inferred = getInferredClassType(symbol);
                }
                var assigned = getAssignedClassType(symbol);
                var valueType = getTypeOfSymbol(symbol);
                if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) {
                    inferred = getInferredClassType(valueType.symbol);
                }
                return assigned && inferred ?
                    getIntersectionType([inferred, assigned]) :
                    assigned || inferred;
            }
            function getAssignedClassType(symbol) {
                var decl = symbol.valueDeclaration;
                var assignmentSymbol = decl && decl.parent &&
                    (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
                        ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
                        ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
                var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
                var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
                return init ? checkExpression(init) : undefined;
            }
            function getAssignedJSPrototype(node) {
                if (!node.parent) {
                    return false;
                }
                var parent = node.parent;
                while (parent && parent.kind === 187 /* PropertyAccessExpression */) {
                    parent = parent.parent;
                }
                if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) {
                    var right = ts.getInitializerOfBinaryExpression(parent);
                    return ts.isObjectLiteralExpression(right) && right;
                }
            }
            function getInferredClassType(symbol) {
                var links = getSymbolLinks(symbol);
                if (!links.inferredClassType) {
                    links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
                }
                return links.inferredClassType;
            }
            function isInferredClassType(type) {
                return type.symbol
                    && ts.getObjectFlags(type) & 16 /* Anonymous */
                    && getSymbolLinks(type.symbol).inferredClassType === type;
            }
            /**
             * Syntactically and semantically checks a call or new expression.
             * @param node The call/new expression to be checked.
             * @returns On success, the expression's signature's return type. On failure, anyType.
             */
            function checkCallExpression(node) {
                if (!checkGrammarTypeArguments(node, node.typeArguments))
                    checkGrammarArguments(node.arguments);
                var signature = getResolvedSignature(node);
                if (node.expression.kind === 97 /* SuperKeyword */) {
                    return voidType;
                }
                if (node.kind === 190 /* NewExpression */) {
                    var declaration = signature.declaration;
                    if (declaration &&
                        declaration.kind !== 155 /* Constructor */ &&
                        declaration.kind !== 159 /* ConstructSignature */ &&
                        declaration.kind !== 164 /* ConstructorType */ &&
                        !ts.isJSDocConstructSignature(declaration)) {
                        // When resolved signature is a call signature (and not a construct signature) the result type is any, unless
                        // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations
                        // in a JS file
                        // Note:JS inferred classes might come from a variable declaration instead of a function declaration.
                        // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration.
                        var funcSymbol = checkExpression(node.expression).symbol;
                        if (!funcSymbol && node.expression.kind === 71 /* Identifier */) {
                            funcSymbol = getResolvedSymbol(node.expression);
                        }
                        var type = funcSymbol && getJSClassType(funcSymbol);
                        if (type) {
                            return signature.target ? instantiateType(type, signature.mapper) : type;
                        }
                        if (noImplicitAny) {
                            error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
                        }
                        return anyType;
                    }
                }
                // In JavaScript files, calls to any identifier 'require' are treated as external module imports
                if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
                    return resolveExternalModuleTypeByLiteral(node.arguments[0]);
                }
                var returnType = getReturnTypeOfSignature(signature);
                // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
                // as a fresh unique symbol literal type.
                if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
                    return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
                }
                var jsAssignmentType;
                if (ts.isInJSFile(node)) {
                    var decl = ts.getDeclarationOfExpando(node);
                    if (decl) {
                        var jsSymbol = getSymbolOfNode(decl);
                        if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
                            jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
                            jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
                        }
                    }
                }
                return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType;
            }
            function isSymbolOrSymbolForCall(node) {
                if (!ts.isCallExpression(node))
                    return false;
                var left = node.expression;
                if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
                    left = left.expression;
                }
                if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
                    return false;
                }
                // make sure `Symbol` is the global symbol
                var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
                if (!globalESSymbol) {
                    return false;
                }
                return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
            }
            function checkImportCallExpression(node) {
                // Check grammar of dynamic import
                if (!checkGrammarArguments(node.arguments))
                    checkGrammarImportCallExpression(node);
                if (node.arguments.length === 0) {
                    return createPromiseReturnType(node, anyType);
                }
                var specifier = node.arguments[0];
                var specifierType = checkExpressionCached(specifier);
                // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
                for (var i = 1; i < node.arguments.length; ++i) {
                    checkExpressionCached(node.arguments[i]);
                }
                if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
                    error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
                }
                // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
                var moduleSymbol = resolveExternalModuleName(node, specifier);
                if (moduleSymbol) {
                    var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true);
                    if (esModuleSymbol) {
                        return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
                    }
                }
                return createPromiseReturnType(node, anyType);
            }
            function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
                if (allowSyntheticDefaultImports && type && type !== errorType) {
                    var synthType = type;
                    if (!synthType.syntheticType) {
                        var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
                        var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
                        if (hasSyntheticDefault) {
                            var memberTable = ts.createSymbolTable();
                            var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
                            newSymbol.target = resolveSymbol(symbol);
                            memberTable.set("default" /* Default */, newSymbol);
                            var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
                            var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
                            anonymousSymbol.type = defaultContainingObject;
                            synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
                        }
                        else {
                            synthType.syntheticType = type;
                        }
                    }
                    return synthType.syntheticType;
                }
                return type;
            }
            function isCommonJsRequire(node) {
                if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
                    return false;
                }
                // Make sure require is not a local function
                if (!ts.isIdentifier(node.expression))
                    return ts.Debug.fail();
                var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
                if (resolvedRequire === requireSymbol) {
                    return true;
                }
                // project includes symbol named 'require' - make sure that it is ambient and local non-alias
                if (resolvedRequire.flags & 2097152 /* Alias */) {
                    return false;
                }
                var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
                    ? 237 /* FunctionDeclaration */
                    : resolvedRequire.flags & 3 /* Variable */
                        ? 235 /* VariableDeclaration */
                        : 0 /* Unknown */;
                if (targetDeclarationKind !== 0 /* Unknown */) {
                    var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
                    // function/variable declaration should be ambient
                    return !!decl && !!(decl.flags & 4194304 /* Ambient */);
                }
                return false;
            }
            function checkTaggedTemplateExpression(node) {
                checkGrammarTypeArguments(node, node.typeArguments);
                if (languageVersion < 2 /* ES2015 */) {
                    checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */);
                }
                return getReturnTypeOfSignature(getResolvedSignature(node));
            }
            function checkAssertion(node) {
                return checkAssertionWorker(node, node.type, node.expression);
            }
            function checkAssertionWorker(errNode, type, expression, checkMode) {
                var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
                checkSourceElement(type);
                var targetType = getTypeFromTypeNode(type);
                if (produceDiagnostics && targetType !== errorType) {
                    var widenedType = getWidenedType(exprType);
                    if (!isTypeComparableTo(targetType, widenedType)) {
                        checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first);
                    }
                }
                return targetType;
            }
            function checkNonNullAssertion(node) {
                return getNonNullableType(checkExpression(node.expression));
            }
            function checkMetaProperty(node) {
                checkGrammarMetaProperty(node);
                if (node.keywordToken === 94 /* NewKeyword */) {
                    return checkNewTargetMetaProperty(node);
                }
                if (node.keywordToken === 91 /* ImportKeyword */) {
                    return checkImportMetaProperty(node);
                }
                return ts.Debug.assertNever(node.keywordToken);
            }
            function checkNewTargetMetaProperty(node) {
                var container = ts.getNewTargetContainer(node);
                if (!container) {
                    error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
                    return errorType;
                }
                else if (container.kind === 155 /* Constructor */) {
                    var symbol = getSymbolOfNode(container.parent);
                    return getTypeOfSymbol(symbol);
                }
                else {
                    var symbol = getSymbolOfNode(container);
                    return getTypeOfSymbol(symbol);
                }
            }
            function checkImportMetaProperty(node) {
                if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
                    error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
                }
                var file = ts.getSourceFileOfNode(node);
                ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
                ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
                return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
            }
            function getTypeOfParameter(symbol) {
                var type = getTypeOfSymbol(symbol);
                if (strictNullChecks) {
                    var declaration = symbol.valueDeclaration;
                    if (declaration && ts.hasInitializer(declaration)) {
                        return getOptionalType(type);
                    }
                }
                return type;
            }
            function getParameterNameAtPosition(signature, pos) {
                var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
                if (pos < paramCount) {
                    return signature.parameters[pos].escapedName;
                }
                var restParameter = signature.parameters[paramCount] || unknownSymbol;
                var restType = getTypeOfSymbol(restParameter);
                if (isTupleType(restType)) {
                    var associatedNames = restType.target.associatedNames;
                    var index = pos - paramCount;
                    return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
                }
                return restParameter.escapedName;
            }
            function getTypeAtPosition(signature, pos) {
                return tryGetTypeAtPosition(signature, pos) || anyType;
            }
            function tryGetTypeAtPosition(signature, pos) {
                var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
                if (pos < paramCount) {
                    return getTypeOfParameter(signature.parameters[pos]);
                }
                if (signature.hasRestParameter) {
                    var restType = getTypeOfSymbol(signature.parameters[paramCount]);
                    if (isTupleType(restType)) {
                        if (pos - paramCount < getLengthOfTupleType(restType)) {
                            return restType.typeArguments[pos - paramCount];
                        }
                        return getRestTypeOfTupleType(restType);
                    }
                    return getIndexTypeOfType(restType, 1 /* Number */);
                }
                return undefined;
            }
            function getRestTypeAtPosition(source, pos) {
                var paramCount = getParameterCount(source);
                var restType = getEffectiveRestType(source);
                if (restType && pos === paramCount - 1) {
                    return restType;
                }
                var start = restType ? Math.min(pos, paramCount - 1) : pos;
                var types = [];
                var names = [];
                for (var i = start; i < paramCount; i++) {
                    types.push(getTypeAtPosition(source, i));
                    names.push(getParameterNameAtPosition(source, i));
                }
                var minArgumentCount = getMinArgumentCount(source);
                var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
                return createTupleType(types, minLength, !!restType, names);
            }
            function getParameterCount(signature) {
                var length = signature.parameters.length;
                if (signature.hasRestParameter) {
                    var restType = getTypeOfSymbol(signature.parameters[length - 1]);
                    if (isTupleType(restType)) {
                        return length + (restType.typeArguments || ts.emptyArray).length - 1;
                    }
                }
                return length;
            }
            function getMinArgumentCount(signature) {
                if (signature.hasRestParameter) {
                    var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
                    if (isTupleType(restType)) {
                        var minLength = restType.target.minLength;
                        if (minLength > 0) {
                            return signature.parameters.length - 1 + minLength;
                        }
                    }
                }
                return signature.minArgumentCount;
            }
            function hasEffectiveRestParameter(signature) {
                if (signature.hasRestParameter) {
                    var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
                    return !isTupleType(restType) || restType.target.hasRestElement;
                }
                return false;
            }
            function getEffectiveRestType(signature) {
                if (signature.hasRestParameter) {
                    var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
                    return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
                }
                return undefined;
            }
            function getNonArrayRestType(signature) {
                var restType = getEffectiveRestType(signature);
                return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined;
            }
            function getTypeOfFirstParameterOfSignature(signature) {
                return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
            }
            function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
                return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
            }
            function inferFromAnnotatedParameters(signature, context, mapper) {
                var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
                for (var i = 0; i < len; i++) {
                    var declaration = signature.parameters[i].valueDeclaration;
                    if (declaration.type) {
                        var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
                        if (typeNode) {
                            inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
                        }
                    }
                }
            }
            function assignContextualParameterTypes(signature, context) {
                signature.typeParameters = context.typeParameters;
                if (context.thisParameter) {
                    var parameter = signature.thisParameter;
                    if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
                        if (!parameter) {
                            signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
                        }
                        assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
                    }
                }
                var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
                for (var i = 0; i < len; i++) {
                    var parameter = signature.parameters[i];
                    if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
                        var contextualParameterType = getTypeAtPosition(context, i);
                        assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType);
                    }
                }
                if (signature.hasRestParameter) {
                    // parameter might be a transient symbol generated by use of `arguments` in the function body.
                    var parameter = ts.last(signature.parameters);
                    if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
                        var contextualParameterType = getRestTypeAtPosition(context, len);
                        assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType);
                    }
                }
            }
            // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
            // the destructured type into the contained binding elements.
            function assignBindingElementTypes(pattern) {
                for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
                    var element = _a[_i];
                    if (!ts.isOmittedExpression(element)) {
                        if (element.name.kind === 71 /* Identifier */) {
                            getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
                        }
                        else {
                            assignBindingElementTypes(element.name);
                        }
                    }
                }
            }
            function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) {
                var links = getSymbolLinks(parameter);
                if (!links.type) {
                    links.type = contextualType;
                    var decl = parameter.valueDeclaration;
                    if (decl.name.kind !== 71 /* Identifier */) {
                        // if inference didn't come up with anything but {}, fall back to the binding pattern if present.
                        if (links.type === emptyObjectType) {
                            links.type = getTypeFromBindingPattern(decl.name);
                        }
                        assignBindingElementTypes(decl.name);
                    }
                }
            }
            function createPromiseType(promisedType) {
                // creates a `Promise<T>` type where `T` is the promisedType argument
                var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
                if (globalPromiseType !== emptyGenericType) {
                    // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
                    promisedType = getAwaitedType(promisedType) || emptyObjectType;
                    return createTypeReference(globalPromiseType, [promisedType]);
                }
                return emptyObjectType;
            }
            function createPromiseReturnType(func, promisedType) {
                var promiseType = createPromiseType(promisedType);
                if (promiseType === emptyObjectType) {
                    error(func, ts.isImportCall(func) ?
                        ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
                        ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option);
                    return errorType;
                }
                else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
                    error(func, ts.isImportCall(func) ?
                        ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option :
                        ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
                }
                return promiseType;
            }
            function getReturnTypeFromBody(func, checkMode) {
                if (!func.body) {
                    return errorType;
                }
                var functionFlags = ts.getFunctionFlags(func);
                var type;
                if (func.body.kind !== 216 /* Block */) {
                    type = checkExpressionCached(func.body, checkMode);
                    if (functionFlags & 2 /* Async */) {
                        // From within an async function you can return either a non-promise value or a promise. Any
                        // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
                        // return type of the body should be unwrapped to its awaited type, which we will wrap in
                        // the native Promise<T> type later in this function.
                        type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
                    }
                }
                else {
                    var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
                    if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
                        types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types);
                        if (!types || types.length === 0) {
                            var iterableIteratorAny = functionFlags & 2 /* Async */
                                ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function
                                : createIterableIteratorType(anyType); // Generator function
                            if (noImplicitAny) {
                                error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny));
                            }
                            return iterableIteratorAny;
                        }
                    }
                    else {
                        if (!types) {
                            // For an async function, the return type will not be never, but rather a Promise for never.
                            return functionFlags & 2 /* Async */
                                ? createPromiseReturnType(func, neverType) // Async function
                                : neverType; // Normal function
                        }
                        if (types.length === 0) {
                            // For an async function, the return type will not be void, but rather a Promise for void.
                            return functionFlags & 2 /* Async */
                                ? createPromiseReturnType(func, voidType) // Async function
                                : voidType; // Normal function
                        }
                    }
                    // Return a union of the return expression types.
                    type = getUnionType(types, 2 /* Subtype */);
                }
                var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
                if (!contextualSignature) {
                    reportErrorsFromWidening(func, type);
                }
                if (isUnitType(type)) {
                    var contextualType = !contextualSignature ? undefined :
                        contextualSignature === getSignatureFromDeclaration(func) ? type :
                            getReturnTypeOfSignature(contextualSignature);
                    if (contextualType) {
                        switch (functionFlags & 3 /* AsyncGenerator */) {
                            case 3 /* AsyncGenerator */:
                                contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true);
                                break;
                            case 1 /* Generator */:
                                contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false);
                                break;
                            case 2 /* Async */:
                                contextualType = getPromisedTypeOfPromise(contextualType);
                                break;
                        }
                    }
                    type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
                }
                var widenedType = getWidenedType(type);
                switch (functionFlags & 3 /* AsyncGenerator */) {
                    case 3 /* AsyncGenerator */:
                        return createAsyncIterableIteratorType(widenedType);
                    case 1 /* Generator */:
                        return createIterableIteratorType(widenedType);
                    case 2 /* Async */:
                        // From within an async function you can return either a non-promise value or a promise. Any
                        // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
                        // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
                        return createPromiseType(widenedType);
                    default:
                        return widenedType;
                }
            }
            function checkAndAggregateYieldOperandTypes(func, checkMode) {
                var aggregatedTypes = [];
                var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
                ts.forEachYieldExpression(func.body, function (yieldExpression) {
                    ts.pushIfUnique(aggregatedTypes, getYieldedTypeOfYieldExpression(yieldExpression, isAsync, checkMode));
                });
                return aggregatedTypes;
            }
            function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) {
                var errorNode = node.expression || node;
                var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType;
                // A `yield*` expression effectively yields everything that its operand yields
                var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType;
                return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
                    ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
                    : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
            }
            /**
             * Collect the TypeFacts learned from a typeof switch with
             * total clauses `witnesses`, and the active clause ranging
             * from `start` to `end`. Parameter `hasDefault` denotes
             * whether the active clause contains a default clause.
             */
            function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
                var facts = 0 /* None */;
                // When in the default we only collect inequality facts
                // because default is 'in theory' a set of infinite
                // equalities.
                if (hasDefault) {
                    // Value is not equal to any types after the active clause.
                    for (var i = end; i < witnesses.length; i++) {
                        facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */;
                    }
                    // Remove inequalities for types that appear in the
                    // active clause because they appear before other
                    // types collected so far.
                    for (var i = start; i < end; i++) {
                        facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
                    }
                    // Add inequalities for types before the active clause unconditionally.
                    for (var i = 0; i < start; i++) {
                        facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */;
                    }
                }
                // When in an active clause without default the set of
                // equalities is finite.
                else {
                    // Add equalities for all types in the active clause.
                    for (var i = start; i < end; i++) {
                        facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */;
                    }
                    // Remove equalities for types that appear before the
                    // active clause.
                    for (var i = 0; i < start; i++) {
                        facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
                    }
                }
                return facts;
            }
            function isExhaustiveSwitchStatement(node) {
                if (!node.possiblyExhaustive) {
                    return false;
                }
                if (node.expression.kind === 197 /* TypeOfExpression */) {
                    var operandType = getTypeOfExpression(node.expression.expression);
                    // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined.
                    var witnesses = getSwitchClauseTypeOfWitnesses(node);
                    // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
                    var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
                    var type_5 = getBaseConstraintOfType(operandType) || operandType;
                    return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */);
                }
                var type = getTypeOfExpression(node.expression);
                if (!isLiteralType(type)) {
                    return false;
                }
                var switchTypes = getSwitchClauseTypes(node);
                if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
                    return false;
                }
                return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
            }
            function functionHasImplicitReturn(func) {
                if (!(func.flags & 128 /* HasImplicitReturn */)) {
                    return false;
                }
                if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) {
                    return false;
                }
                return true;
            }
            /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
            function checkAndAggregateReturnExpressionTypes(func, checkMode) {
                var functionFlags = ts.getFunctionFlags(func);
                var aggregatedTypes = [];
                var hasReturnWithNoExpression = functionHasImplicitReturn(func);
                var hasReturnOfTypeNever = false;
                ts.forEachReturnStatement(func.body, function (returnStatement) {
                    var expr = returnStatement.expression;
                    if (expr) {
                        var type = checkExpressionCached(expr, checkMode);
                        if (functionFlags & 2 /* Async */) {
                            // From within an async function you can return either a non-promise value or a promise. Any
                            // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
                            // return type of the body should be unwrapped to its awaited type, which should be wrapped in
                            // the native Promise<T> type by the caller.
                            type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
                        }
                        if (type.flags & 32768 /* Never */) {
                            hasReturnOfTypeNever = true;
                        }
                        ts.pushIfUnique(aggregatedTypes, type);
                    }
                    else {
                        hasReturnWithNoExpression = true;
                    }
                });
                if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
                    return undefined;
                }
                if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
                    !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
                    // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
                    ts.pushIfUnique(aggregatedTypes, undefinedType);
                }
                return aggregatedTypes;
            }
            function mayReturnNever(func) {
                switch (func.kind) {
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        return true;
                    case 154 /* MethodDeclaration */:
                        return func.parent.kind === 186 /* ObjectLiteralExpression */;
                    default:
                        return false;
                }
            }
            /**
             * TypeScript Specification 1.0 (6.3) - July 2014
             *   An explicitly typed function whose return type isn't the Void type,
             *   the Any type, or a union type containing the Void or Any type as a constituent
             *   must have at least one return statement somewhere in its body.
             *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
             *
             * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
             */
            function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
                if (!produceDiagnostics) {
                    return;
                }
                // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
                if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) {
                    return;
                }
                // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
                // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
                if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) {
                    return;
                }
                var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */;
                if (returnType && returnType.flags & 32768 /* Never */) {
                    error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
                }
                else if (returnType && !hasExplicitReturn) {
                    // minimal check: function has syntactic return type annotation and no explicit return statements in the body
                    // this function does not conform to the specification.
                    // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
                    error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
                }
                else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) {
                    error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
                }
                else if (compilerOptions.noImplicitReturns) {
                    if (!returnType) {
                        // If return type annotation is omitted check if function has any explicit return statements.
                        // If it does not have any - its inferred return type is void - don't do any checks.
                        // Otherwise get inferred return type from function body and report error only if it is not void / anytype
                        if (!hasExplicitReturn) {
                            return;
                        }
                        var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
                        if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
                            return;
                        }
                    }
                    error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
                }
            }
            function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
                ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
                // The identityMapper object is used to indicate that function expressions are wildcards
                if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
                    // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
                    if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
                        var links_1 = getNodeLinks(node);
                        if (links_1.contextFreeType) {
                            return links_1.contextFreeType;
                        }
                        var returnType = getReturnTypeFromBody(node, checkMode);
                        var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
                        var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
                        returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
                        return links_1.contextFreeType = returnOnlyType;
                    }
                    return anyFunctionType;
                }
                // Grammar checking
                var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
                if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) {
                    checkGrammarForGenerator(node);
                }
                var links = getNodeLinks(node);
                var type = getTypeOfSymbol(getMergedSymbol(node.symbol));
                if (isTypeAny(type)) {
                    return type;
                }
                // Check if function expression is contextually typed and assign parameter types if so.
                if (!(links.flags & 1024 /* ContextChecked */)) {
                    var contextualSignature = getContextualSignature(node);
                    // If a type check is started at a function expression that is an argument of a function call, obtaining the
                    // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
                    // already assigned contextual types.
                    if (!(links.flags & 1024 /* ContextChecked */)) {
                        links.flags |= 1024 /* ContextChecked */;
                        if (contextualSignature) {
                            var signature = getSignaturesOfType(type, 0 /* Call */)[0];
                            if (isContextSensitive(node)) {
                                var contextualMapper = getContextualMapper(node);
                                if (checkMode === 2 /* Inferential */) {
                                    inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
                                }
                                var instantiatedContextualSignature = contextualMapper === identityMapper ?
                                    contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
                                assignContextualParameterTypes(signature, instantiatedContextualSignature);
                            }
                            if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
                                var returnType = getReturnTypeFromBody(node, checkMode);
                                if (!signature.resolvedReturnType) {
                                    signature.resolvedReturnType = returnType;
                                }
                            }
                        }
                        checkSignatureDeclaration(node);
                        checkNodeDeferred(node);
                    }
                }
                return type;
            }
            function getReturnOrPromisedType(node, functionFlags) {
                var type = getReturnTypeFromAnnotation(node);
                return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ?
                    getAwaitedType(type) || errorType : type;
            }
            function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
                ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
                var functionFlags = ts.getFunctionFlags(node);
                var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags);
                if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
                    // return is not necessary in the body of generators
                    checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
                }
                if (node.body) {
                    if (!ts.getEffectiveReturnTypeNode(node)) {
                        // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
                        // we need. An example is the noImplicitAny errors resulting from widening the return expression
                        // of a function. Because checking of function expression bodies is deferred, there was never an
                        // appropriate time to do this during the main walk of the file (see the comment at the top of
                        // checkFunctionExpressionBodies). So it must be done now.
                        getReturnTypeOfSignature(getSignatureFromDeclaration(node));
                    }
                    if (node.body.kind === 216 /* Block */) {
                        checkSourceElement(node.body);
                    }
                    else {
                        // From within an async function you can return either a non-promise value or a promise. Any
                        // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
                        // should not be checking assignability of a promise to the return type. Instead, we need to
                        // check assignability of the awaited type of the expression body against the promised type of
                        // its return type annotation.
                        var exprType = checkExpression(node.body);
                        if (returnOrPromisedType) {
                            if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
                                var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
                                checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
                            }
                            else { // Normal function
                                checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
                            }
                        }
                    }
                }
            }
            function checkArithmeticOperandType(operand, type, diagnostic) {
                if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) {
                    error(operand, diagnostic);
                    return false;
                }
                return true;
            }
            function isReadonlySymbol(symbol) {
                // The following symbols are considered read-only:
                // Properties with a 'readonly' modifier
                // Variables declared with 'const'
                // Get accessors without matching set accessors
                // Enum members
                // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
                return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
                    symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
                    symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
                    symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
                    symbol.flags & 8 /* EnumMember */);
            }
            function isReferenceToReadonlyEntity(expr, symbol) {
                if (isReadonlySymbol(symbol)) {
                    // Allow assignments to readonly properties within constructors of the same class declaration.
                    if (symbol.flags & 4 /* Property */ &&
                        (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) &&
                        expr.expression.kind === 99 /* ThisKeyword */) {
                        // Look for if this is the constructor for the class that `symbol` is a property of.
                        var func = ts.getContainingFunction(expr);
                        if (!(func && func.kind === 155 /* Constructor */)) {
                            return true;
                        }
                        // If func.parent is a class and symbol is a (readonly) property of that class, or
                        // if func is a constructor and symbol is a (readonly) parameter property declared in it,
                        // then symbol is writeable here.
                        return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent);
                    }
                    return true;
                }
                return false;
            }
            function isReferenceThroughNamespaceImport(expr) {
                if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) {
                    var node = ts.skipParentheses(expr.expression);
                    if (node.kind === 71 /* Identifier */) {
                        var symbol = getNodeLinks(node).resolvedSymbol;
                        if (symbol.flags & 2097152 /* Alias */) {
                            var declaration = getDeclarationOfAliasSymbol(symbol);
                            return !!declaration && declaration.kind === 249 /* NamespaceImport */;
                        }
                    }
                }
                return false;
            }
            function checkReferenceExpression(expr, invalidReferenceMessage) {
                // References are combinations of identifiers, parentheses, and property accesses.
                var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */);
                if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) {
                    error(expr, invalidReferenceMessage);
                    return false;
                }
                return true;
            }
            function checkDeleteExpression(node) {
                checkExpression(node.expression);
                var expr = ts.skipParentheses(node.expression);
                if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) {
                    error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
                    return booleanType;
                }
                var links = getNodeLinks(expr);
                var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
                if (symbol && isReadonlySymbol(symbol)) {
                    error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
                }
                return booleanType;
            }
            function checkTypeOfExpression(node) {
                checkExpression(node.expression);
                return typeofType;
            }
            function checkVoidExpression(node) {
                checkExpression(node.expression);
                return undefinedWideningType;
            }
            function checkAwaitExpression(node) {
                // Grammar checking
                if (produceDiagnostics) {
                    if (!(node.flags & 16384 /* AwaitContext */)) {
                        grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function);
                    }
                    if (isInParameterInitializerBeforeContainingFunction(node)) {
                        error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
                    }
                }
                var operandType = checkExpression(node.expression);
                return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
            }
            function checkPrefixUnaryExpression(node) {
                var operandType = checkExpression(node.operand);
                if (operandType === silentNeverType) {
                    return silentNeverType;
                }
                if (node.operand.kind === 8 /* NumericLiteral */) {
                    if (node.operator === 38 /* MinusToken */) {
                        return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
                    }
                    else if (node.operator === 37 /* PlusToken */) {
                        return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
                    }
                }
                switch (node.operator) {
                    case 37 /* PlusToken */:
                    case 38 /* MinusToken */:
                    case 52 /* TildeToken */:
                        checkNonNullType(operandType, node.operand);
                        if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) {
                            error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
                        }
                        return numberType;
                    case 51 /* ExclamationToken */:
                        checkTruthinessExpression(node.operand);
                        var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */);
                        return facts === 1048576 /* Truthy */ ? falseType :
                            facts === 2097152 /* Falsy */ ? trueType :
                                booleanType;
                    case 43 /* PlusPlusToken */:
                    case 44 /* MinusMinusToken */:
                        var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type);
                        if (ok) {
                            // run check only if former checks succeeded to avoid reporting cascading errors
                            checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access);
                        }
                        return numberType;
                }
                return errorType;
            }
            function checkPostfixUnaryExpression(node) {
                var operandType = checkExpression(node.operand);
                if (operandType === silentNeverType) {
                    return silentNeverType;
                }
                var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type);
                if (ok) {
                    // run check only if former checks succeeded to avoid reporting cascading errors
                    checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access);
                }
                return numberType;
            }
            // Return true if type might be of the given kind. A union or intersection type might be of a given
            // kind if at least one constituent type is of the given kind.
            function maybeTypeOfKind(type, kind) {
                if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) {
                    return true;
                }
                if (type.flags & 786432 /* UnionOrIntersection */) {
                    var types = type.types;
                    for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
                        var t = types_15[_i];
                        if (maybeTypeOfKind(t, kind)) {
                            return true;
                        }
                    }
                }
                return false;
            }
            function isTypeAssignableToKind(source, kind, strict) {
                if (source.flags & kind) {
                    return true;
                }
                if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) {
                    return false;
                }
                return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
                    !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
                    !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
                    !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) ||
                    !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) ||
                    !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) ||
                    !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
                    !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
                    !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
            }
            function allTypesAssignableToKind(source, kind, strict) {
                return source.flags & 262144 /* Union */ ?
                    ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
                    isTypeAssignableToKind(source, kind, strict);
            }
            function isConstEnumObjectType(type) {
                return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
            }
            function isConstEnumSymbol(symbol) {
                return (symbol.flags & 128 /* ConstEnum */) !== 0;
            }
            function checkInstanceOfExpression(left, right, leftType, rightType) {
                if (leftType === silentNeverType || rightType === silentNeverType) {
                    return silentNeverType;
                }
                // TypeScript 1.0 spec (April 2014): 4.15.4
                // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
                // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
                // The result is always of the Boolean primitive type.
                // NOTE: do not raise error if leftType is unknown as related error was already reported
                if (!isTypeAny(leftType) &&
                    allTypesAssignableToKind(leftType, 32764 /* Primitive */)) {
                    error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
                }
                // NOTE: do not raise error if right is unknown as related error was already reported
                if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
                    error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type);
                }
                return booleanType;
            }
            function checkInExpression(left, right, leftType, rightType) {
                if (leftType === silentNeverType || rightType === silentNeverType) {
                    return silentNeverType;
                }
                leftType = checkNonNullType(leftType, left);
                rightType = checkNonNullType(rightType, right);
                // TypeScript 1.0 spec (April 2014): 4.15.5
                // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
                // and the right operand to be of type Any, an object type, or a type parameter type.
                // The result is always of the Boolean primitive type.
                if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) {
                    error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
                }
                if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) {
                    error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
                }
                return booleanType;
            }
            function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
                var properties = node.properties;
                if (strictNullChecks && properties.length === 0) {
                    return checkNonNullType(sourceType, node);
                }
                for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
                    var p = properties_7[_i];
                    checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
                }
                return sourceType;
            }
            /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
            function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) {
                if (rightIsThis === void 0) {
                    rightIsThis = false;
                }
                if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) {
                    var name = property.name;
                    if (name.kind === 147 /* ComputedPropertyName */) {
                        checkComputedPropertyName(name);
                    }
                    if (isComputedNonLiteralName(name)) {
                        return undefined;
                    }
                    var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis);
                    if (type) {
                        // non-shorthand property assignments should always have initializers
                        return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
                    }
                    else {
                        error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name));
                    }
                }
                else if (property.kind === 275 /* SpreadAssignment */) {
                    if (languageVersion < 6 /* ESNext */) {
                        checkExternalEmitHelpers(property, 4 /* Rest */);
                    }
                    var nonRestNames = [];
                    if (allProperties) {
                        for (var i = 0; i < allProperties.length - 1; i++) {
                            nonRestNames.push(allProperties[i].name);
                        }
                    }
                    var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
                    checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
                    return checkDestructuringAssignment(property.expression, type);
                }
                else {
                    error(property, ts.Diagnostics.Property_assignment_expected);
                }
            }
            function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) {
                if (isTypeAny(objectLiteralType)) {
                    return objectLiteralType;
                }
                var type;
                var text = ts.getTextOfPropertyName(name);
                if (text) { // TODO: GH#26379
                    var prop = getPropertyOfType(objectLiteralType, text);
                    if (prop) {
                        markPropertyAsReferenced(prop, property, rightIsThis);
                        checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
                        type = getTypeOfSymbol(prop);
                    }
                    type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined);
                }
                return type || getIndexTypeOfType(objectLiteralType, 0 /* String */);
            }
            function checkArrayLiteralAssignment(node, sourceType, checkMode) {
                var elements = node.elements;
                if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
                    checkExternalEmitHelpers(node, 512 /* Read */);
                }
                // This elementType will be used if the specific property corresponding to this index is not
                // present (aka the tuple element property). This call also checks that the parentType is in
                // fact an iterable or array (depending on target language).
                var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType;
                for (var i = 0; i < elements.length; i++) {
                    checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
                }
                return sourceType;
            }
            function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
                var elements = node.elements;
                var element = elements[elementIndex];
                if (element.kind !== 208 /* OmittedExpression */) {
                    if (element.kind !== 206 /* SpreadElement */) {
                        var propName = "" + elementIndex;
                        var type = isTypeAny(sourceType) ? sourceType :
                            isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) :
                                elementType;
                        if (type) {
                            return checkDestructuringAssignment(element, type, checkMode);
                        }
                        // We still need to check element expression here because we may need to set appropriate flag on the expression
                        // such as NodeCheckFlags.LexicalThis on "this"expression.
                        checkExpression(element);
                        if (isTupleType(sourceType)) {
                            error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length);
                        }
                        else {
                            error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName);
                        }
                    }
                    else {
                        if (elementIndex < elements.length - 1) {
                            error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
                        }
                        else {
                            var restExpression = element.expression;
                            if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) {
                                error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
                            }
                            else {
                                checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
                                var type = isTupleType(sourceType) ?
                                    getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) :
                                    createArrayType(elementType);
                                return checkDestructuringAssignment(restExpression, type, checkMode);
                            }
                        }
                    }
                }
                return undefined;
            }
            function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
                var target;
                if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) {
                    var prop = exprOrAssignment;
                    if (prop.objectAssignmentInitializer) {
                        // In strict null checking mode, if a default value of a non-undefined type is specified, remove
                        // undefined from the final type.
                        if (strictNullChecks &&
                            !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) {
                            sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */);
                        }
                        checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
                    }
                    target = exprOrAssignment.name;
                }
                else {
                    target = exprOrAssignment;
                }
                if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) {
                    checkBinaryExpression(target, checkMode);
                    target = target.left;
                }
                if (target.kind === 186 /* ObjectLiteralExpression */) {
                    return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
                }
                if (target.kind === 185 /* ArrayLiteralExpression */) {
                    return checkArrayLiteralAssignment(target, sourceType, checkMode);
                }
                return checkReferenceAssignment(target, sourceType, checkMode);
            }
            function checkReferenceAssignment(target, sourceType, checkMode) {
                var targetType = checkExpression(target, checkMode);
                var error = target.parent.kind === 275 /* SpreadAssignment */ ?
                    ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
                    ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
                if (checkReferenceExpression(target, error)) {
                    checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
                }
                return sourceType;
            }
            /**
             * This is a *shallow* check: An expression is side-effect-free if the
             * evaluation of the expression *itself* cannot produce side effects.
             * For example, x++ / 3 is side-effect free because the / operator
             * does not have side effects.
             * The intent is to "smell test" an expression for correctness in positions where
             * its value is discarded (e.g. the left side of the comma operator).
             */
            function isSideEffectFree(node) {
                node = ts.skipParentheses(node);
                switch (node.kind) {
                    case 71 /* Identifier */:
                    case 9 /* StringLiteral */:
                    case 12 /* RegularExpressionLiteral */:
                    case 191 /* TaggedTemplateExpression */:
                    case 204 /* TemplateExpression */:
                    case 13 /* NoSubstitutionTemplateLiteral */:
                    case 8 /* NumericLiteral */:
                    case 101 /* TrueKeyword */:
                    case 86 /* FalseKeyword */:
                    case 95 /* NullKeyword */:
                    case 140 /* UndefinedKeyword */:
                    case 194 /* FunctionExpression */:
                    case 207 /* ClassExpression */:
                    case 195 /* ArrowFunction */:
                    case 185 /* ArrayLiteralExpression */:
                    case 186 /* ObjectLiteralExpression */:
                    case 197 /* TypeOfExpression */:
                    case 211 /* NonNullExpression */:
                    case 259 /* JsxSelfClosingElement */:
                    case 258 /* JsxElement */:
                        return true;
                    case 203 /* ConditionalExpression */:
                        return isSideEffectFree(node.whenTrue) &&
                            isSideEffectFree(node.whenFalse);
                    case 202 /* BinaryExpression */:
                        if (ts.isAssignmentOperator(node.operatorToken.kind)) {
                            return false;
                        }
                        return isSideEffectFree(node.left) &&
                            isSideEffectFree(node.right);
                    case 200 /* PrefixUnaryExpression */:
                    case 201 /* PostfixUnaryExpression */:
                        // Unary operators ~, !, +, and - have no side effects.
                        // The rest do.
                        switch (node.operator) {
                            case 51 /* ExclamationToken */:
                            case 37 /* PlusToken */:
                            case 38 /* MinusToken */:
                            case 52 /* TildeToken */:
                                return true;
                        }
                        return false;
                    // Some forms listed here for clarity
                    case 198 /* VoidExpression */: // Explicit opt-out
                    case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
                    case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings
                    default:
                        return false;
                }
            }
            function isTypeEqualityComparableTo(source, target) {
                return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
            }
            function checkBinaryExpression(node, checkMode) {
                if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
                    return checkExpression(node.right, checkMode);
                }
                return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node);
            }
            function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
                var operator = operatorToken.kind;
                if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) {
                    return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */);
                }
                var leftType;
                if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) {
                    leftType = checkTruthinessExpression(left, checkMode);
                }
                else {
                    leftType = checkExpression(left, checkMode);
                }
                var rightType = checkExpression(right, checkMode);
                switch (operator) {
                    case 39 /* AsteriskToken */:
                    case 40 /* AsteriskAsteriskToken */:
                    case 61 /* AsteriskEqualsToken */:
                    case 62 /* AsteriskAsteriskEqualsToken */:
                    case 41 /* SlashToken */:
                    case 63 /* SlashEqualsToken */:
                    case 42 /* PercentToken */:
                    case 64 /* PercentEqualsToken */:
                    case 38 /* MinusToken */:
                    case 60 /* MinusEqualsToken */:
                    case 45 /* LessThanLessThanToken */:
                    case 65 /* LessThanLessThanEqualsToken */:
                    case 46 /* GreaterThanGreaterThanToken */:
                    case 66 /* GreaterThanGreaterThanEqualsToken */:
                    case 47 /* GreaterThanGreaterThanGreaterThanToken */:
                    case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                    case 49 /* BarToken */:
                    case 69 /* BarEqualsToken */:
                    case 50 /* CaretToken */:
                    case 70 /* CaretEqualsToken */:
                    case 48 /* AmpersandToken */:
                    case 68 /* AmpersandEqualsToken */:
                        if (leftType === silentNeverType || rightType === silentNeverType) {
                            return silentNeverType;
                        }
                        leftType = checkNonNullType(leftType, left);
                        rightType = checkNonNullType(rightType, right);
                        var suggestedOperator = void 0;
                        // if a user tries to apply a bitwise operator to 2 boolean operands
                        // try and return them a helpful suggestion
                        if ((leftType.flags & 272 /* BooleanLike */) &&
                            (rightType.flags & 272 /* BooleanLike */) &&
                            (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
                            error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator));
                        }
                        else {
                            // otherwise just check each operand separately and report errors as normal
                            var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type);
                            var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type);
                            if (leftOk && rightOk) {
                                checkAssignmentOperator(numberType);
                            }
                        }
                        return numberType;
                    case 37 /* PlusToken */:
                    case 59 /* PlusEqualsToken */:
                        if (leftType === silentNeverType || rightType === silentNeverType) {
                            return silentNeverType;
                        }
                        if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) {
                            leftType = checkNonNullType(leftType, left);
                            rightType = checkNonNullType(rightType, right);
                        }
                        var resultType = void 0;
                        if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* NumberLike */, /*strict*/ true)) {
                            // Operands of an enum type are treated as having the primitive type Number.
                            // If both operands are of the Number primitive type, the result is of the Number primitive type.
                            resultType = numberType;
                        }
                        else if (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* StringLike */, /*strict*/ true)) {
                            // If one or both operands are of the String primitive type, the result is of the String primitive type.
                            resultType = stringType;
                        }
                        else if (isTypeAny(leftType) || isTypeAny(rightType)) {
                            // Otherwise, the result is of type Any.
                            // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
                            resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
                        }
                        // Symbols are not allowed at all in arithmetic expressions
                        if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
                            return resultType;
                        }
                        if (!resultType) {
                            reportOperatorError();
                            return anyType;
                        }
                        if (operator === 59 /* PlusEqualsToken */) {
                            checkAssignmentOperator(resultType);
                        }
                        return resultType;
                    case 27 /* LessThanToken */:
                    case 29 /* GreaterThanToken */:
                    case 30 /* LessThanEqualsToken */:
                    case 31 /* GreaterThanEqualsToken */:
                        if (checkForDisallowedESSymbolOperand(operator)) {
                            leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
                            rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
                            if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) {
                                reportOperatorError();
                            }
                        }
                        return booleanType;
                    case 32 /* EqualsEqualsToken */:
                    case 33 /* ExclamationEqualsToken */:
                    case 34 /* EqualsEqualsEqualsToken */:
                    case 35 /* ExclamationEqualsEqualsToken */:
                        var leftIsLiteral = isLiteralType(leftType);
                        var rightIsLiteral = isLiteralType(rightType);
                        if (!leftIsLiteral || !rightIsLiteral) {
                            leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType;
                            rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType;
                        }
                        if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) {
                            reportOperatorError();
                        }
                        return booleanType;
                    case 93 /* InstanceOfKeyword */:
                        return checkInstanceOfExpression(left, right, leftType, rightType);
                    case 92 /* InKeyword */:
                        return checkInExpression(left, right, leftType, rightType);
                    case 53 /* AmpersandAmpersandToken */:
                        return getTypeFacts(leftType) & 1048576 /* Truthy */ ?
                            getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
                            leftType;
                    case 54 /* BarBarToken */:
                        return getTypeFacts(leftType) & 2097152 /* Falsy */ ?
                            getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
                            leftType;
                    case 58 /* EqualsToken */:
                        var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
                        checkAssignmentDeclaration(declKind, right);
                        if (isAssignmentDeclaration(declKind)) {
                            return leftType;
                        }
                        else {
                            checkAssignmentOperator(rightType);
                            return getRegularTypeOfObjectLiteral(rightType);
                        }
                    case 26 /* CommaToken */:
                        if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
                            error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
                        }
                        return rightType;
                    default:
                        return ts.Debug.fail();
                }
                function checkAssignmentDeclaration(kind, right) {
                    if (kind === 2 /* ModuleExports */) {
                        var rightType_1 = checkExpression(right, checkMode);
                        for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) {
                            var prop = _a[_i];
                            var propType = getTypeOfSymbol(prop);
                            if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
                                var name = prop.escapedName;
                                var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false);
                                if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
                                    grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
                                    return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name));
                                }
                            }
                        }
                    }
                }
                function isEvalNode(node) {
                    return node.kind === 71 /* Identifier */ && node.escapedText === "eval";
                }
                // Return true if there was no error, false if there was an error.
                function checkForDisallowedESSymbolOperand(operator) {
                    var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left :
                        maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right :
                            undefined;
                    if (offendingSymbolOperand) {
                        error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
                        return false;
                    }
                    return true;
                }
                function getSuggestedBooleanOperator(operator) {
                    switch (operator) {
                        case 49 /* BarToken */:
                        case 69 /* BarEqualsToken */:
                            return 54 /* BarBarToken */;
                        case 50 /* CaretToken */:
                        case 70 /* CaretEqualsToken */:
                            return 35 /* ExclamationEqualsEqualsToken */;
                        case 48 /* AmpersandToken */:
                        case 68 /* AmpersandEqualsToken */:
                            return 53 /* AmpersandAmpersandToken */;
                        default:
                            return undefined;
                    }
                }
                function checkAssignmentOperator(valueType) {
                    if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
                        // TypeScript 1.0 spec (April 2014): 4.17
                        // An assignment of the form
                        //    VarExpr = ValueExpr
                        // requires VarExpr to be classified as a reference
                        // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
                        // and the type of the non-compound operation to be assignable to the type of VarExpr.
                        if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)
                            && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
                            // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
                            checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
                        }
                    }
                }
                function isAssignmentDeclaration(kind) {
                    switch (kind) {
                        case 2 /* ModuleExports */:
                            return true;
                        case 1 /* ExportsProperty */:
                        case 5 /* Property */:
                        case 6 /* Prototype */:
                        case 3 /* PrototypeProperty */:
                        case 4 /* ThisProperty */:
                            var symbol = getSymbolOfNode(left);
                            var init = ts.getAssignedExpandoInitializer(right);
                            return init && ts.isObjectLiteralExpression(init) &&
                                symbol && ts.hasEntries(symbol.exports);
                        default:
                            return false;
                    }
                }
                function reportOperatorError() {
                    var leftStr = typeToString(leftType);
                    var rightStr = typeToString(rightType);
                    var errNode = errorNode || operatorToken;
                    if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) {
                        error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
                    }
                }
                function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) {
                    switch (operatorToken.kind) {
                        case 34 /* EqualsEqualsEqualsToken */:
                        case 32 /* EqualsEqualsToken */:
                            return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr);
                        case 35 /* ExclamationEqualsEqualsToken */:
                        case 33 /* ExclamationEqualsToken */:
                            return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr);
                    }
                    return undefined;
                }
            }
            function isYieldExpressionInClass(node) {
                var current = node;
                var parent = node.parent;
                while (parent) {
                    if (ts.isFunctionLike(parent) && current === parent.body) {
                        return false;
                    }
                    else if (ts.isClassLike(current)) {
                        return true;
                    }
                    current = parent;
                    parent = parent.parent;
                }
                return false;
            }
            function checkYieldExpression(node) {
                // Grammar checking
                if (produceDiagnostics) {
                    if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) {
                        grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
                    }
                    if (isInParameterInitializerBeforeContainingFunction(node)) {
                        error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
                    }
                }
                var func = ts.getContainingFunction(node);
                if (!func)
                    return anyType;
                var functionFlags = ts.getFunctionFlags(func);
                if (!(functionFlags & 1 /* Generator */)) {
                    // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
                    return anyType;
                }
                if (node.asteriskToken) {
                    // Async generator functions prior to ESNext require the __await, __asyncDelegator,
                    // and __asyncValues helpers
                    if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
                        languageVersion < 6 /* ESNext */) {
                        checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
                    }
                    // Generator functions prior to ES2015 require the __values helper
                    if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ &&
                        languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
                        checkExternalEmitHelpers(node, 256 /* Values */);
                    }
                }
                var isAsync = (functionFlags & 2 /* Async */) !== 0;
                var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217
                // There is no point in doing an assignability check if the function
                // has no explicit return type because the return type is directly computed
                // from the yield expressions.
                var returnType = getReturnTypeFromAnnotation(func);
                if (returnType) {
                    var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType;
                    checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression);
                }
                // Both yield and yield* expressions have type 'any'
                return anyType;
            }
            function checkConditionalExpression(node, checkMode) {
                checkTruthinessExpression(node.condition);
                var type1 = checkExpression(node.whenTrue, checkMode);
                var type2 = checkExpression(node.whenFalse, checkMode);
                return getUnionType([type1, type2], 2 /* Subtype */);
            }
            function checkTemplateExpression(node) {
                // We just want to check each expressions, but we are unconcerned with
                // the type of each expression, as any value may be coerced into a string.
                // It is worth asking whether this is what we really want though.
                // A place where we actually *are* concerned with the expressions' types are
                // in tagged templates.
                ts.forEach(node.templateSpans, function (templateSpan) {
                    if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) {
                        error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
                    }
                });
                return stringType;
            }
            function getContextNode(node) {
                if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
                    return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes)
                }
                return node;
            }
            function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
                var context = getContextNode(node);
                var saveContextualType = context.contextualType;
                var saveContextualMapper = context.contextualMapper;
                context.contextualType = contextualType;
                context.contextualMapper = contextualMapper;
                var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
                    contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
                var result = checkExpression(node, checkMode);
                context.contextualType = saveContextualType;
                context.contextualMapper = saveContextualMapper;
                return result;
            }
            function checkExpressionCached(node, checkMode) {
                var links = getNodeLinks(node);
                if (!links.resolvedType) {
                    if (checkMode) {
                        return checkExpression(node, checkMode);
                    }
                    // When computing a type that we're going to cache, we need to ignore any ongoing control flow
                    // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
                    // to the top of the stack ensures all transient types are computed from a known point.
                    var saveFlowLoopStart = flowLoopStart;
                    flowLoopStart = flowLoopCount;
                    links.resolvedType = checkExpression(node, checkMode);
                    flowLoopStart = saveFlowLoopStart;
                }
                return links.resolvedType;
            }
            function isTypeAssertion(node) {
                node = ts.skipParentheses(node);
                return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */;
            }
            function checkDeclarationInitializer(declaration) {
                var initializer = ts.getEffectiveInitializer(declaration);
                var type = getTypeOfExpression(initializer, /*cache*/ true);
                var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ ||
                    ts.isDeclarationReadonly(declaration) ||
                    isTypeAssertion(initializer) ? type : getWidenedLiteralType(type);
                if (ts.isInJSFile(declaration)) {
                    if (widened.flags & 24576 /* Nullable */) {
                        if (noImplicitAny) {
                            reportImplicitAnyError(declaration, anyType);
                        }
                        return anyType;
                    }
                    else if (isEmptyArrayLiteralType(widened)) {
                        if (noImplicitAny) {
                            reportImplicitAnyError(declaration, anyArrayType);
                        }
                        return anyArrayType;
                    }
                }
                return widened;
            }
            function isLiteralOfContextualType(candidateType, contextualType) {
                if (contextualType) {
                    if (contextualType.flags & 786432 /* UnionOrIntersection */) {
                        var types = contextualType.types;
                        return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
                    }
                    if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) {
                        // If the contextual type is a type variable constrained to a primitive type, consider
                        // this a literal context for literals of that primitive type. For example, given a
                        // type parameter 'T extends string', infer string literal types for T.
                        var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType;
                        return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) ||
                            maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) ||
                            maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) ||
                            isLiteralOfContextualType(candidateType, constraint);
                    }
                    // If the contextual type is a literal of a particular primitive type, we consider this a
                    // literal context for all literals of that primitive type.
                    return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) ||
                        contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) ||
                        contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) ||
                        contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */));
                }
                return false;
            }
            function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
                if (arguments.length === 2) {
                    contextualType = getContextualType(node);
                }
                var type = checkExpression(node, checkMode, forceTuple);
                return isTypeAssertion(node) ? type :
                    getWidenedLiteralLikeTypeForContextualType(type, contextualType);
            }
            function checkPropertyAssignment(node, checkMode) {
                // Do not use hasDynamicName here, because that returns false for well known symbols.
                // We want to perform checkComputedPropertyName for all computed properties, including
                // well known symbols.
                if (node.name.kind === 147 /* ComputedPropertyName */) {
                    checkComputedPropertyName(node.name);
                }
                return checkExpressionForMutableLocation(node.initializer, checkMode);
            }
            function checkObjectLiteralMethod(node, checkMode) {
                // Grammar checking
                checkGrammarMethod(node);
                // Do not use hasDynamicName here, because that returns false for well known symbols.
                // We want to perform checkComputedPropertyName for all computed properties, including
                // well known symbols.
                if (node.name.kind === 147 /* ComputedPropertyName */) {
                    checkComputedPropertyName(node.name);
                }
                var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
                return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
            }
            function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
                if (checkMode === 2 /* Inferential */) {
                    var signature = getSingleCallSignature(type);
                    if (signature && signature.typeParameters) {
                        var contextualType = getApparentTypeOfContextualType(node);
                        if (contextualType) {
                            var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
                            if (contextualSignature && !contextualSignature.typeParameters) {
                                return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
                            }
                        }
                    }
                }
                return type;
            }
            /**
             * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
             * with computing the type and may not fully check all contained sub-expressions for errors.
             * A cache argument of true indicates that if the function performs a full type check, it is ok
             * to cache the result.
             */
            function getTypeOfExpression(node, cache) {
                var expr = ts.skipParentheses(node);
                // Optimize for the common case of a call to a function with a single non-generic call
                // signature where we can just fetch the return type without checking the arguments.
                if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
                    var funcType = checkNonNullExpression(expr.expression);
                    var signature = getSingleCallSignature(funcType);
                    if (signature && !signature.typeParameters) {
                        return getReturnTypeOfSignature(signature);
                    }
                }
                else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) {
                    return getTypeFromTypeNode(expr.type);
                }
                // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
                // should have a parameter that indicates whether full error checking is required such that
                // we can perform the optimizations locally.
                return cache ? checkExpressionCached(node) : checkExpression(node);
            }
            /**
             * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
             * with computing the type and may not fully check all contained sub-expressions for errors.
             * It is intended for uses where you know there is no contextual type,
             * and requesting the contextual type might cause a circularity or other bad behaviour.
             * It sets the contextual type of the node to any before calling getTypeOfExpression.
             */
            function getContextFreeTypeOfExpression(node) {
                var links = getNodeLinks(node);
                if (links.contextFreeType) {
                    return links.contextFreeType;
                }
                var saveContextualType = node.contextualType;
                node.contextualType = anyType;
                var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
                node.contextualType = saveContextualType;
                return type;
            }
            // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When
            // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the
            // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in
            // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function
            // object, it serves as an indicator that all contained function and arrow expressions should be considered to
            // have the wildcard function type; this form of type check is used during overload resolution to exclude
            // contextually typed function and arrow expressions in the initial phase.
            function checkExpression(node, checkMode, forceTuple) {
                var type;
                if (node.kind === 146 /* QualifiedName */) {
                    type = checkQualifiedName(node);
                }
                else {
                    var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
                    type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
                }
                if (isConstEnumObjectType(type)) {
                    // enum object type for const enums are only permitted in:
                    // - 'left' in property access
                    // - 'object' in indexed access
                    // - target in rhs of import statement
                    var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) ||
                        (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) ||
                        ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
                            (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node));
                    if (!ok) {
                        error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query);
                    }
                }
                return type;
            }
            function checkParenthesizedExpression(node, checkMode) {
                var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
                if (tag) {
                    return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
                }
                return checkExpression(node.expression, checkMode);
            }
            function checkExpressionWorker(node, checkMode, forceTuple) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return checkIdentifier(node);
                    case 99 /* ThisKeyword */:
                        return checkThisExpression(node);
                    case 97 /* SuperKeyword */:
                        return checkSuperExpression(node);
                    case 95 /* NullKeyword */:
                        return nullWideningType;
                    case 13 /* NoSubstitutionTemplateLiteral */:
                    case 9 /* StringLiteral */:
                        return getFreshTypeOfLiteralType(getLiteralType(node.text));
                    case 8 /* NumericLiteral */:
                        checkGrammarNumericLiteral(node);
                        return getFreshTypeOfLiteralType(getLiteralType(+node.text));
                    case 101 /* TrueKeyword */:
                        return trueType;
                    case 86 /* FalseKeyword */:
                        return falseType;
                    case 204 /* TemplateExpression */:
                        return checkTemplateExpression(node);
                    case 12 /* RegularExpressionLiteral */:
                        return globalRegExpType;
                    case 185 /* ArrayLiteralExpression */:
                        return checkArrayLiteral(node, checkMode, forceTuple);
                    case 186 /* ObjectLiteralExpression */:
                        return checkObjectLiteral(node, checkMode);
                    case 187 /* PropertyAccessExpression */:
                        return checkPropertyAccessExpression(node);
                    case 188 /* ElementAccessExpression */:
                        return checkIndexedAccess(node);
                    case 189 /* CallExpression */:
                        if (node.expression.kind === 91 /* ImportKeyword */) {
                            return checkImportCallExpression(node);
                        }
                    /* falls through */
                    case 190 /* NewExpression */:
                        return checkCallExpression(node);
                    case 191 /* TaggedTemplateExpression */:
                        return checkTaggedTemplateExpression(node);
                    case 193 /* ParenthesizedExpression */:
                        return checkParenthesizedExpression(node, checkMode);
                    case 207 /* ClassExpression */:
                        return checkClassExpression(node);
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
                    case 197 /* TypeOfExpression */:
                        return checkTypeOfExpression(node);
                    case 192 /* TypeAssertionExpression */:
                    case 210 /* AsExpression */:
                        return checkAssertion(node);
                    case 211 /* NonNullExpression */:
                        return checkNonNullAssertion(node);
                    case 212 /* MetaProperty */:
                        return checkMetaProperty(node);
                    case 196 /* DeleteExpression */:
                        return checkDeleteExpression(node);
                    case 198 /* VoidExpression */:
                        return checkVoidExpression(node);
                    case 199 /* AwaitExpression */:
                        return checkAwaitExpression(node);
                    case 200 /* PrefixUnaryExpression */:
                        return checkPrefixUnaryExpression(node);
                    case 201 /* PostfixUnaryExpression */:
                        return checkPostfixUnaryExpression(node);
                    case 202 /* BinaryExpression */:
                        return checkBinaryExpression(node, checkMode);
                    case 203 /* ConditionalExpression */:
                        return checkConditionalExpression(node, checkMode);
                    case 206 /* SpreadElement */:
                        return checkSpreadExpression(node, checkMode);
                    case 208 /* OmittedExpression */:
                        return undefinedWideningType;
                    case 205 /* YieldExpression */:
                        return checkYieldExpression(node);
                    case 213 /* SyntheticExpression */:
                        return node.type;
                    case 268 /* JsxExpression */:
                        return checkJsxExpression(node, checkMode);
                    case 258 /* JsxElement */:
                        return checkJsxElement(node, checkMode);
                    case 259 /* JsxSelfClosingElement */:
                        return checkJsxSelfClosingElement(node, checkMode);
                    case 262 /* JsxFragment */:
                        return checkJsxFragment(node, checkMode);
                    case 266 /* JsxAttributes */:
                        return checkJsxAttributes(node, checkMode);
                    case 260 /* JsxOpeningElement */:
                        ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
                }
                return errorType;
            }
            // DECLARATION AND STATEMENT TYPE CHECKING
            function checkTypeParameter(node) {
                // Grammar Checking
                if (node.expression) {
                    grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
                }
                checkSourceElement(node.constraint);
                checkSourceElement(node.default);
                var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
                if (!hasNonCircularBaseConstraint(typeParameter)) {
                    error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
                }
                if (!hasNonCircularTypeParameterDefault(typeParameter)) {
                    error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
                }
                var constraintType = getConstraintOfTypeParameter(typeParameter);
                var defaultType = getDefaultFromTypeParameter(typeParameter);
                if (constraintType && defaultType) {
                    checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
                }
                if (produceDiagnostics) {
                    checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
                }
            }
            function checkParameter(node) {
                // Grammar checking
                // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
                // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
                // or if its FunctionBody is strict code(11.1.5).
                checkGrammarDecoratorsAndModifiers(node);
                checkVariableLikeDeclaration(node);
                var func = ts.getContainingFunction(node);
                if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
                    if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) {
                        error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
                    }
                }
                if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
                    error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
                }
                if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
                    if (func.parameters.indexOf(node) !== 0) {
                        error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
                    }
                    if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) {
                        error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
                    }
                    if (func.kind === 195 /* ArrowFunction */) {
                        error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
                    }
                }
                // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
                // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
                if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
                    error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
                }
            }
            function checkTypePredicate(node) {
                var parent = getTypePredicateParent(node);
                if (!parent) {
                    // The parent must not be valid.
                    error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
                    return;
                }
                var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
                if (!typePredicate) {
                    return;
                }
                checkSourceElement(node.type);
                var parameterName = node.parameterName;
                if (ts.isThisTypePredicate(typePredicate)) {
                    getTypeFromThisTypeNode(parameterName);
                }
                else {
                    if (typePredicate.parameterIndex >= 0) {
                        if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
                            error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
                        }
                        else {
                            var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
                            checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, 
                            /*headMessage*/ undefined, leadingError);
                        }
                    }
                    else if (parameterName) {
                        var hasReportedError = false;
                        for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
                            var name = _a[_i].name;
                            if (ts.isBindingPattern(name) &&
                                checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
                                hasReportedError = true;
                                break;
                            }
                        }
                        if (!hasReportedError) {
                            error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
                        }
                    }
                }
            }
            function getTypePredicateParent(node) {
                switch (node.parent.kind) {
                    case 195 /* ArrowFunction */:
                    case 158 /* CallSignature */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 163 /* FunctionType */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                        var parent = node.parent;
                        if (node === parent.type) {
                            return parent;
                        }
                }
            }
            function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
                for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
                    var element = _a[_i];
                    if (ts.isOmittedExpression(element)) {
                        continue;
                    }
                    var name = element.name;
                    if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) {
                        error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
                        return true;
                    }
                    else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) {
                        if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
                            return true;
                        }
                    }
                }
            }
            function checkSignatureDeclaration(node) {
                // Grammar checking
                if (node.kind === 160 /* IndexSignature */) {
                    checkGrammarIndexSignature(node);
                }
                // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
                else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ ||
                    node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ ||
                    node.kind === 159 /* ConstructSignature */) {
                    checkGrammarFunctionLikeDeclaration(node);
                }
                var functionFlags = ts.getFunctionFlags(node);
                if (!(functionFlags & 4 /* Invalid */)) {
                    // Async generators prior to ESNext require the __await and __asyncGenerator helpers
                    if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) {
                        checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
                    }
                    // Async functions prior to ES2017 require the __awaiter helper
                    if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
                        checkExternalEmitHelpers(node, 64 /* Awaiter */);
                    }
                    // Generator functions, Async functions, and Async Generator functions prior to
                    // ES2015 require the __generator helper
                    if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
                        checkExternalEmitHelpers(node, 128 /* Generator */);
                    }
                }
                checkTypeParameters(node.typeParameters);
                ts.forEach(node.parameters, checkParameter);
                // TODO(rbuckton): Should we start checking JSDoc types?
                if (node.type) {
                    checkSourceElement(node.type);
                }
                if (produceDiagnostics) {
                    checkCollisionWithArgumentsInGeneratedCode(node);
                    var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
                    if (noImplicitAny && !returnTypeNode) {
                        switch (node.kind) {
                            case 159 /* ConstructSignature */:
                                error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
                                break;
                            case 158 /* CallSignature */:
                                error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
                                break;
                        }
                    }
                    if (returnTypeNode) {
                        var functionFlags_1 = ts.getFunctionFlags(node);
                        if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
                            var returnType = getTypeFromTypeNode(returnTypeNode);
                            if (returnType === voidType) {
                                error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
                            }
                            else {
                                var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
                                var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */
                                    ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function
                                    : createIterableIteratorType(generatorElementType); // Generator function
                                // Naively, one could check that IterableIterator<any> is assignable to the return type annotation.
                                // However, that would not catch the error in the following case.
                                //
                                //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
                                //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
                                //
                                checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode);
                            }
                        }
                        else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
                            checkAsyncFunctionReturnType(node, returnTypeNode);
                        }
                    }
                    if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) {
                        registerForUnusedIdentifiersCheck(node);
                    }
                }
            }
            function checkClassForDuplicateDeclarations(node) {
                var Declaration;
                (function (Declaration) {
                    Declaration[Declaration["Getter"] = 1] = "Getter";
                    Declaration[Declaration["Setter"] = 2] = "Setter";
                    Declaration[Declaration["Method"] = 4] = "Method";
                    Declaration[Declaration["Property"] = 3] = "Property";
                })(Declaration || (Declaration = {}));
                var instanceNames = ts.createUnderscoreEscapedMap();
                var staticNames = ts.createUnderscoreEscapedMap();
                for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                    var member = _a[_i];
                    if (member.kind === 155 /* Constructor */) {
                        for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
                            var param = _c[_b];
                            if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) {
                                addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */);
                            }
                        }
                    }
                    else {
                        var isStatic = ts.hasModifier(member, 32 /* Static */);
                        var names = isStatic ? staticNames : instanceNames;
                        var name = member.name;
                        var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
                        if (name && memberName) {
                            switch (member.kind) {
                                case 156 /* GetAccessor */:
                                    addName(names, name, memberName, 1 /* Getter */);
                                    break;
                                case 157 /* SetAccessor */:
                                    addName(names, name, memberName, 2 /* Setter */);
                                    break;
                                case 152 /* PropertyDeclaration */:
                                    addName(names, name, memberName, 3 /* Property */);
                                    break;
                                case 154 /* MethodDeclaration */:
                                    addName(names, name, memberName, 4 /* Method */);
                                    break;
                            }
                        }
                    }
                }
                function addName(names, location, name, meaning) {
                    var prev = names.get(name);
                    if (prev) {
                        if (prev & 4 /* Method */) {
                            if (meaning !== 4 /* Method */) {
                                error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
                            }
                        }
                        else if (prev & meaning) {
                            error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
                        }
                        else {
                            names.set(name, prev | meaning);
                        }
                    }
                    else {
                        names.set(name, meaning);
                    }
                }
            }
            /**
             * Static members being set on a constructor function may conflict with built-in properties
             * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
             * built-in properties. This check issues a transpile error when a class has a static
             * member with the same name as a non-writable built-in property.
             *
             * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
             * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
             * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
             * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
             */
            function checkClassForStaticPropertyNameConflicts(node) {
                for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                    var member = _a[_i];
                    var memberNameNode = member.name;
                    var isStatic = ts.hasModifier(member, 32 /* Static */);
                    if (isStatic && memberNameNode) {
                        var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
                        switch (memberName) {
                            case "name":
                            case "length":
                            case "caller":
                            case "arguments":
                            case "prototype":
                                var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
                                var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
                                error(memberNameNode, message, memberName, className);
                                break;
                        }
                    }
                }
            }
            function checkObjectTypeForDuplicateDeclarations(node) {
                var names = ts.createMap();
                for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                    var member = _a[_i];
                    if (member.kind === 151 /* PropertySignature */) {
                        var memberName = void 0;
                        var name = member.name;
                        switch (name.kind) {
                            case 9 /* StringLiteral */:
                            case 8 /* NumericLiteral */:
                                memberName = name.text;
                                break;
                            case 71 /* Identifier */:
                                memberName = ts.idText(name);
                                break;
                            default:
                                continue;
                        }
                        if (names.get(memberName)) {
                            error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
                            error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
                        }
                        else {
                            names.set(memberName, true);
                        }
                    }
                }
            }
            function checkTypeForDuplicateIndexSignatures(node) {
                if (node.kind === 239 /* InterfaceDeclaration */) {
                    var nodeSymbol = getSymbolOfNode(node);
                    // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
                    // to prevent this run check only for the first declaration of a given kind
                    if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
                        return;
                    }
                }
                // TypeScript 1.0 spec (April 2014)
                // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
                // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
                var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
                if (indexSymbol) {
                    var seenNumericIndexer = false;
                    var seenStringIndexer = false;
                    for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        var declaration = decl;
                        if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
                            switch (declaration.parameters[0].type.kind) {
                                case 137 /* StringKeyword */:
                                    if (!seenStringIndexer) {
                                        seenStringIndexer = true;
                                    }
                                    else {
                                        error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
                                    }
                                    break;
                                case 134 /* NumberKeyword */:
                                    if (!seenNumericIndexer) {
                                        seenNumericIndexer = true;
                                    }
                                    else {
                                        error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
                                    }
                                    break;
                            }
                        }
                    }
                }
            }
            function checkPropertyDeclaration(node) {
                // Grammar checking
                if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
                    checkGrammarComputedPropertyName(node.name);
                checkVariableLikeDeclaration(node);
            }
            function checkMethodDeclaration(node) {
                // Grammar checking
                if (!checkGrammarMethod(node))
                    checkGrammarComputedPropertyName(node.name);
                // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
                checkFunctionOrMethodDeclaration(node);
                // Abstract methods cannot have an implementation.
                // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
                if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) {
                    error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
                }
            }
            function checkConstructorDeclaration(node) {
                // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
                checkSignatureDeclaration(node);
                // Grammar check for checking only related to constructorDeclaration
                if (!checkGrammarConstructorTypeParameters(node))
                    checkGrammarConstructorTypeAnnotation(node);
                checkSourceElement(node.body);
                var symbol = getSymbolOfNode(node);
                var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
                // Only type check the symbol once
                if (node === firstDeclaration) {
                    checkFunctionOrConstructorSymbol(symbol);
                }
                // exit early in the case of signature - super checks are not relevant to them
                if (ts.nodeIsMissing(node.body)) {
                    return;
                }
                if (!produceDiagnostics) {
                    return;
                }
                function isInstancePropertyWithInitializer(n) {
                    return n.kind === 152 /* PropertyDeclaration */ &&
                        !ts.hasModifier(n, 32 /* Static */) &&
                        !!n.initializer;
                }
                // TS 1.0 spec (April 2014): 8.3.2
                // Constructors of classes with no extends clause may not contain super calls, whereas
                // constructors of derived classes must contain at least one super call somewhere in their function body.
                var containingClassDecl = node.parent;
                if (ts.getEffectiveBaseTypeNode(containingClassDecl)) {
                    captureLexicalThis(node.parent, containingClassDecl);
                    var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
                    var superCall = getSuperCallInConstructor(node);
                    if (superCall) {
                        if (classExtendsNull) {
                            error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
                        }
                        // The first statement in the body of a constructor (excluding prologue directives) must be a super call
                        // if both of the following are true:
                        // - The containing class is a derived class.
                        // - The constructor declares parameter properties
                        //   or the containing class declares instance member variables with initializers.
                        var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) ||
                            ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); });
                        // Skip past any prologue directives to find the first statement
                        // to ensure that it was a super call.
                        if (superCallShouldBeFirst) {
                            var statements = node.body.statements;
                            var superCallStatement = void 0;
                            for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
                                var statement = statements_2[_i];
                                if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
                                    superCallStatement = statement;
                                    break;
                                }
                                if (!ts.isPrologueDirective(statement)) {
                                    break;
                                }
                            }
                            if (!superCallStatement) {
                                error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties);
                            }
                        }
                    }
                    else if (!classExtendsNull) {
                        error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
                    }
                }
            }
            function checkAccessorDeclaration(node) {
                if (produceDiagnostics) {
                    // Grammar checking accessors
                    if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
                        checkGrammarComputedPropertyName(node.name);
                    checkDecorators(node);
                    checkSignatureDeclaration(node);
                    if (node.kind === 156 /* GetAccessor */) {
                        if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) {
                            if (!(node.flags & 256 /* HasExplicitReturn */)) {
                                error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
                            }
                        }
                    }
                    // Do not use hasDynamicName here, because that returns false for well known symbols.
                    // We want to perform checkComputedPropertyName for all computed properties, including
                    // well known symbols.
                    if (node.name.kind === 147 /* ComputedPropertyName */) {
                        checkComputedPropertyName(node.name);
                    }
                    if (!hasNonBindableDynamicName(node)) {
                        // TypeScript 1.0 spec (April 2014): 8.4.3
                        // Accessors for the same member name must specify the same accessibility.
                        var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */;
                        var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
                        if (otherAccessor) {
                            var nodeFlags = ts.getModifierFlags(node);
                            var otherFlags = ts.getModifierFlags(otherAccessor);
                            if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
                                error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
                            }
                            if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
                                error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
                            }
                            // TypeScript 1.0 spec (April 2014): 4.5
                            // If both accessors include type annotations, the specified types must be identical.
                            checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
                            checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
                        }
                    }
                    var returnType = getTypeOfAccessors(getSymbolOfNode(node));
                    if (node.kind === 156 /* GetAccessor */) {
                        checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
                    }
                }
                checkSourceElement(node.body);
            }
            function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
                var firstType = getAnnotatedType(first);
                var secondType = getAnnotatedType(second);
                if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
                    error(first, message);
                }
            }
            function checkMissingDeclaration(node) {
                checkDecorators(node);
            }
            function getEffectiveTypeArguments(node, typeParameters) {
                return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
            }
            function checkTypeArgumentConstraints(node, typeParameters) {
                var typeArguments;
                var mapper;
                var result = true;
                for (var i = 0; i < typeParameters.length; i++) {
                    var constraint = getConstraintOfTypeParameter(typeParameters[i]);
                    if (constraint) {
                        if (!typeArguments) {
                            typeArguments = getEffectiveTypeArguments(node, typeParameters);
                            mapper = createTypeMapper(typeParameters, typeArguments);
                        }
                        result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
                    }
                }
                return result;
            }
            function getTypeParametersForTypeReference(node) {
                var type = getTypeFromTypeReference(node);
                if (type !== errorType) {
                    var symbol = getNodeLinks(node).resolvedSymbol;
                    if (symbol) {
                        return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
                            (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
                    }
                }
                return undefined;
            }
            function checkTypeReferenceNode(node) {
                checkGrammarTypeArguments(node, node.typeArguments);
                if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
                    grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
                }
                var type = getTypeFromTypeReference(node);
                if (type !== errorType) {
                    if (node.typeArguments) {
                        // Do type argument local checks only if referenced type is successfully resolved
                        ts.forEach(node.typeArguments, checkSourceElement);
                        if (produceDiagnostics) {
                            var typeParameters = getTypeParametersForTypeReference(node);
                            if (typeParameters) {
                                checkTypeArgumentConstraints(node, typeParameters);
                            }
                        }
                    }
                    if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
                        error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
                    }
                }
            }
            function getTypeArgumentConstraint(node) {
                var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
                if (!typeReferenceNode)
                    return undefined;
                var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
                var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
                return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
            }
            function checkTypeQuery(node) {
                getTypeFromTypeQueryNode(node);
            }
            function checkTypeLiteral(node) {
                ts.forEach(node.members, checkSourceElement);
                if (produceDiagnostics) {
                    var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
                    checkIndexConstraints(type);
                    checkTypeForDuplicateIndexSignatures(node);
                    checkObjectTypeForDuplicateDeclarations(node);
                }
            }
            function checkArrayType(node) {
                checkSourceElement(node.elementType);
            }
            function checkTupleType(node) {
                var elementTypes = node.elementTypes;
                var seenOptionalElement = false;
                for (var i = 0; i < elementTypes.length; i++) {
                    var e = elementTypes[i];
                    if (e.kind === 170 /* RestType */) {
                        if (i !== elementTypes.length - 1) {
                            grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
                            break;
                        }
                        if (!isArrayType(getTypeFromTypeNode(e))) {
                            error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
                        }
                    }
                    else if (e.kind === 169 /* OptionalType */) {
                        seenOptionalElement = true;
                    }
                    else if (seenOptionalElement) {
                        grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
                        break;
                    }
                }
                checkGrammarForDisallowedTrailingComma(node.elementTypes);
                ts.forEach(node.elementTypes, checkSourceElement);
            }
            function checkUnionOrIntersectionType(node) {
                ts.forEach(node.types, checkSourceElement);
            }
            function checkIndexedAccessIndexType(type, accessNode) {
                if (!(type.flags & 2097152 /* IndexedAccess */)) {
                    return type;
                }
                // Check if the index type is assignable to 'keyof T' for the object type.
                var objectType = type.objectType;
                var indexType = type.indexType;
                if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
                    if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
                        ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
                        error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
                    }
                    return type;
                }
                // Check if we're indexing with a numeric type and if either object or index types
                // is a generic type with a constraint that has a numeric index signature.
                if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) {
                    return type;
                }
                error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
                return type;
            }
            function checkIndexedAccessType(node) {
                checkSourceElement(node.objectType);
                checkSourceElement(node.indexType);
                checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
            }
            function checkMappedType(node) {
                checkSourceElement(node.typeParameter);
                checkSourceElement(node.type);
                if (noImplicitAny && !node.type) {
                    reportImplicitAnyError(node, anyType);
                }
                var type = getTypeFromMappedTypeNode(node);
                var constraintType = getConstraintTypeFromMappedType(type);
                checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
            }
            function checkThisType(node) {
                getTypeFromThisTypeNode(node);
            }
            function checkTypeOperator(node) {
                checkGrammarTypeOperatorNode(node);
                checkSourceElement(node.type);
            }
            function checkConditionalType(node) {
                ts.forEachChild(node, checkSourceElement);
            }
            function checkInferType(node) {
                if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) {
                    grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
                }
                checkSourceElement(node.typeParameter);
                registerForUnusedIdentifiersCheck(node);
            }
            function checkImportType(node) {
                checkSourceElement(node.argument);
                getTypeFromTypeNode(node);
            }
            function isPrivateWithinAmbient(node) {
                return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */);
            }
            function getEffectiveDeclarationFlags(n, flagsToCheck) {
                var flags = ts.getCombinedModifierFlags(n);
                // children of classes (even ambient classes) should not be marked as ambient or export
                // because those flags have no useful semantics there.
                if (n.parent.kind !== 239 /* InterfaceDeclaration */ &&
                    n.parent.kind !== 238 /* ClassDeclaration */ &&
                    n.parent.kind !== 207 /* ClassExpression */ &&
                    n.flags & 4194304 /* Ambient */) {
                    if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
                        // It is nested in an ambient context, which means it is automatically exported
                        flags |= 1 /* Export */;
                    }
                    flags |= 2 /* Ambient */;
                }
                return flags & flagsToCheck;
            }
            function checkFunctionOrConstructorSymbol(symbol) {
                if (!produceDiagnostics) {
                    return;
                }
                function getCanonicalOverload(overloads, implementation) {
                    // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
                    // Error on all deviations from this canonical set of flags
                    // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
                    // report the errors on those. To achieve this, we will say that the implementation is
                    // the canonical signature only if it is in the same container as the first overload
                    var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
                    return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
                }
                function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
                    // Error if some overloads have a flag that is not shared by all overloads. To find the
                    // deviations, we XOR someOverloadFlags with allOverloadFlags
                    var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
                    if (someButNotAllOverloadFlags !== 0) {
                        var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
                        ts.forEach(overloads, function (o) {
                            var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
                            if (deviation & 1 /* Export */) {
                                error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
                            }
                            else if (deviation & 2 /* Ambient */) {
                                error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
                            }
                            else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
                                error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
                            }
                            else if (deviation & 128 /* Abstract */) {
                                error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
                            }
                        });
                    }
                }
                function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
                    if (someHaveQuestionToken !== allHaveQuestionToken) {
                        var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
                        ts.forEach(overloads, function (o) {
                            var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
                            if (deviation) {
                                error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
                            }
                        });
                    }
                }
                var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
                var someNodeFlags = 0 /* None */;
                var allNodeFlags = flagsToCheck;
                var someHaveQuestionToken = false;
                var allHaveQuestionToken = true;
                var hasOverloads = false;
                var bodyDeclaration;
                var lastSeenNonAmbientDeclaration;
                var previousDeclaration;
                var declarations = symbol.declarations;
                var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
                function reportImplementationExpectedError(node) {
                    if (node.name && ts.nodeIsMissing(node.name)) {
                        return;
                    }
                    var seen = false;
                    var subsequentNode = ts.forEachChild(node.parent, function (c) {
                        if (seen) {
                            return c;
                        }
                        else {
                            seen = c === node;
                        }
                    });
                    // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
                    // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
                    if (subsequentNode && subsequentNode.pos === node.end) {
                        if (subsequentNode.kind === node.kind) {
                            var errorNode_1 = subsequentNode.name || subsequentNode;
                            // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
                            var subsequentName = subsequentNode.name;
                            if (node.name && subsequentName &&
                                (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
                                    !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
                                var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) &&
                                    ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
                                // we can get here in two cases
                                // 1. mixed static and instance class members
                                // 2. something with the same name was defined before the set of overloads that prevents them from merging
                                // here we'll report error only for the first case since for second we should already report error in binder
                                if (reportError) {
                                    var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
                                    error(errorNode_1, diagnostic);
                                }
                                return;
                            }
                            else if (ts.nodeIsPresent(subsequentNode.body)) {
                                error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
                                return;
                            }
                        }
                    }
                    var errorNode = node.name || node;
                    if (isConstructor) {
                        error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
                    }
                    else {
                        // Report different errors regarding non-consecutive blocks of declarations depending on whether
                        // the node in question is abstract.
                        if (ts.hasModifier(node, 128 /* Abstract */)) {
                            error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
                        }
                        else {
                            error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
                        }
                    }
                }
                var duplicateFunctionDeclaration = false;
                var multipleConstructorImplementation = false;
                for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
                    var current = declarations_4[_i];
                    var node = current;
                    var inAmbientContext = node.flags & 4194304 /* Ambient */;
                    var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext;
                    if (inAmbientContextOrInterface) {
                        // check if declarations are consecutive only if they are non-ambient
                        // 1. ambient declarations can be interleaved
                        // i.e. this is legal
                        //     declare function foo();
                        //     declare function bar();
                        //     declare function foo();
                        // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
                        previousDeclaration = undefined;
                    }
                    if (node.kind === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) {
                        var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
                        someNodeFlags |= currentNodeFlags;
                        allNodeFlags &= currentNodeFlags;
                        someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
                        allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
                        if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
                            if (isConstructor) {
                                multipleConstructorImplementation = true;
                            }
                            else {
                                duplicateFunctionDeclaration = true;
                            }
                        }
                        else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
                            reportImplementationExpectedError(previousDeclaration);
                        }
                        if (ts.nodeIsPresent(node.body)) {
                            if (!bodyDeclaration) {
                                bodyDeclaration = node;
                            }
                        }
                        else {
                            hasOverloads = true;
                        }
                        previousDeclaration = node;
                        if (!inAmbientContextOrInterface) {
                            lastSeenNonAmbientDeclaration = node;
                        }
                    }
                }
                if (multipleConstructorImplementation) {
                    ts.forEach(declarations, function (declaration) {
                        error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
                    });
                }
                if (duplicateFunctionDeclaration) {
                    ts.forEach(declarations, function (declaration) {
                        error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
                    });
                }
                // Abstract methods can't have an implementation -- in particular, they don't need one.
                if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
                    !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
                    reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
                }
                if (hasOverloads) {
                    checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
                    checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
                    if (bodyDeclaration) {
                        var signatures = getSignaturesOfSymbol(symbol);
                        var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
                        for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) {
                            var signature = signatures_7[_a];
                            if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
                                error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
                                break;
                            }
                        }
                    }
                }
            }
            var DeclarationSpaces;
            (function (DeclarationSpaces) {
                DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
                DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
                DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
                DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
            })(DeclarationSpaces || (DeclarationSpaces = {}));
            function checkExportsOnMergedDeclarations(node) {
                if (!produceDiagnostics) {
                    return;
                }
                // if localSymbol is defined on node then node itself is exported - check is required
                var symbol = node.localSymbol;
                if (!symbol) {
                    // local symbol is undefined => this declaration is non-exported.
                    // however symbol might contain other declarations that are exported
                    symbol = getSymbolOfNode(node);
                    if (!symbol.exportSymbol) {
                        // this is a pure local symbol (all declarations are non-exported) - no need to check anything
                        return;
                    }
                }
                // run the check only for the first declaration in the list
                if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
                    return;
                }
                var exportedDeclarationSpaces = 0 /* None */;
                var nonExportedDeclarationSpaces = 0 /* None */;
                var defaultExportedDeclarationSpaces = 0 /* None */;
                for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                    var d = _a[_i];
                    var declarationSpaces = getDeclarationSpaces(d);
                    var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
                    if (effectiveDeclarationFlags & 1 /* Export */) {
                        if (effectiveDeclarationFlags & 512 /* Default */) {
                            defaultExportedDeclarationSpaces |= declarationSpaces;
                        }
                        else {
                            exportedDeclarationSpaces |= declarationSpaces;
                        }
                    }
                    else {
                        nonExportedDeclarationSpaces |= declarationSpaces;
                    }
                }
                // Spaces for anything not declared a 'default export'.
                var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
                var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
                var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
                if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
                    // declaration spaces for exported and non-exported declarations intersect
                    for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
                        var d = _c[_b];
                        var declarationSpaces = getDeclarationSpaces(d);
                        var name = ts.getNameOfDeclaration(d);
                        // Only error on the declarations that contributed to the intersecting spaces.
                        if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
                            error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name));
                        }
                        else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
                            error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
                        }
                    }
                }
                function getDeclarationSpaces(decl) {
                    var d = decl;
                    switch (d.kind) {
                        case 239 /* InterfaceDeclaration */:
                        case 240 /* TypeAliasDeclaration */:
                        // A jsdoc typedef and callback are, by definition, type aliases
                        case 302 /* JSDocTypedefTag */:
                        case 295 /* JSDocCallbackTag */:
                            return 2 /* ExportType */;
                        case 242 /* ModuleDeclaration */:
                            return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
                                ? 4 /* ExportNamespace */ | 1 /* ExportValue */
                                : 4 /* ExportNamespace */;
                        case 238 /* ClassDeclaration */:
                        case 241 /* EnumDeclaration */:
                            return 2 /* ExportType */ | 1 /* ExportValue */;
                        case 277 /* SourceFile */:
                            return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
                        case 252 /* ExportAssignment */:
                            // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
                            if (!ts.isEntityNameExpression(d.expression)) {
                                return 1 /* ExportValue */;
                            }
                            d = d.expression;
                        /* falls through */
                        // The below options all declare an Alias, which is allowed to merge with other values within the importing module
                        case 246 /* ImportEqualsDeclaration */:
                        case 249 /* NamespaceImport */:
                        case 248 /* ImportClause */:
                            var result_4 = 0 /* None */;
                            var target = resolveAlias(getSymbolOfNode(d));
                            ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); });
                            return result_4;
                        case 235 /* VariableDeclaration */:
                        case 184 /* BindingElement */:
                        case 237 /* FunctionDeclaration */:
                        case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
                            return 1 /* ExportValue */;
                        default:
                            return ts.Debug.fail(ts.Debug.showSyntaxKind(d));
                    }
                }
            }
            function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) {
                var promisedType = getPromisedTypeOfPromise(type, errorNode);
                return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage);
            }
            /**
             * Gets the "promised type" of a promise.
             * @param type The type of the promise.
             * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
             */
            function getPromisedTypeOfPromise(promise, errorNode) {
                //
                //  { // promise
                //      then( // thenFunction
                //          onfulfilled: ( // onfulfilledParameterType
                //              value: T // valueParameterType
                //          ) => any
                //      ): any;
                //  }
                //
                if (isTypeAny(promise)) {
                    return undefined;
                }
                var typeAsPromise = promise;
                if (typeAsPromise.promisedTypeOfPromise) {
                    return typeAsPromise.promisedTypeOfPromise;
                }
                if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) {
                    return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0];
                }
                var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217
                if (isTypeAny(thenFunction)) {
                    return undefined;
                }
                var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
                if (thenSignatures.length === 0) {
                    if (errorNode) {
                        error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
                    }
                    return undefined;
                }
                var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */);
                if (isTypeAny(onfulfilledParameterType)) {
                    return undefined;
                }
                var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
                if (onfulfilledParameterSignatures.length === 0) {
                    if (errorNode) {
                        error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
                    }
                    return undefined;
                }
                return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
            }
            /**
             * Gets the "awaited type" of a type.
             * @param type The type to await.
             * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
             * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
             * The runtime behavior of the `await` keyword.
             */
            function checkAwaitedType(type, errorNode, diagnosticMessage) {
                return getAwaitedType(type, errorNode, diagnosticMessage) || errorType;
            }
            function getAwaitedType(type, errorNode, diagnosticMessage) {
                var typeAsAwaitable = type;
                if (typeAsAwaitable.awaitedTypeOfType) {
                    return typeAsAwaitable.awaitedTypeOfType;
                }
                if (isTypeAny(type)) {
                    return typeAsAwaitable.awaitedTypeOfType = type;
                }
                if (type.flags & 262144 /* Union */) {
                    var types = void 0;
                    for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
                        var constituentType = _a[_i];
                        types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage));
                    }
                    if (!types) {
                        return undefined;
                    }
                    return typeAsAwaitable.awaitedTypeOfType = getUnionType(types);
                }
                var promisedType = getPromisedTypeOfPromise(type);
                if (promisedType) {
                    if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) {
                        // Verify that we don't have a bad actor in the form of a promise whose
                        // promised type is the same as the promise type, or a mutually recursive
                        // promise. If so, we return undefined as we cannot guess the shape. If this
                        // were the actual case in the JavaScript, this Promise would never resolve.
                        //
                        // An example of a bad actor with a singly-recursive promise type might
                        // be:
                        //
                        //  interface BadPromise {
                        //      then(
                        //          onfulfilled: (value: BadPromise) => any,
                        //          onrejected: (error: any) => any): BadPromise;
                        //  }
                        // The above interface will pass the PromiseLike check, and return a
                        // promised type of `BadPromise`. Since this is a self reference, we
                        // don't want to keep recursing ad infinitum.
                        //
                        // An example of a bad actor in the form of a mutually-recursive
                        // promise type might be:
                        //
                        //  interface BadPromiseA {
                        //      then(
                        //          onfulfilled: (value: BadPromiseB) => any,
                        //          onrejected: (error: any) => any): BadPromiseB;
                        //  }
                        //
                        //  interface BadPromiseB {
                        //      then(
                        //          onfulfilled: (value: BadPromiseA) => any,
                        //          onrejected: (error: any) => any): BadPromiseA;
                        //  }
                        //
                        if (errorNode) {
                            error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
                        }
                        return undefined;
                    }
                    // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
                    // See the comments above for more information.
                    awaitedTypeStack.push(type.id);
                    var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage);
                    awaitedTypeStack.pop();
                    if (!awaitedType) {
                        return undefined;
                    }
                    return typeAsAwaitable.awaitedTypeOfType = awaitedType;
                }
                // The type was not a promise, so it could not be unwrapped any further.
                // As long as the type does not have a callable "then" property, it is
                // safe to return the type; otherwise, an error will be reported in
                // the call to getNonThenableType and we will return undefined.
                //
                // An example of a non-promise "thenable" might be:
                //
                //  await { then(): void {} }
                //
                // The "thenable" does not match the minimal definition for a promise. When
                // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
                // will never settle. We treat this as an error to help flag an early indicator
                // of a runtime problem. If the user wants to return this value from an async
                // function, they would need to wrap it in some other value. If they want it to
                // be treated as a promise, they can cast to <any>.
                var thenFunction = getTypeOfPropertyOfType(type, "then");
                if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) {
                    if (errorNode) {
                        if (!diagnosticMessage)
                            return ts.Debug.fail();
                        error(errorNode, diagnosticMessage);
                    }
                    return undefined;
                }
                return typeAsAwaitable.awaitedTypeOfType = type;
            }
            /**
             * Checks the return type of an async function to ensure it is a compatible
             * Promise implementation.
             *
             * This checks that an async function has a valid Promise-compatible return type.
             * An async function has a valid Promise-compatible return type if the resolved value
             * of the return type has a construct signature that takes in an `initializer` function
             * that in turn supplies a `resolve` function as one of its arguments and results in an
             * object with a callable `then` signature.
             *
             * @param node The signature to check
             */
            function checkAsyncFunctionReturnType(node, returnTypeNode) {
                // As part of our emit for an async function, we will need to emit the entity name of
                // the return type annotation as an expression. To meet the necessary runtime semantics
                // for __awaiter, we must also check that the type of the declaration (e.g. the static
                // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
                //
                // An example might be (from lib.es6.d.ts):
                //
                //  interface Promise<T> { ... }
                //  interface PromiseConstructor {
                //      new <T>(...): Promise<T>;
                //  }
                //  declare var Promise: PromiseConstructor;
                //
                // When an async function declares a return type annotation of `Promise<T>`, we
                // need to get the type of the `Promise` variable declaration above, which would
                // be `PromiseConstructor`.
                //
                // The same case applies to a class:
                //
                //  declare class Promise<T> {
                //      constructor(...);
                //      then<U>(...): Promise<U>;
                //  }
                //
                var returnType = getTypeFromTypeNode(returnTypeNode);
                if (languageVersion >= 2 /* ES2015 */) {
                    if (returnType === errorType) {
                        return;
                    }
                    var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
                    if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
                        // The promise type was not a valid type reference to the global promise type, so we
                        // report an error and return the unknown type.
                        error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
                        return;
                    }
                }
                else {
                    // Always mark the type node as referenced if it points to a value
                    markTypeNodeAsReferenced(returnTypeNode);
                    if (returnType === errorType) {
                        return;
                    }
                    var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
                    if (promiseConstructorName === undefined) {
                        error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType));
                        return;
                    }
                    var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true);
                    var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
                    if (promiseConstructorType === errorType) {
                        if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
                            error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
                        }
                        else {
                            error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
                        }
                        return;
                    }
                    var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
                    if (globalPromiseConstructorLikeType === emptyObjectType) {
                        // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
                        // compatibility with __awaiter.
                        error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
                        return;
                    }
                    if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) {
                        return;
                    }
                    // Verify there is no local declaration that could collide with the promise constructor.
                    var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName);
                    var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */);
                    if (collidingSymbol) {
                        error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
                        return;
                    }
                }
                checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
            }
            /** Check a decorator */
            function checkDecorator(node) {
                var signature = getResolvedSignature(node);
                var returnType = getReturnTypeOfSignature(signature);
                if (returnType.flags & 1 /* Any */) {
                    return;
                }
                var expectedReturnType;
                var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
                var errorInfo;
                switch (node.parent.kind) {
                    case 238 /* ClassDeclaration */:
                        var classSymbol = getSymbolOfNode(node.parent);
                        var classConstructorType = getTypeOfSymbol(classSymbol);
                        expectedReturnType = getUnionType([classConstructorType, voidType]);
                        break;
                    case 149 /* Parameter */:
                        expectedReturnType = voidType;
                        errorInfo = ts.chainDiagnosticMessages(
                        /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
                        break;
                    case 152 /* PropertyDeclaration */:
                        expectedReturnType = voidType;
                        errorInfo = ts.chainDiagnosticMessages(
                        /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
                        break;
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        var methodType = getTypeOfNode(node.parent);
                        var descriptorType = createTypedPropertyDescriptorType(methodType);
                        expectedReturnType = getUnionType([descriptorType, voidType]);
                        break;
                    default:
                        return ts.Debug.fail();
                }
                checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
            }
            /**
             * If a TypeNode can be resolved to a value symbol imported from an external module, it is
             * marked as referenced to prevent import elision.
             */
            function markTypeNodeAsReferenced(node) {
                markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
            }
            function markEntityNameOrEntityExpressionAsReference(typeName) {
                if (!typeName)
                    return;
                var rootName = getFirstIdentifier(typeName);
                var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
                var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
                if (rootSymbol
                    && rootSymbol.flags & 2097152 /* Alias */
                    && symbolIsValue(rootSymbol)
                    && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) {
                    markAliasSymbolAsReferenced(rootSymbol);
                }
            }
            /**
             * This function marks the type used for metadata decorator as referenced if it is import
             * from external module.
             * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
             * union and intersection type
             * @param node
             */
            function markDecoratorMedataDataTypeNodeAsReferenced(node) {
                var entityName = getEntityNameForDecoratorMetadata(node);
                if (entityName && ts.isEntityName(entityName)) {
                    markEntityNameOrEntityExpressionAsReference(entityName);
                }
            }
            function getEntityNameForDecoratorMetadata(node) {
                if (node) {
                    switch (node.kind) {
                        case 172 /* IntersectionType */:
                        case 171 /* UnionType */:
                            var commonEntityName = void 0;
                            for (var _i = 0, _a = node.types; _i < _a.length; _i++) {
                                var typeNode = _a[_i];
                                while (typeNode.kind === 175 /* ParenthesizedType */) {
                                    typeNode = typeNode.type; // Skip parens if need be
                                }
                                if (typeNode.kind === 131 /* NeverKeyword */) {
                                    continue; // Always elide `never` from the union/intersection if possible
                                }
                                if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) {
                                    continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
                                }
                                var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
                                if (!individualEntityName) {
                                    // Individual is something like string number
                                    // So it would be serialized to either that type or object
                                    // Safe to return here
                                    return undefined;
                                }
                                if (commonEntityName) {
                                    // Note this is in sync with the transformation that happens for type node.
                                    // Keep this in sync with serializeUnionOrIntersectionType
                                    // Verify if they refer to same entity and is identifier
                                    // return undefined if they dont match because we would emit object
                                    if (!ts.isIdentifier(commonEntityName) ||
                                        !ts.isIdentifier(individualEntityName) ||
                                        commonEntityName.escapedText !== individualEntityName.escapedText) {
                                        return undefined;
                                    }
                                }
                                else {
                                    commonEntityName = individualEntityName;
                                }
                            }
                            return commonEntityName;
                        case 175 /* ParenthesizedType */:
                            return getEntityNameForDecoratorMetadata(node.type);
                        case 162 /* TypeReference */:
                            return node.typeName;
                    }
                }
            }
            function getParameterTypeNodeForDecoratorCheck(node) {
                var typeNode = ts.getEffectiveTypeAnnotationNode(node);
                return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
            }
            /** Check the decorators of a node */
            function checkDecorators(node) {
                if (!node.decorators) {
                    return;
                }
                // skip this check for nodes that cannot have decorators. These should have already had an error reported by
                // checkGrammarDecorators.
                if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
                    return;
                }
                if (!compilerOptions.experimentalDecorators) {
                    error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning);
                }
                var firstDecorator = node.decorators[0];
                checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
                if (node.kind === 149 /* Parameter */) {
                    checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
                }
                if (compilerOptions.emitDecoratorMetadata) {
                    checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
                    // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
                    switch (node.kind) {
                        case 238 /* ClassDeclaration */:
                            var constructor = ts.getFirstConstructorWithBody(node);
                            if (constructor) {
                                for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
                                    var parameter = _a[_i];
                                    markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
                                }
                            }
                            break;
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */;
                            var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
                            markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
                            break;
                        case 154 /* MethodDeclaration */:
                            for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
                                var parameter = _c[_b];
                                markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
                            }
                            markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
                            break;
                        case 152 /* PropertyDeclaration */:
                            markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
                            break;
                        case 149 /* Parameter */:
                            markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
                            var containingSignature = node.parent;
                            for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
                                var parameter = _e[_d];
                                markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
                            }
                            break;
                    }
                }
                ts.forEach(node.decorators, checkDecorator);
            }
            function checkFunctionDeclaration(node) {
                if (produceDiagnostics) {
                    checkFunctionOrMethodDeclaration(node);
                    checkGrammarForGenerator(node);
                    checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
                    checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
                }
            }
            function checkJSDocTypeAliasTag(node) {
                if (!node.typeExpression) {
                    // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
                    error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
                }
                if (node.name) {
                    checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
                }
                checkSourceElement(node.typeExpression);
            }
            function checkJSDocTemplateTag(node) {
                checkSourceElement(node.constraint);
                for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
                    var tp = _a[_i];
                    checkSourceElement(tp);
                }
            }
            function checkJSDocTypeTag(node) {
                checkSourceElement(node.typeExpression);
            }
            function checkJSDocParameterTag(node) {
                checkSourceElement(node.typeExpression);
                if (!ts.getParameterSymbolFromJSDoc(node)) {
                    var decl = ts.getHostSignatureFromJSDoc(node);
                    // don't issue an error for invalid hosts -- just functions --
                    // and give a better error message when the host function mentions `arguments`
                    // but the tag doesn't have an array type
                    if (decl) {
                        var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
                        if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
                            return;
                        }
                        if (!containsArgumentsReference(decl)) {
                            error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name));
                        }
                        else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
                            node.typeExpression && node.typeExpression.type &&
                            !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
                            error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name));
                        }
                    }
                }
            }
            function checkJSDocAugmentsTag(node) {
                var classLike = ts.getJSDocHost(node);
                if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
                    error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
                    return;
                }
                var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
                ts.Debug.assert(augmentsTags.length > 0);
                if (augmentsTags.length > 1) {
                    error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
                }
                var name = getIdentifierFromEntityNameExpression(node.class.expression);
                var extend = ts.getClassExtendsHeritageElement(classLike);
                if (extend) {
                    var className = getIdentifierFromEntityNameExpression(extend.expression);
                    if (className && name.escapedText !== className.escapedText) {
                        error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
                    }
                }
            }
            function getIdentifierFromEntityNameExpression(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return node;
                    case 187 /* PropertyAccessExpression */:
                        return node.name;
                    default:
                        return undefined;
                }
            }
            function checkFunctionOrMethodDeclaration(node) {
                checkDecorators(node);
                checkSignatureDeclaration(node);
                var functionFlags = ts.getFunctionFlags(node);
                // Do not use hasDynamicName here, because that returns false for well known symbols.
                // We want to perform checkComputedPropertyName for all computed properties, including
                // well known symbols.
                if (node.name && node.name.kind === 147 /* ComputedPropertyName */) {
                    // This check will account for methods in class/interface declarations,
                    // as well as accessors in classes/object literals
                    checkComputedPropertyName(node.name);
                }
                if (!hasNonBindableDynamicName(node)) {
                    // first we want to check the local symbol that contain this declaration
                    // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
                    // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
                    var symbol = getSymbolOfNode(node);
                    var localSymbol = node.localSymbol || symbol;
                    // Since the javascript won't do semantic analysis like typescript,
                    // if the javascript file comes before the typescript file and both contain same name functions,
                    // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
                    var firstDeclaration = ts.find(localSymbol.declarations, 
                    // Get first non javascript function declaration
                    function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); });
                    // Only type check the symbol once
                    if (node === firstDeclaration) {
                        checkFunctionOrConstructorSymbol(localSymbol);
                    }
                    if (symbol.parent) {
                        // run check once for the first declaration
                        if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
                            // run check on export symbol to check that modifiers agree across all exported declarations
                            checkFunctionOrConstructorSymbol(symbol);
                        }
                    }
                }
                var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body;
                checkSourceElement(body);
                if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function
                    var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags);
                    checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
                }
                if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
                    // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
                    // in an ambient context
                    if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
                        reportImplicitAnyError(node, anyType);
                    }
                    if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
                        // A generator with a body and no type annotation can still cause errors. It can error if the
                        // yielded values have no common supertype, or it can give an implicit any error if it has no
                        // yielded values. The only way to trigger these errors is to try checking its return type.
                        getReturnTypeOfSignature(getSignatureFromDeclaration(node));
                    }
                }
                // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
                if (ts.isInJSFile(node)) {
                    var typeTag = ts.getJSDocTypeTag(node);
                    if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
                        error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
                    }
                }
            }
            function registerForUnusedIdentifiersCheck(node) {
                // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
                if (produceDiagnostics) {
                    var sourceFile = ts.getSourceFileOfNode(node);
                    var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
                    if (!potentiallyUnusedIdentifiers) {
                        potentiallyUnusedIdentifiers = [];
                        allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
                    }
                    // TODO: GH#22580
                    // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
                    potentiallyUnusedIdentifiers.push(node);
                }
            }
            function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
                for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
                    var node = potentiallyUnusedIdentifiers_1[_i];
                    switch (node.kind) {
                        case 238 /* ClassDeclaration */:
                        case 207 /* ClassExpression */:
                            checkUnusedClassMembers(node, addDiagnostic);
                            checkUnusedTypeParameters(node, addDiagnostic);
                            break;
                        case 239 /* InterfaceDeclaration */:
                            checkUnusedTypeParameters(node, addDiagnostic);
                            break;
                        case 277 /* SourceFile */:
                        case 242 /* ModuleDeclaration */:
                        case 216 /* Block */:
                        case 244 /* CaseBlock */:
                        case 223 /* ForStatement */:
                        case 224 /* ForInStatement */:
                        case 225 /* ForOfStatement */:
                            checkUnusedLocalsAndParameters(node, addDiagnostic);
                            break;
                        case 155 /* Constructor */:
                        case 194 /* FunctionExpression */:
                        case 237 /* FunctionDeclaration */:
                        case 195 /* ArrowFunction */:
                        case 154 /* MethodDeclaration */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            if (node.body) {
                                checkUnusedLocalsAndParameters(node, addDiagnostic);
                            }
                            checkUnusedTypeParameters(node, addDiagnostic);
                            break;
                        case 153 /* MethodSignature */:
                        case 158 /* CallSignature */:
                        case 159 /* ConstructSignature */:
                        case 163 /* FunctionType */:
                        case 164 /* ConstructorType */:
                        case 240 /* TypeAliasDeclaration */:
                        case 174 /* InferType */:
                            checkUnusedTypeParameters(node, addDiagnostic);
                            break;
                        default:
                            ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
                    }
                }
            }
            function errorUnusedLocal(declaration, name, addDiagnostic) {
                var node = ts.getNameOfDeclaration(declaration) || declaration;
                var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
                addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
            }
            function isIdentifierThatStartsWithUnderscore(node) {
                return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
            }
            function checkUnusedClassMembers(node, addDiagnostic) {
                if (!(node.flags & 4194304 /* Ambient */)) {
                    for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                        var member = _a[_i];
                        switch (member.kind) {
                            case 154 /* MethodDeclaration */:
                            case 152 /* PropertyDeclaration */:
                            case 156 /* GetAccessor */:
                            case 157 /* SetAccessor */:
                                if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
                                    // Already would have reported an error on the getter.
                                    break;
                                }
                                var symbol = getSymbolOfNode(member);
                                if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) {
                                    addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
                                }
                                break;
                            case 155 /* Constructor */:
                                for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
                                    var parameter = _c[_b];
                                    if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
                                        addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
                                    }
                                }
                                break;
                            case 160 /* IndexSignature */:
                            case 215 /* SemicolonClassElement */:
                                // Can't be private
                                break;
                            default:
                                ts.Debug.fail();
                        }
                    }
                }
            }
            function checkUnusedTypeParameters(node, addDiagnostic) {
                // Only report errors on the last declaration for the type parameter container;
                // this ensures that all uses have been accounted for.
                if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node)
                    return;
                if (node.kind === 174 /* InferType */) {
                    var typeParameter = node.typeParameter;
                    if (isTypeParameterUnused(typeParameter)) {
                        addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
                    }
                }
                else {
                    var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
                    var seenParentsWithEveryUnused = new ts.NodeSet();
                    for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
                        var typeParameter = typeParameters_2[_i];
                        if (!isTypeParameterUnused(typeParameter))
                            continue;
                        var name = ts.idText(typeParameter.name);
                        var parent = typeParameter.parent;
                        if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
                            if (seenParentsWithEveryUnused.tryAdd(parent)) {
                                var range = ts.isJSDocTemplateTag(parent)
                                    // Whole @template tag
                                    ? ts.rangeOfNode(parent)
                                    // Include the `<>` in the error message
                                    : ts.rangeOfTypeParameters(parent.typeParameters);
                                var only = typeParameters.length === 1;
                                var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
                                var arg0 = only ? name : undefined;
                                addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
                            }
                        }
                        else {
                            addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
                        }
                    }
                }
            }
            function isTypeParameterUnused(typeParameter) {
                return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
            }
            function addToGroup(map, key, value, getKey) {
                var keyString = String(getKey(key));
                var group = map.get(keyString);
                if (group) {
                    group[1].push(value);
                }
                else {
                    map.set(keyString, [key, [value]]);
                }
            }
            function tryGetRootParameterDeclaration(node) {
                return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
            }
            function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
                if (nodeWithLocals.flags & 4194304 /* Ambient */)
                    return;
                // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
                var unusedImports = ts.createMap();
                var unusedDestructures = ts.createMap();
                var unusedVariables = ts.createMap();
                nodeWithLocals.locals.forEach(function (local) {
                    // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
                    // If it's a type parameter merged with a parameter, check if the parameter-side is used.
                    if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
                        return;
                    }
                    for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
                        var declaration = _a[_i];
                        if (ts.isAmbientModule(declaration) ||
                            (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
                            continue;
                        }
                        if (isImportedDeclaration(declaration)) {
                            addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
                        }
                        else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
                            // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
                            var lastElement = ts.last(declaration.parent.elements);
                            if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
                                addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
                            }
                        }
                        else if (ts.isVariableDeclaration(declaration)) {
                            addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
                        }
                        else {
                            var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
                            var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
                            if (parameter && name) {
                                if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
                                    addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
                                }
                            }
                            else {
                                errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
                            }
                        }
                    }
                });
                unusedImports.forEach(function (_a) {
                    var importClause = _a[0], unuseds = _a[1];
                    var importDecl = importClause.parent;
                    var nDeclarations = (importClause.name ? 1 : 0) +
                        (importClause.namedBindings ?
                            (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
                            : 0);
                    if (nDeclarations === unuseds.length) {
                        addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
                            ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
                            : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
                    }
                    else {
                        for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
                            var unused = unuseds_1[_i];
                            errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
                        }
                    }
                });
                unusedDestructures.forEach(function (_a) {
                    var bindingPattern = _a[0], bindingElements = _a[1];
                    var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
                    if (bindingPattern.elements.length === bindingElements.length) {
                        if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) {
                            addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
                        }
                        else {
                            addDiagnostic(bindingPattern, kind, bindingElements.length === 1
                                ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
                                : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
                        }
                    }
                    else {
                        for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
                            var e = bindingElements_1[_i];
                            addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
                        }
                    }
                });
                unusedVariables.forEach(function (_a) {
                    var declarationList = _a[0], declarations = _a[1];
                    if (declarationList.declarations.length === declarations.length) {
                        addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
                            ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
                            : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
                    }
                    else {
                        for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
                            var decl = declarations_5[_i];
                            addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
                        }
                    }
                });
            }
            function bindingNameText(name) {
                switch (name.kind) {
                    case 71 /* Identifier */:
                        return ts.idText(name);
                    case 183 /* ArrayBindingPattern */:
                    case 182 /* ObjectBindingPattern */:
                        return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
                    default:
                        return ts.Debug.assertNever(name);
                }
            }
            function isImportedDeclaration(node) {
                return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */;
            }
            function importClauseFromImported(decl) {
                return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
            }
            function checkBlock(node) {
                // Grammar checking for SyntaxKind.Block
                if (node.kind === 216 /* Block */) {
                    checkGrammarStatementInAmbientContext(node);
                }
                if (ts.isFunctionOrModuleBlock(node)) {
                    var saveFlowAnalysisDisabled = flowAnalysisDisabled;
                    ts.forEach(node.statements, checkSourceElement);
                    flowAnalysisDisabled = saveFlowAnalysisDisabled;
                }
                else {
                    ts.forEach(node.statements, checkSourceElement);
                }
                if (node.locals) {
                    registerForUnusedIdentifiersCheck(node);
                }
            }
            function checkCollisionWithArgumentsInGeneratedCode(node) {
                // no rest parameters \ declaration context \ overload - no codegen impact
                if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) {
                    return;
                }
                ts.forEach(node.parameters, function (p) {
                    if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
                        error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
                    }
                });
            }
            function needCollisionCheckForIdentifier(node, identifier, name) {
                if (!(identifier && identifier.escapedText === name)) {
                    return false;
                }
                if (node.kind === 152 /* PropertyDeclaration */ ||
                    node.kind === 151 /* PropertySignature */ ||
                    node.kind === 154 /* MethodDeclaration */ ||
                    node.kind === 153 /* MethodSignature */ ||
                    node.kind === 156 /* GetAccessor */ ||
                    node.kind === 157 /* SetAccessor */) {
                    // it is ok to have member named '_super' or '_this' - member access is always qualified
                    return false;
                }
                if (node.flags & 4194304 /* Ambient */) {
                    // ambient context - no codegen impact
                    return false;
                }
                var root = ts.getRootDeclaration(node);
                if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
                    // just an overload - no codegen impact
                    return false;
                }
                return true;
            }
            // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
            function checkIfThisIsCapturedInEnclosingScope(node) {
                ts.findAncestor(node, function (current) {
                    if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
                        var isDeclaration_1 = node.kind !== 71 /* Identifier */;
                        if (isDeclaration_1) {
                            error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
                        }
                        else {
                            error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
                        }
                        return true;
                    }
                    return false;
                });
            }
            function checkIfNewTargetIsCapturedInEnclosingScope(node) {
                ts.findAncestor(node, function (current) {
                    if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
                        var isDeclaration_2 = node.kind !== 71 /* Identifier */;
                        if (isDeclaration_2) {
                            error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
                        }
                        else {
                            error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
                        }
                        return true;
                    }
                    return false;
                });
            }
            function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
                // No need to check for require or exports for ES6 modules and later
                if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
                    return;
                }
                if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
                    return;
                }
                // Uninstantiated modules shouldnt do this check
                if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
                    return;
                }
                // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
                var parent = getDeclarationContainer(node);
                if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
                    // If the declaration happens to be in external module, report error that require and exports are reserved keywords
                    error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
                }
            }
            function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
                if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
                    return;
                }
                // Uninstantiated modules shouldnt do this check
                if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
                    return;
                }
                // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
                var parent = getDeclarationContainer(node);
                if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
                    // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
                    error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
                }
            }
            function checkVarDeclaredNamesNotShadowed(node) {
                // - ScriptBody : StatementList
                // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
                // also occurs in the VarDeclaredNames of StatementList.
                // - Block : { StatementList }
                // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
                // also occurs in the VarDeclaredNames of StatementList.
                // Variable declarations are hoisted to the top of their function scope. They can shadow
                // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
                // by the binder as the declaration scope is different.
                // A non-initialized declaration is a no-op as the block declaration will resolve before the var
                // declaration. the problem is if the declaration has an initializer. this will act as a write to the
                // block declared value. this is fine for let, but not const.
                // Only consider declarations with initializers, uninitialized const declarations will not
                // step on a let/const variable.
                // Do not consider const and const declarations, as duplicate block-scoped declarations
                // are handled by the binder.
                // We are only looking for const declarations that step on let\const declarations from a
                // different scope. e.g.:
                //      {
                //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
                //          const x = 0; // symbol for this declaration will be 'symbol'
                //      }
                // skip block-scoped variables and parameters
                if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
                    return;
                }
                // skip variable declarations that don't have initializers
                // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
                // so we'll always treat binding elements as initialized
                if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) {
                    return;
                }
                var symbol = getSymbolOfNode(node);
                if (symbol.flags & 1 /* FunctionScopedVariable */) {
                    if (!ts.isIdentifier(node.name))
                        return ts.Debug.fail();
                    var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
                    if (localDeclarationSymbol &&
                        localDeclarationSymbol !== symbol &&
                        localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
                        if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
                            var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */);
                            var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent
                                ? varDeclList.parent.parent
                                : undefined;
                            // names of block-scoped and function scoped variables can collide only
                            // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
                            var namesShareScope = container &&
                                (container.kind === 216 /* Block */ && ts.isFunctionLike(container.parent) ||
                                    container.kind === 243 /* ModuleBlock */ ||
                                    container.kind === 242 /* ModuleDeclaration */ ||
                                    container.kind === 277 /* SourceFile */);
                            // here we know that function scoped variable is shadowed by block scoped one
                            // if they are defined in the same scope - binder has already reported redeclaration error
                            // otherwise if variable has an initializer - show error that initialization will fail
                            // since LHS will be block scoped name instead of function scoped
                            if (!namesShareScope) {
                                var name = symbolToString(localDeclarationSymbol);
                                error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
                            }
                        }
                    }
                }
            }
            // Check that a parameter initializer contains no references to parameters declared to the right of itself
            function checkParameterInitializer(node) {
                if (ts.getRootDeclaration(node).kind !== 149 /* Parameter */) {
                    return;
                }
                var func = ts.getContainingFunction(node);
                visit(node.initializer);
                function visit(n) {
                    if (ts.isTypeNode(n) || ts.isDeclarationName(n)) {
                        // do not dive in types
                        // skip declaration names (i.e. in object literal expressions)
                        return;
                    }
                    if (n.kind === 187 /* PropertyAccessExpression */) {
                        // skip property names in property access expression
                        return visit(n.expression);
                    }
                    else if (n.kind === 71 /* Identifier */) {
                        // check FunctionLikeDeclaration.locals (stores parameters\function local variable)
                        // if it contains entry with a specified name
                        var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
                        if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) {
                            return;
                        }
                        if (symbol.valueDeclaration === node) {
                            error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name));
                            return;
                        }
                        // locals map for function contain both parameters and function locals
                        // so we need to do a bit of extra work to check if reference is legal
                        var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
                        if (enclosingContainer === func) {
                            if (symbol.valueDeclaration.kind === 149 /* Parameter */ ||
                                symbol.valueDeclaration.kind === 184 /* BindingElement */) {
                                // it is ok to reference parameter in initializer if either
                                // - parameter is located strictly on the left of current parameter declaration
                                if (symbol.valueDeclaration.pos < node.pos) {
                                    return;
                                }
                                // - parameter is wrapped in function-like entity
                                if (ts.findAncestor(n, function (current) {
                                    if (current === node.initializer) {
                                        return "quit";
                                    }
                                    return ts.isFunctionLike(current.parent) ||
                                        // computed property names/initializers in instance property declaration of class like entities
                                        // are executed in constructor and thus deferred
                                        (current.parent.kind === 152 /* PropertyDeclaration */ &&
                                            !(ts.hasModifier(current.parent, 32 /* Static */)) &&
                                            ts.isClassLike(current.parent.parent));
                                })) {
                                    return;
                                }
                                // fall through to report error
                            }
                            error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n));
                        }
                    }
                    else {
                        return ts.forEachChild(n, visit);
                    }
                }
            }
            function convertAutoToAny(type) {
                return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
            }
            // Check variable, parameter, or property declaration
            function checkVariableLikeDeclaration(node) {
                checkDecorators(node);
                if (!ts.isBindingElement(node)) {
                    checkSourceElement(node.type);
                }
                // JSDoc `function(string, string): string` syntax results in parameters with no name
                if (!node.name) {
                    return;
                }
                // For a computed property, just check the initializer and exit
                // Do not use hasDynamicName here, because that returns false for well known symbols.
                // We want to perform checkComputedPropertyName for all computed properties, including
                // well known symbols.
                if (node.name.kind === 147 /* ComputedPropertyName */) {
                    checkComputedPropertyName(node.name);
                    if (node.initializer) {
                        checkExpressionCached(node.initializer);
                    }
                }
                if (node.kind === 184 /* BindingElement */) {
                    if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {
                        checkExternalEmitHelpers(node, 4 /* Rest */);
                    }
                    // check computed properties inside property names of binding elements
                    if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) {
                        checkComputedPropertyName(node.propertyName);
                    }
                    // check private/protected variable access
                    var parent = node.parent.parent;
                    var parentType = getTypeForBindingElementParent(parent);
                    var name = node.propertyName || node.name;
                    if (!ts.isBindingPattern(name)) {
                        var nameText = ts.getTextOfPropertyName(name);
                        if (nameText) {
                            var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217
                            markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
                            if (parent.initializer && property) {
                                checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property);
                            }
                        }
                    }
                }
                // For a binding pattern, check contained binding elements
                if (ts.isBindingPattern(node.name)) {
                    if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
                        checkExternalEmitHelpers(node, 512 /* Read */);
                    }
                    ts.forEach(node.name.elements, checkSourceElement);
                }
                // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
                if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
                    error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
                    return;
                }
                // For a binding pattern, validate the initializer and exit
                if (ts.isBindingPattern(node.name)) {
                    // Don't validate for-in initializer as it is already an error
                    if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) {
                        var initializerType = checkExpressionCached(node.initializer);
                        if (strictNullChecks && node.name.elements.length === 0) {
                            checkNonNullType(initializerType, node);
                        }
                        else {
                            checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
                        }
                        checkParameterInitializer(node);
                    }
                    return;
                }
                var symbol = getSymbolOfNode(node);
                var type = convertAutoToAny(getTypeOfSymbol(symbol));
                if (node === symbol.valueDeclaration) {
                    // Node is the primary declaration of the symbol, just validate the initializer
                    // Don't validate for-in initializer as it is already an error
                    var initializer = ts.getEffectiveInitializer(node);
                    if (initializer) {
                        var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
                            ts.isObjectLiteralExpression(initializer) &&
                            (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
                            ts.hasEntries(symbol.exports);
                        if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) {
                            checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
                            checkParameterInitializer(node);
                        }
                    }
                }
                else {
                    // Node is a secondary declaration, check that type is identical to primary declaration and check that
                    // initializer is consistent with type associated with the node
                    var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
                    if (type !== errorType && declarationType !== errorType &&
                        !isTypeIdenticalTo(type, declarationType) &&
                        !(symbol.flags & 67108864 /* Assignment */)) {
                        errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType);
                    }
                    if (node.initializer) {
                        checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
                    }
                    if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
                        error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
                        error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
                    }
                }
                if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) {
                    // We know we don't have a binding pattern or computed name here
                    checkExportsOnMergedDeclarations(node);
                    if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) {
                        checkVarDeclaredNamesNotShadowed(node);
                    }
                    checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
                    checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
                }
            }
            function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) {
                var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
                var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */
                    ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
                    : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
                error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType));
            }
            function areDeclarationFlagsIdentical(left, right) {
                if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) ||
                    (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) {
                    // Differences in optionality between parameters and variables are allowed.
                    return true;
                }
                if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
                    return false;
                }
                var interestingFlags = 8 /* Private */ |
                    16 /* Protected */ |
                    256 /* Async */ |
                    128 /* Abstract */ |
                    64 /* Readonly */ |
                    32 /* Static */;
                return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
            }
            function checkVariableDeclaration(node) {
                checkGrammarVariableDeclaration(node);
                return checkVariableLikeDeclaration(node);
            }
            function checkBindingElement(node) {
                checkGrammarBindingElement(node);
                return checkVariableLikeDeclaration(node);
            }
            function checkVariableStatement(node) {
                // Grammar checking
                if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
                    checkGrammarForDisallowedLetOrConstStatement(node);
                ts.forEach(node.declarationList.declarations, checkSourceElement);
            }
            function checkExpressionStatement(node) {
                // Grammar checking
                checkGrammarStatementInAmbientContext(node);
                checkExpression(node.expression);
            }
            function checkIfStatement(node) {
                // Grammar checking
                checkGrammarStatementInAmbientContext(node);
                checkTruthinessExpression(node.expression);
                checkSourceElement(node.thenStatement);
                if (node.thenStatement.kind === 218 /* EmptyStatement */) {
                    error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
                }
                checkSourceElement(node.elseStatement);
            }
            function checkDoStatement(node) {
                // Grammar checking
                checkGrammarStatementInAmbientContext(node);
                checkSourceElement(node.statement);
                checkTruthinessExpression(node.expression);
            }
            function checkWhileStatement(node) {
                // Grammar checking
                checkGrammarStatementInAmbientContext(node);
                checkTruthinessExpression(node.expression);
                checkSourceElement(node.statement);
            }
            function checkTruthinessExpression(node, checkMode) {
                var type = checkExpression(node, checkMode);
                if (type.flags & 4096 /* Void */) {
                    error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
                }
                return type;
            }
            function checkForStatement(node) {
                // Grammar checking
                if (!checkGrammarStatementInAmbientContext(node)) {
                    if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) {
                        checkGrammarVariableDeclarationList(node.initializer);
                    }
                }
                if (node.initializer) {
                    if (node.initializer.kind === 236 /* VariableDeclarationList */) {
                        ts.forEach(node.initializer.declarations, checkVariableDeclaration);
                    }
                    else {
                        checkExpression(node.initializer);
                    }
                }
                if (node.condition)
                    checkTruthinessExpression(node.condition);
                if (node.incrementor)
                    checkExpression(node.incrementor);
                checkSourceElement(node.statement);
                if (node.locals) {
                    registerForUnusedIdentifiersCheck(node);
                }
            }
            function checkForOfStatement(node) {
                checkGrammarForInOrForOfStatement(node);
                if (node.awaitModifier) {
                    var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
                    if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) {
                        // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
                        checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
                    }
                }
                else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
                    // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
                    checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
                }
                // Check the LHS and RHS
                // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
                // via checkRightHandSideOfForOf.
                // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
                // Then check that the RHS is assignable to it.
                if (node.initializer.kind === 236 /* VariableDeclarationList */) {
                    checkForInOrForOfVariableDeclaration(node);
                }
                else {
                    var varExpr = node.initializer;
                    var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier);
                    // There may be a destructuring assignment on the left side
                    if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) {
                        // iteratedType may be undefined. In this case, we still want to check the structure of
                        // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
                        // to short circuit the type relation checking as much as possible, so we pass the unknownType.
                        checkDestructuringAssignment(varExpr, iteratedType || errorType);
                    }
                    else {
                        var leftType = checkExpression(varExpr);
                        checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access);
                        // iteratedType will be undefined if the rightType was missing properties/signatures
                        // required to get its iteratedType (like [Symbol.iterator] or next). This may be
                        // because we accessed properties from anyType, or it may have led to an error inside
                        // getElementTypeOfIterable.
                        if (iteratedType) {
                            checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
                        }
                    }
                }
                checkSourceElement(node.statement);
                if (node.locals) {
                    registerForUnusedIdentifiersCheck(node);
                }
            }
            function checkForInStatement(node) {
                // Grammar checking
                checkGrammarForInOrForOfStatement(node);
                var rightType = checkNonNullExpression(node.expression);
                // TypeScript 1.0 spec (April 2014): 5.4
                // In a 'for-in' statement of the form
                // for (let VarDecl in Expr) Statement
                //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
                //   and Expr must be an expression of type Any, an object type, or a type parameter type.
                if (node.initializer.kind === 236 /* VariableDeclarationList */) {
                    var variable = node.initializer.declarations[0];
                    if (variable && ts.isBindingPattern(variable.name)) {
                        error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
                    }
                    checkForInOrForOfVariableDeclaration(node);
                }
                else {
                    // In a 'for-in' statement of the form
                    // for (Var in Expr) Statement
                    //   Var must be an expression classified as a reference of type Any or the String primitive type,
                    //   and Expr must be an expression of type Any, an object type, or a type parameter type.
                    var varExpr = node.initializer;
                    var leftType = checkExpression(varExpr);
                    if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) {
                        error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
                    }
                    else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
                        error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
                    }
                    else {
                        // run check only former check succeeded to avoid cascading errors
                        checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access);
                    }
                }
                // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
                // in this case error about missing name is already reported - do not report extra one
                if (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) {
                    error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType));
                }
                checkSourceElement(node.statement);
                if (node.locals) {
                    registerForUnusedIdentifiersCheck(node);
                }
            }
            function checkForInOrForOfVariableDeclaration(iterationStatement) {
                var variableDeclarationList = iterationStatement.initializer;
                // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
                if (variableDeclarationList.declarations.length >= 1) {
                    var decl = variableDeclarationList.declarations[0];
                    checkVariableDeclaration(decl);
                }
            }
            function checkRightHandSideOfForOf(rhsExpression, awaitModifier) {
                var expressionType = checkNonNullExpression(rhsExpression);
                return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined);
            }
            function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) {
                if (isTypeAny(inputType)) {
                    return inputType;
                }
                return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType;
            }
            /**
             * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
             * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
             * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
             */
            function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) {
                if (inputType === neverType) {
                    reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
                    return undefined;
                }
                var uplevelIteration = languageVersion >= 2 /* ES2015 */;
                var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
                // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
                // or higher, when inside of an async generator or for-await-if, or when
                // downlevelIteration is requested.
                if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
                    // We only report errors for an invalid iterable type in ES2015 or higher.
                    var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability);
                    if (iteratedType || uplevelIteration) {
                        return iteratedType;
                    }
                }
                var arrayType = inputType;
                var reportedError = false;
                var hasStringConstituent = false;
                // If strings are permitted, remove any string-like constituents from the array type.
                // This allows us to find other non-string element types from an array unioned with
                // a string.
                if (allowStringInput) {
                    if (arrayType.flags & 262144 /* Union */) {
                        // After we remove all types that are StringLike, we will know if there was a string constituent
                        // based on whether the result of filter is a new array.
                        var arrayTypes = inputType.types;
                        var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); });
                        if (filteredTypes !== arrayTypes) {
                            arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
                        }
                    }
                    else if (arrayType.flags & 68 /* StringLike */) {
                        arrayType = neverType;
                    }
                    hasStringConstituent = arrayType !== inputType;
                    if (hasStringConstituent) {
                        if (languageVersion < 1 /* ES5 */) {
                            if (errorNode) {
                                error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
                                reportedError = true;
                            }
                        }
                        // Now that we've removed all the StringLike types, if no constituents remain, then the entire
                        // arrayOrStringType was a string.
                        if (arrayType.flags & 32768 /* Never */) {
                            return stringType;
                        }
                    }
                }
                if (!isArrayLikeType(arrayType)) {
                    if (errorNode && !reportedError) {
                        // Which error we report depends on whether we allow strings or if there was a
                        // string constituent. For example, if the input type is number | string, we
                        // want to say that number is not an array type. But if the input was just
                        // number and string input is allowed, we want to say that number is not an
                        // array type or a string type.
                        var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability);
                        var diagnostic = !allowStringInput || hasStringConstituent
                            ? downlevelIteration
                                ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
                                : isIterable
                                    ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
                                    : ts.Diagnostics.Type_0_is_not_an_array_type
                            : downlevelIteration
                                ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
                                : isIterable
                                    ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
                                    : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type;
                        error(errorNode, diagnostic, typeToString(arrayType));
                    }
                    return hasStringConstituent ? stringType : undefined;
                }
                var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
                if (hasStringConstituent && arrayElementType) {
                    // This is just an optimization for the case where arrayOrStringType is string | string[]
                    if (arrayElementType.flags & 68 /* StringLike */) {
                        return stringType;
                    }
                    return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
                }
                return arrayElementType;
            }
            /**
             * We want to treat type as an iterable, and get the type it is an iterable of. The iterable
             * must have the following structure (annotated with the names of the variables below):
             *
             *     { // iterable
             *         [Symbol.iterator]: { // iteratorMethod
             *             (): Iterator<T>
             *         }
             *     }
             *
             * For an async iterable, we expect the following structure:
             *
             *     { // iterable
             *         [Symbol.asyncIterator]: { // iteratorMethod
             *             (): AsyncIterator<T>
             *         }
             *     }
             *
             * T is the type we are after. At every level that involves analyzing return types
             * of signatures, we union the return types of all the signatures.
             *
             * Another thing to note is that at any step of this process, we could run into a dead end,
             * meaning either the property is missing, or we run into the anyType. If either of these things
             * happens, we return undefined to signal that we could not find the iterated type. If a property
             * is missing, and the previous step did not result in 'any', then we also give an error if the
             * caller requested it. Then the caller can decide what to do in the case where there is no iterated
             * type. This is different from returning anyType, because that would signify that we have matched the
             * whole pattern and that T (above) is 'any'.
             *
             * For a **for-of** statement, `yield*` (in a normal generator), spread, array
             * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
             * method.
             *
             * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
             *
             * For a **for-await-of** statement or a `yield*` in an async generator we will look for
             * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
             */
            function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) {
                if (isTypeAny(type)) {
                    return undefined;
                }
                return mapType(type, getIteratedType);
                function getIteratedType(type) {
                    var typeAsIterable = type;
                    if (allowAsyncIterables) {
                        if (typeAsIterable.iteratedTypeOfAsyncIterable) {
                            return typeAsIterable.iteratedTypeOfAsyncIterable;
                        }
                        // As an optimization, if the type is an instantiation of the global `AsyncIterable<T>`
                        // or the global `AsyncIterableIterator<T>` then just grab its type argument.
                        if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) ||
                            isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) {
                            return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0];
                        }
                    }
                    if (allowSyncIterables) {
                        if (typeAsIterable.iteratedTypeOfIterable) {
                            return typeAsIterable.iteratedTypeOfIterable;
                        }
                        // As an optimization, if the type is an instantiation of the global `Iterable<T>` or
                        // `IterableIterator<T>` then just grab its type argument.
                        if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) ||
                            isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) {
                            return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0];
                        }
                    }
                    var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator"));
                    var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined);
                    if (isTypeAny(methodType)) {
                        return undefined;
                    }
                    var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
                    if (!ts.some(signatures)) {
                        if (errorNode) {
                            // only report on the first error
                            reportTypeNotIterableError(errorNode, type, allowAsyncIterables);
                            errorNode = undefined;
                        }
                        return undefined;
                    }
                    var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
                    var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType);
                    if (checkAssignability && errorNode && iteratedType) {
                        // If `checkAssignability` was specified, we were called from
                        // `checkIteratedTypeOrElementType`. As such, we need to validate that
                        // the type passed in is actually an Iterable.
                        checkTypeAssignableTo(type, asyncMethodType
                            ? createAsyncIterableType(iteratedType)
                            : createIterableType(iteratedType), errorNode);
                    }
                    return asyncMethodType
                        ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType
                        : typeAsIterable.iteratedTypeOfIterable = iteratedType;
                }
            }
            function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
                error(errorNode, allowAsyncIterables
                    ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
                    : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type));
            }
            /**
             * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on
             * Iterators instead of Iterables. Here is the structure:
             *
             *  { // iterator
             *      next: { // nextMethod
             *          (): { // nextResult
             *              value: T // nextValue
             *          }
             *      }
             *  }
             *
             * For an async iterator, we expect the following structure:
             *
             *  { // iterator
             *      next: { // nextMethod
             *          (): PromiseLike<{ // nextResult
             *              value: T // nextValue
             *          }>
             *      }
             *  }
             */
            function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) {
                if (isTypeAny(type)) {
                    return undefined;
                }
                var typeAsIterator = type;
                if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) {
                    return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator;
                }
                // As an optimization, if the type is an instantiation of the global `Iterator<T>` (for
                // a non-async iterator) or the global `AsyncIterator<T>` (for an async-iterator) then
                // just grab its type argument.
                var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType;
                if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) {
                    return isAsyncIterator
                        ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0]
                        : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0];
                }
                // Both async and non-async iterators must have a `next` method.
                var nextMethod = getTypeOfPropertyOfType(type, "next");
                if (isTypeAny(nextMethod)) {
                    return undefined;
                }
                var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray;
                if (nextMethodSignatures.length === 0) {
                    if (errorNode) {
                        error(errorNode, isAsyncIterator
                            ? ts.Diagnostics.An_async_iterator_must_have_a_next_method
                            : ts.Diagnostics.An_iterator_must_have_a_next_method);
                    }
                    return undefined;
                }
                var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */);
                if (isTypeAny(nextResult)) {
                    return undefined;
                }
                // For an async iterator, we must get the awaited type of the return type.
                if (isAsyncIterator) {
                    nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property);
                    if (isTypeAny(nextResult)) {
                        return undefined;
                    }
                }
                var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value");
                if (!nextValue) {
                    if (errorNode) {
                        error(errorNode, isAsyncIterator
                            ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property
                            : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property);
                    }
                    return undefined;
                }
                return isAsyncIterator
                    ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue
                    : typeAsIterator.iteratedTypeOfIterator = nextValue;
            }
            /**
             * A generator may have a return type of `Iterator<T>`, `Iterable<T>`, or
             * `IterableIterator<T>`. An async generator may have a return type of `AsyncIterator<T>`,
             * `AsyncIterable<T>`, or `AsyncIterableIterator<T>`. This function can be used to extract
             * the iterated type from this return type for contextual typing and verifying signatures.
             */
            function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) {
                if (isTypeAny(returnType)) {
                    return undefined;
                }
                return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false)
                    || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator);
            }
            function checkBreakOrContinueStatement(node) {
                // Grammar checking
                if (!checkGrammarStatementInAmbientContext(node))
                    checkGrammarBreakOrContinueStatement(node);
                // TODO: Check that target label is valid
            }
            function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
                var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */
                    ? getPromisedTypeOfPromise(returnType) // Async function
                    : returnType; // AsyncGenerator function, Generator function, or normal function
                return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */);
            }
            function checkReturnStatement(node) {
                // Grammar checking
                if (checkGrammarStatementInAmbientContext(node)) {
                    return;
                }
                var func = ts.getContainingFunction(node);
                if (!func) {
                    grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
                    return;
                }
                var signature = getSignatureFromDeclaration(func);
                var returnType = getReturnTypeOfSignature(signature);
                var functionFlags = ts.getFunctionFlags(func);
                var isGenerator = functionFlags & 1 /* Generator */;
                if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) {
                    var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
                    if (isGenerator) { // AsyncGenerator function or Generator function
                        // A generator does not need its return expressions checked against its return type.
                        // Instead, the yield expressions are checked against the element type.
                        // TODO: Check return types of generators when return type tracking is added
                        // for generators.
                        return;
                    }
                    else if (func.kind === 157 /* SetAccessor */) {
                        if (node.expression) {
                            error(node, ts.Diagnostics.Setters_cannot_return_a_value);
                        }
                    }
                    else if (func.kind === 155 /* Constructor */) {
                        if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
                            error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
                        }
                    }
                    else if (getReturnTypeFromAnnotation(func)) {
                        if (functionFlags & 2 /* Async */) { // Async function
                            var promisedType = getPromisedTypeOfPromise(returnType);
                            var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
                            if (promisedType) {
                                // If the function has a return type, but promisedType is
                                // undefined, an error will be reported in checkAsyncFunctionReturnType
                                // so we don't need to report one here.
                                checkTypeAssignableTo(awaitedType, promisedType, node);
                            }
                        }
                        else {
                            checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression);
                        }
                    }
                }
                else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) {
                    // The function has a return type, but the return statement doesn't have an expression.
                    error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
                }
            }
            function checkWithStatement(node) {
                // Grammar checking for withStatement
                if (!checkGrammarStatementInAmbientContext(node)) {
                    if (node.flags & 16384 /* AwaitContext */) {
                        grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
                    }
                }
                checkExpression(node.expression);
                var sourceFile = ts.getSourceFileOfNode(node);
                if (!hasParseDiagnostics(sourceFile)) {
                    var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
                    var end = node.statement.pos;
                    grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
                }
            }
            function checkSwitchStatement(node) {
                // Grammar checking
                checkGrammarStatementInAmbientContext(node);
                var firstDefaultClause;
                var hasDuplicateDefaultClause = false;
                var expressionType = checkExpression(node.expression);
                var expressionIsLiteral = isLiteralType(expressionType);
                ts.forEach(node.caseBlock.clauses, function (clause) {
                    // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
                    if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) {
                        if (firstDefaultClause === undefined) {
                            firstDefaultClause = clause;
                        }
                        else {
                            var sourceFile = ts.getSourceFileOfNode(node);
                            var start = ts.skipTrivia(sourceFile.text, clause.pos);
                            var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end;
                            grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
                            hasDuplicateDefaultClause = true;
                        }
                    }
                    if (produceDiagnostics && clause.kind === 269 /* CaseClause */) {
                        // TypeScript 1.0 spec (April 2014): 5.9
                        // In a 'switch' statement, each 'case' expression must be of a type that is comparable
                        // to or from the type of the 'switch' expression.
                        var caseType = checkExpression(clause.expression);
                        var caseIsLiteral = isLiteralType(caseType);
                        var comparedExpressionType = expressionType;
                        if (!caseIsLiteral || !expressionIsLiteral) {
                            caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
                            comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
                        }
                        if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
                            // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
                            checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
                        }
                    }
                    ts.forEach(clause.statements, checkSourceElement);
                });
                if (node.caseBlock.locals) {
                    registerForUnusedIdentifiersCheck(node.caseBlock);
                }
            }
            function checkLabeledStatement(node) {
                // Grammar checking
                if (!checkGrammarStatementInAmbientContext(node)) {
                    ts.findAncestor(node.parent, function (current) {
                        if (ts.isFunctionLike(current)) {
                            return "quit";
                        }
                        if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
                            grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
                            return true;
                        }
                        return false;
                    });
                }
                // ensure that label is unique
                checkSourceElement(node.statement);
            }
            function checkThrowStatement(node) {
                // Grammar checking
                if (!checkGrammarStatementInAmbientContext(node)) {
                    if (node.expression === undefined) {
                        grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
                    }
                }
                if (node.expression) {
                    checkExpression(node.expression);
                }
            }
            function checkTryStatement(node) {
                // Grammar checking
                checkGrammarStatementInAmbientContext(node);
                checkBlock(node.tryBlock);
                var catchClause = node.catchClause;
                if (catchClause) {
                    // Grammar checking
                    if (catchClause.variableDeclaration) {
                        if (catchClause.variableDeclaration.type) {
                            grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
                        }
                        else if (catchClause.variableDeclaration.initializer) {
                            grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
                        }
                        else {
                            var blockLocals_1 = catchClause.block.locals;
                            if (blockLocals_1) {
                                ts.forEachKey(catchClause.locals, function (caughtName) {
                                    var blockLocal = blockLocals_1.get(caughtName);
                                    if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
                                        grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
                                    }
                                });
                            }
                        }
                    }
                    checkBlock(catchClause.block);
                }
                if (node.finallyBlock) {
                    checkBlock(node.finallyBlock);
                }
            }
            function checkIndexConstraints(type) {
                var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
                var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
                var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
                var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
                if (stringIndexType || numberIndexType) {
                    ts.forEach(getPropertiesOfObjectType(type), function (prop) {
                        var propType = getTypeOfSymbol(prop);
                        checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
                        checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
                    });
                    var classDeclaration = type.symbol.valueDeclaration;
                    if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
                        for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
                            var member = _a[_i];
                            // Only process instance properties with computed names here.
                            // Static properties cannot be in conflict with indexers,
                            // and properties with literal names were already checked.
                            if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
                                var symbol = getSymbolOfNode(member);
                                var propType = getTypeOfSymbol(symbol);
                                checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
                                checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
                            }
                        }
                    }
                }
                var errorNode;
                if (stringIndexType && numberIndexType) {
                    errorNode = declaredNumberIndexer || declaredStringIndexer;
                    // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
                    if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
                        var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
                        errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
                    }
                }
                if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
                    error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
                }
                function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
                    // ESSymbol properties apply to neither string nor numeric indexers.
                    if (!indexType || ts.isKnownSymbol(prop)) {
                        return;
                    }
                    var propDeclaration = prop.valueDeclaration;
                    var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
                    // index is numeric and property name is not valid numeric literal
                    if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
                        return;
                    }
                    // perform property check if property or indexer is declared in 'type'
                    // this allows us to rule out cases when both property and indexer are inherited from the base class
                    var errorNode;
                    if (propDeclaration && name &&
                        (propDeclaration.kind === 202 /* BinaryExpression */ ||
                            name.kind === 147 /* ComputedPropertyName */ ||
                            prop.parent === containingType.symbol)) {
                        errorNode = propDeclaration;
                    }
                    else if (indexDeclaration) {
                        errorNode = indexDeclaration;
                    }
                    else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
                        // for interfaces property and indexer might be inherited from different bases
                        // check if any base class already has both property and indexer.
                        // check should be performed only if 'type' is the first type that brings property\indexer together
                        var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
                        errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
                    }
                    if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
                        var errorMessage = indexKind === 0 /* String */
                            ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
                            : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
                        error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
                    }
                }
            }
            function checkTypeNameIsReserved(name, message) {
                // TS 1.0 spec (April 2014): 3.6.1
                // The predefined type keywords are reserved and cannot be used as names of user defined types.
                switch (name.escapedText) {
                    case "any":
                    case "unknown":
                    case "number":
                    case "boolean":
                    case "string":
                    case "symbol":
                    case "void":
                    case "object":
                        error(name, message, name.escapedText);
                }
            }
            /**
             * The name cannot be used as 'Object' of user defined types with special target.
             */
            function checkClassNameCollisionWithObject(name) {
                if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
                    && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) {
                    error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494
                }
            }
            /**
             * Check each type parameter and check that type parameters have no duplicate type parameter declarations
             */
            function checkTypeParameters(typeParameterDeclarations) {
                if (typeParameterDeclarations) {
                    var seenDefault = false;
                    for (var i = 0; i < typeParameterDeclarations.length; i++) {
                        var node = typeParameterDeclarations[i];
                        checkTypeParameter(node);
                        if (produceDiagnostics) {
                            if (node.default) {
                                seenDefault = true;
                            }
                            else if (seenDefault) {
                                error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
                            }
                            for (var j = 0; j < i; j++) {
                                if (typeParameterDeclarations[j].symbol === node.symbol) {
                                    error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
                                }
                            }
                        }
                    }
                }
            }
            /** Check that type parameter lists are identical across multiple declarations */
            function checkTypeParameterListsIdentical(symbol) {
                if (symbol.declarations.length === 1) {
                    return;
                }
                var links = getSymbolLinks(symbol);
                if (!links.typeParametersChecked) {
                    links.typeParametersChecked = true;
                    var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
                    if (declarations.length <= 1) {
                        return;
                    }
                    var type = getDeclaredTypeOfSymbol(symbol);
                    if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
                        // Report an error on every conflicting declaration.
                        var name = symbolToString(symbol);
                        for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
                            var declaration = declarations_6[_i];
                            error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
                        }
                    }
                }
            }
            function areTypeParametersIdentical(declarations, targetParameters) {
                var maxTypeArgumentCount = ts.length(targetParameters);
                var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
                for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
                    var declaration = declarations_7[_i];
                    // If this declaration has too few or too many type parameters, we report an error
                    var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
                    var numTypeParameters = sourceParameters.length;
                    if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
                        return false;
                    }
                    for (var i = 0; i < numTypeParameters; i++) {
                        var source = sourceParameters[i];
                        var target = targetParameters[i];
                        // If the type parameter node does not have the same as the resolved type
                        // parameter at this position, we report an error.
                        if (source.name.escapedText !== target.symbol.escapedName) {
                            return false;
                        }
                        // If the type parameter node does not have an identical constraint as the resolved
                        // type parameter at this position, we report an error.
                        var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
                        var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
                        var targetConstraint = getConstraintOfTypeParameter(target);
                        if (sourceConstraint) {
                            // relax check if later interface augmentation has no constraint
                            if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
                                return false;
                            }
                        }
                        // If the type parameter node has a default and it is not identical to the default
                        // for the type parameter at this position, we report an error.
                        var sourceDefault = source.default && getTypeFromTypeNode(source.default);
                        var targetDefault = getDefaultFromTypeParameter(target);
                        if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
                            return false;
                        }
                    }
                }
                return true;
            }
            function checkClassExpression(node) {
                checkClassLikeDeclaration(node);
                checkNodeDeferred(node);
                return getTypeOfSymbol(getSymbolOfNode(node));
            }
            function checkClassExpressionDeferred(node) {
                ts.forEach(node.members, checkSourceElement);
                registerForUnusedIdentifiersCheck(node);
            }
            function checkClassDeclaration(node) {
                if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
                    grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
                }
                checkClassLikeDeclaration(node);
                ts.forEach(node.members, checkSourceElement);
                registerForUnusedIdentifiersCheck(node);
            }
            function checkClassLikeDeclaration(node) {
                checkGrammarClassLikeDeclaration(node);
                checkDecorators(node);
                if (node.name) {
                    checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
                    checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
                    checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
                    if (!(node.flags & 4194304 /* Ambient */)) {
                        checkClassNameCollisionWithObject(node.name);
                    }
                }
                checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
                checkExportsOnMergedDeclarations(node);
                var symbol = getSymbolOfNode(node);
                var type = getDeclaredTypeOfSymbol(symbol);
                var typeWithThis = getTypeWithThisArgument(type);
                var staticType = getTypeOfSymbol(symbol);
                checkTypeParameterListsIdentical(symbol);
                checkClassForDuplicateDeclarations(node);
                // Only check for reserved static identifiers on non-ambient context.
                if (!(node.flags & 4194304 /* Ambient */)) {
                    checkClassForStaticPropertyNameConflicts(node);
                }
                var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
                if (baseTypeNode) {
                    if (languageVersion < 2 /* ES2015 */) {
                        checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
                    }
                    var baseTypes = getBaseTypes(type);
                    if (baseTypes.length && produceDiagnostics) {
                        var baseType_1 = baseTypes[0];
                        var baseConstructorType = getBaseConstructorTypeOfClass(type);
                        var staticBaseType = getApparentType(baseConstructorType);
                        checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
                        checkSourceElement(baseTypeNode.expression);
                        var extendsNode = ts.getClassExtendsHeritageElement(node);
                        if (extendsNode && extendsNode !== baseTypeNode) {
                            checkExpression(extendsNode.expression);
                        }
                        if (ts.some(baseTypeNode.typeArguments)) {
                            ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
                            for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
                                var constructor = _a[_i];
                                if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
                                    break;
                                }
                            }
                        }
                        var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
                        if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
                            issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
                        }
                        checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
                        if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
                            error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
                        }
                        if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) {
                            // When the static base type is a "class-like" constructor function (but not actually a class), we verify
                            // that all instantiated base constructor signatures return the same type. We can simply compare the type
                            // references (as opposed to checking the structure of the types) because elsewhere we have already checked
                            // that the base type is a class or interface type (and not, for example, an anonymous object type).
                            // (Javascript constructor functions have this property trivially true since their return type is ignored.)
                            var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
                            if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) {
                                error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
                            }
                        }
                        checkKindsOfPropertyMemberOverrides(type, baseType_1);
                    }
                }
                var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node);
                if (implementedTypeNodes) {
                    for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
                        var typeRefNode = implementedTypeNodes_1[_b];
                        if (!ts.isEntityNameExpression(typeRefNode.expression)) {
                            error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
                        }
                        checkTypeReferenceNode(typeRefNode);
                        if (produceDiagnostics) {
                            var t = getTypeFromTypeNode(typeRefNode);
                            if (t !== errorType) {
                                if (isValidBaseType(t)) {
                                    var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
                                        ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
                                        ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
                                    var baseWithThis = getTypeWithThisArgument(t, type.thisType);
                                    if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
                                        issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
                                    }
                                }
                                else {
                                    error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface);
                                }
                            }
                        }
                    }
                }
                if (produceDiagnostics) {
                    checkIndexConstraints(type);
                    checkTypeForDuplicateIndexSignatures(node);
                    checkPropertyInitialization(node);
                }
            }
            function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
                // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
                var issuedMemberError = false;
                var _loop_7 = function (member) {
                    if (ts.hasStaticModifier(member)) {
                        return "continue";
                    }
                    var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
                    if (declaredProp) {
                        var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
                        var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
                        if (prop && baseProp) {
                            var rootChain = function () {
                                return ts.chainDiagnosticMessages(
                                /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis));
                            };
                            if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
                                issuedMemberError = true;
                            }
                        }
                    }
                };
                for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                    var member = _a[_i];
                    _loop_7(member);
                }
                if (!issuedMemberError) {
                    // check again with diagnostics to generate a less-specific error
                    checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
                }
            }
            function checkBaseTypeAccessibility(type, node) {
                var signatures = getSignaturesOfType(type, 1 /* Construct */);
                if (signatures.length) {
                    var declaration = signatures[0].declaration;
                    if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
                        var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
                        if (!isNodeWithinClass(node, typeClassDeclaration)) {
                            error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
                        }
                    }
                }
            }
            function getTargetSymbol(s) {
                // if symbol is instantiated its flags are not copied from the 'target'
                // so we'll need to get back original 'target' symbol to work with correct set of flags
                return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
            }
            function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
                return ts.filter(symbol.declarations, function (d) {
                    return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */;
                });
            }
            function checkKindsOfPropertyMemberOverrides(type, baseType) {
                // TypeScript 1.0 spec (April 2014): 8.2.3
                // A derived class inherits all members from its base class it doesn't override.
                // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
                // Both public and private property members are inherited, but only public property members can be overridden.
                // A property member in a derived class is said to override a property member in a base class
                // when the derived class property member has the same name and kind(instance or static)
                // as the base class property member.
                // The type of an overriding property member must be assignable(section 3.8.4)
                // to the type of the overridden property member, or otherwise a compile - time error occurs.
                // Base class instance member functions can be overridden by derived class instance member functions,
                // but not by other kinds of members.
                // Base class instance member variables and accessors can be overridden by
                // derived class instance member variables and accessors, but not by other kinds of members.
                // NOTE: assignability is checked in checkClassDeclaration
                var baseProperties = getPropertiesOfType(baseType);
                for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
                    var baseProperty = baseProperties_1[_i];
                    var base = getTargetSymbol(baseProperty);
                    if (base.flags & 4194304 /* Prototype */) {
                        continue;
                    }
                    var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217
                    var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
                    ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
                    if (derived) {
                        // In order to resolve whether the inherited method was overridden in the base class or not,
                        // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
                        // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
                        if (derived === base) {
                            // derived class inherits base without override/redeclaration
                            var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
                            // It is an error to inherit an abstract member without implementing it or being declared abstract.
                            // If there is no declaration for the derived class (as in the case of class expressions),
                            // then the class cannot be declared abstract.
                            if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
                                if (derivedClassDecl.kind === 207 /* ClassExpression */) {
                                    error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
                                }
                                else {
                                    error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
                                }
                            }
                        }
                        else {
                            // derived overrides base.
                            var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
                            if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
                                // either base or derived property is private - not override, skip it
                                continue;
                            }
                            if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) {
                                // method is overridden with method or property/accessor is overridden with property/accessor - correct case
                                continue;
                            }
                            var errorMessage = void 0;
                            if (isPrototypeProperty(base)) {
                                if (derived.flags & 98304 /* Accessor */) {
                                    errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
                                }
                                else {
                                    errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property;
                                }
                            }
                            else if (base.flags & 98304 /* Accessor */) {
                                errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
                            }
                            else {
                                errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
                            }
                            error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
                        }
                    }
                }
            }
            function checkInheritedPropertiesAreIdentical(type, typeNode) {
                var baseTypes = getBaseTypes(type);
                if (baseTypes.length < 2) {
                    return true;
                }
                var seen = ts.createUnderscoreEscapedMap();
                ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
                var ok = true;
                for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
                    var base = baseTypes_2[_i];
                    var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
                    for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) {
                        var prop = properties_8[_a];
                        var existing = seen.get(prop.escapedName);
                        if (!existing) {
                            seen.set(prop.escapedName, { prop: prop, containingType: base });
                        }
                        else {
                            var isInheritedProperty = existing.containingType !== type;
                            if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
                                ok = false;
                                var typeName1 = typeToString(existing.containingType);
                                var typeName2 = typeToString(base);
                                var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
                                errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
                                diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
                            }
                        }
                    }
                }
                return ok;
            }
            function checkPropertyInitialization(node) {
                if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) {
                    return;
                }
                var constructor = findConstructorDeclaration(node);
                for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                    var member = _a[_i];
                    if (isInstancePropertyWithoutInitializer(member)) {
                        var propName = member.name;
                        if (ts.isIdentifier(propName)) {
                            var type = getTypeOfSymbol(getSymbolOfNode(member));
                            if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) {
                                if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
                                    error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
                                }
                            }
                        }
                    }
                }
            }
            function isInstancePropertyWithoutInitializer(node) {
                return node.kind === 152 /* PropertyDeclaration */ &&
                    !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
                    !node.exclamationToken &&
                    !node.initializer;
            }
            function isPropertyInitializedInConstructor(propName, propType, constructor) {
                var reference = ts.createPropertyAccess(ts.createThis(), propName);
                reference.expression.parent = reference;
                reference.parent = constructor;
                reference.flowNode = constructor.returnFlowNode;
                var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
                return !(getFalsyFlags(flowType) & 8192 /* Undefined */);
            }
            function checkInterfaceDeclaration(node) {
                // Grammar checking
                if (!checkGrammarDecoratorsAndModifiers(node))
                    checkGrammarInterfaceDeclaration(node);
                checkTypeParameters(node.typeParameters);
                if (produceDiagnostics) {
                    checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
                    checkExportsOnMergedDeclarations(node);
                    var symbol = getSymbolOfNode(node);
                    checkTypeParameterListsIdentical(symbol);
                    // Only check this symbol once
                    var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */);
                    if (node === firstInterfaceDecl) {
                        var type = getDeclaredTypeOfSymbol(symbol);
                        var typeWithThis = getTypeWithThisArgument(type);
                        // run subsequent checks only if first set succeeded
                        if (checkInheritedPropertiesAreIdentical(type, node.name)) {
                            for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
                                var baseType = _a[_i];
                                checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
                            }
                            checkIndexConstraints(type);
                        }
                    }
                    checkObjectTypeForDuplicateDeclarations(node);
                }
                ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
                    if (!ts.isEntityNameExpression(heritageElement.expression)) {
                        error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
                    }
                    checkTypeReferenceNode(heritageElement);
                });
                ts.forEach(node.members, checkSourceElement);
                if (produceDiagnostics) {
                    checkTypeForDuplicateIndexSignatures(node);
                    registerForUnusedIdentifiersCheck(node);
                }
            }
            function checkTypeAliasDeclaration(node) {
                // Grammar checking
                checkGrammarDecoratorsAndModifiers(node);
                checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
                checkTypeParameters(node.typeParameters);
                checkSourceElement(node.type);
                registerForUnusedIdentifiersCheck(node);
            }
            function computeEnumMemberValues(node) {
                var nodeLinks = getNodeLinks(node);
                if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
                    nodeLinks.flags |= 16384 /* EnumValuesComputed */;
                    var autoValue = 0;
                    for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                        var member = _a[_i];
                        var value = computeMemberValue(member, autoValue);
                        getNodeLinks(member).enumMemberValue = value;
                        autoValue = typeof value === "number" ? value + 1 : undefined;
                    }
                }
            }
            function computeMemberValue(member, autoValue) {
                if (isComputedNonLiteralName(member.name)) {
                    error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
                }
                else {
                    var text = ts.getTextOfPropertyName(member.name);
                    if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
                        error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
                    }
                }
                if (member.initializer) {
                    return computeConstantValue(member);
                }
                // In ambient enum declarations that specify no const modifier, enum member declarations that omit
                // a value are considered computed members (as opposed to having auto-incremented values).
                if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) {
                    return undefined;
                }
                // If the member declaration specifies no value, the member is considered a constant enum member.
                // If the member is the first member in the enum declaration, it is assigned the value zero.
                // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
                // occurs if the immediately preceding member is not a constant enum member.
                if (autoValue !== undefined) {
                    return autoValue;
                }
                error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
                return undefined;
            }
            function computeConstantValue(member) {
                var enumKind = getEnumKind(getSymbolOfNode(member.parent));
                var isConstEnum = ts.isEnumConst(member.parent);
                var initializer = member.initializer;
                var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
                if (value !== undefined) {
                    if (isConstEnum && typeof value === "number" && !isFinite(value)) {
                        error(initializer, isNaN(value) ?
                            ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
                            ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
                    }
                }
                else if (enumKind === 1 /* Literal */) {
                    error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
                    return 0;
                }
                else if (isConstEnum) {
                    error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression);
                }
                else if (member.parent.flags & 4194304 /* Ambient */) {
                    error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
                }
                else {
                    // Only here do we need to check that the initializer is assignable to the enum type.
                    checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
                }
                return value;
                function evaluate(expr) {
                    switch (expr.kind) {
                        case 200 /* PrefixUnaryExpression */:
                            var value_2 = evaluate(expr.operand);
                            if (typeof value_2 === "number") {
                                switch (expr.operator) {
                                    case 37 /* PlusToken */: return value_2;
                                    case 38 /* MinusToken */: return -value_2;
                                    case 52 /* TildeToken */: return ~value_2;
                                }
                            }
                            break;
                        case 202 /* BinaryExpression */:
                            var left = evaluate(expr.left);
                            var right = evaluate(expr.right);
                            if (typeof left === "number" && typeof right === "number") {
                                switch (expr.operatorToken.kind) {
                                    case 49 /* BarToken */: return left | right;
                                    case 48 /* AmpersandToken */: return left & right;
                                    case 46 /* GreaterThanGreaterThanToken */: return left >> right;
                                    case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
                                    case 45 /* LessThanLessThanToken */: return left << right;
                                    case 50 /* CaretToken */: return left ^ right;
                                    case 39 /* AsteriskToken */: return left * right;
                                    case 41 /* SlashToken */: return left / right;
                                    case 37 /* PlusToken */: return left + right;
                                    case 38 /* MinusToken */: return left - right;
                                    case 42 /* PercentToken */: return left % right;
                                    case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right);
                                }
                            }
                            else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) {
                                return left + right;
                            }
                            break;
                        case 9 /* StringLiteral */:
                            return expr.text;
                        case 8 /* NumericLiteral */:
                            checkGrammarNumericLiteral(expr);
                            return +expr.text;
                        case 193 /* ParenthesizedExpression */:
                            return evaluate(expr.expression);
                        case 71 /* Identifier */:
                            var identifier = expr;
                            if (isInfinityOrNaNString(identifier.escapedText)) {
                                return +(identifier.escapedText);
                            }
                            return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
                        case 188 /* ElementAccessExpression */:
                        case 187 /* PropertyAccessExpression */:
                            var ex = expr;
                            if (isConstantMemberAccess(ex)) {
                                var type = getTypeOfExpression(ex.expression);
                                if (type.symbol && type.symbol.flags & 384 /* Enum */) {
                                    var name = void 0;
                                    if (ex.kind === 187 /* PropertyAccessExpression */) {
                                        name = ex.name.escapedText;
                                    }
                                    else {
                                        var argument = ex.argumentExpression;
                                        ts.Debug.assert(ts.isLiteralExpression(argument));
                                        name = ts.escapeLeadingUnderscores(argument.text);
                                    }
                                    return evaluateEnumMember(expr, type.symbol, name);
                                }
                            }
                            break;
                    }
                    return undefined;
                }
                function evaluateEnumMember(expr, enumSymbol, name) {
                    var memberSymbol = enumSymbol.exports.get(name);
                    if (memberSymbol) {
                        var declaration = memberSymbol.valueDeclaration;
                        if (declaration !== member) {
                            if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
                                return getEnumMemberValue(declaration);
                            }
                            error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
                            return 0;
                        }
                    }
                    return undefined;
                }
            }
            function isConstantMemberAccess(node) {
                return node.kind === 71 /* Identifier */ ||
                    node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
                    node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
                        node.argumentExpression.kind === 9 /* StringLiteral */;
            }
            function checkEnumDeclaration(node) {
                if (!produceDiagnostics) {
                    return;
                }
                // Grammar checking
                checkGrammarDecoratorsAndModifiers(node);
                checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
                checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
                checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
                checkExportsOnMergedDeclarations(node);
                computeEnumMemberValues(node);
                var enumIsConst = ts.isEnumConst(node);
                if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) {
                    error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided);
                }
                // Spec 2014 - Section 9.3:
                // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
                // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
                // for the first member.
                //
                // Only perform this check once per symbol
                var enumSymbol = getSymbolOfNode(node);
                var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
                if (node === firstDeclaration) {
                    if (enumSymbol.declarations.length > 1) {
                        // check that const is placed\omitted on all enum declarations
                        ts.forEach(enumSymbol.declarations, function (decl) {
                            if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
                                error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
                            }
                        });
                    }
                    var seenEnumMissingInitialInitializer_1 = false;
                    ts.forEach(enumSymbol.declarations, function (declaration) {
                        // return true if we hit a violation of the rule, false otherwise
                        if (declaration.kind !== 241 /* EnumDeclaration */) {
                            return false;
                        }
                        var enumDeclaration = declaration;
                        if (!enumDeclaration.members.length) {
                            return false;
                        }
                        var firstEnumMember = enumDeclaration.members[0];
                        if (!firstEnumMember.initializer) {
                            if (seenEnumMissingInitialInitializer_1) {
                                error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
                            }
                            else {
                                seenEnumMissingInitialInitializer_1 = true;
                            }
                        }
                    });
                }
            }
            function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
                var declarations = symbol.declarations;
                for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
                    var declaration = declarations_8[_i];
                    if ((declaration.kind === 238 /* ClassDeclaration */ ||
                        (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
                        !(declaration.flags & 4194304 /* Ambient */)) {
                        return declaration;
                    }
                }
                return undefined;
            }
            function inSameLexicalScope(node1, node2) {
                var container1 = ts.getEnclosingBlockScopeContainer(node1);
                var container2 = ts.getEnclosingBlockScopeContainer(node2);
                if (isGlobalSourceFile(container1)) {
                    return isGlobalSourceFile(container2);
                }
                else if (isGlobalSourceFile(container2)) {
                    return false;
                }
                else {
                    return container1 === container2;
                }
            }
            function checkModuleDeclaration(node) {
                if (produceDiagnostics) {
                    // Grammar checking
                    var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
                    var inAmbientContext = node.flags & 4194304 /* Ambient */;
                    if (isGlobalAugmentation && !inAmbientContext) {
                        error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
                    }
                    var isAmbientExternalModule = ts.isAmbientModule(node);
                    var contextErrorMessage = isAmbientExternalModule
                        ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
                        : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
                    if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
                        // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
                        return;
                    }
                    if (!checkGrammarDecoratorsAndModifiers(node)) {
                        if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) {
                            grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
                        }
                    }
                    if (ts.isIdentifier(node.name)) {
                        checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
                        checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
                    }
                    checkExportsOnMergedDeclarations(node);
                    var symbol = getSymbolOfNode(node);
                    // The following checks only apply on a non-ambient instantiated module declaration.
                    if (symbol.flags & 512 /* ValueModule */
                        && symbol.declarations.length > 1
                        && !inAmbientContext
                        && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
                        var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
                        if (firstNonAmbientClassOrFunc) {
                            if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
                                error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
                            }
                            else if (node.pos < firstNonAmbientClassOrFunc.pos) {
                                error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
                            }
                        }
                        // if the module merges with a class declaration in the same lexical scope,
                        // we need to track this to ensure the correct emit.
                        var mergedClass = ts.getDeclarationOfKind(symbol, 238 /* ClassDeclaration */);
                        if (mergedClass &&
                            inSameLexicalScope(node, mergedClass)) {
                            getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
                        }
                    }
                    if (isAmbientExternalModule) {
                        if (ts.isExternalModuleAugmentation(node)) {
                            // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
                            // otherwise we'll be swamped in cascading errors.
                            // We can detect if augmentation was applied using following rules:
                            // - augmentation for a global scope is always applied
                            // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
                            var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
                            if (checkBody && node.body) {
                                for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
                                    var statement = _a[_i];
                                    checkModuleAugmentationElement(statement, isGlobalAugmentation);
                                }
                            }
                        }
                        else if (isGlobalSourceFile(node.parent)) {
                            if (isGlobalAugmentation) {
                                error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
                            }
                            else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
                                error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
                            }
                        }
                        else {
                            if (isGlobalAugmentation) {
                                error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
                            }
                            else {
                                // Node is not an augmentation and is not located on the script level.
                                // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
                                error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
                            }
                        }
                    }
                }
                if (node.body) {
                    checkSourceElement(node.body);
                    if (!ts.isGlobalScopeAugmentation(node)) {
                        registerForUnusedIdentifiersCheck(node);
                    }
                }
            }
            function checkModuleAugmentationElement(node, isGlobalAugmentation) {
                switch (node.kind) {
                    case 217 /* VariableStatement */:
                        // error each individual name in variable statement instead of marking the entire variable statement
                        for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                            var decl = _a[_i];
                            checkModuleAugmentationElement(decl, isGlobalAugmentation);
                        }
                        break;
                    case 252 /* ExportAssignment */:
                    case 253 /* ExportDeclaration */:
                        grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
                        break;
                    case 246 /* ImportEqualsDeclaration */:
                    case 247 /* ImportDeclaration */:
                        grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
                        break;
                    case 184 /* BindingElement */:
                    case 235 /* VariableDeclaration */:
                        var name = node.name;
                        if (ts.isBindingPattern(name)) {
                            for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
                                var el = _c[_b];
                                // mark individual names in binding pattern
                                checkModuleAugmentationElement(el, isGlobalAugmentation);
                            }
                            break;
                        }
                    // falls through
                    case 238 /* ClassDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 237 /* FunctionDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 242 /* ModuleDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                        if (isGlobalAugmentation) {
                            return;
                        }
                        var symbol = getSymbolOfNode(node);
                        if (symbol) {
                            // module augmentations cannot introduce new names on the top level scope of the module
                            // this is done it two steps
                            // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
                            // 2. main check - report error if value declaration of the parent symbol is module augmentation)
                            var reportError = !(symbol.flags & 33554432 /* Transient */);
                            if (!reportError) {
                                // symbol should not originate in augmentation
                                reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
                            }
                        }
                        break;
                }
            }
            function getFirstIdentifier(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return node;
                    case 146 /* QualifiedName */:
                        do {
                            node = node.left;
                        } while (node.kind !== 71 /* Identifier */);
                        return node;
                    case 187 /* PropertyAccessExpression */:
                        do {
                            node = node.expression;
                        } while (node.kind !== 71 /* Identifier */);
                        return node;
                }
            }
            function checkExternalImportOrExportDeclaration(node) {
                var moduleName = ts.getExternalModuleName(node);
                if (!moduleName || ts.nodeIsMissing(moduleName)) {
                    // Should be a parse error.
                    return false;
                }
                if (!ts.isStringLiteral(moduleName)) {
                    error(moduleName, ts.Diagnostics.String_literal_expected);
                    return false;
                }
                var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
                if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) {
                    error(moduleName, node.kind === 253 /* ExportDeclaration */ ?
                        ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
                        ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
                    return false;
                }
                if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
                    // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration
                    // no need to do this again.
                    if (!isTopLevelInExternalModuleAugmentation(node)) {
                        // TypeScript 1.0 spec (April 2013): 12.1.6
                        // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
                        // other external modules only through top - level external module names.
                        // Relative external module names are not permitted.
                        error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
                        return false;
                    }
                }
                return true;
            }
            function checkAliasSymbol(node) {
                var symbol = getSymbolOfNode(node);
                var target = resolveAlias(symbol);
                if (target !== unknownSymbol) {
                    // For external modules symbol represent local symbol for an alias.
                    // This local symbol will merge any other local declarations (excluding other aliases)
                    // and symbol.flags will contains combined representation for all merged declaration.
                    // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
                    // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
                    // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
                    var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) |
                        (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) |
                        (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
                    if (target.flags & excludedMeanings) {
                        var message = node.kind === 255 /* ExportSpecifier */ ?
                            ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
                            ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
                        error(node, message, symbolToString(symbol));
                    }
                    // Don't allow to re-export something with no value side when `--isolatedModules` is set.
                    if (compilerOptions.isolatedModules
                        && node.kind === 255 /* ExportSpecifier */
                        && !(target.flags & 67220415 /* Value */)
                        && !(node.flags & 4194304 /* Ambient */)) {
                        error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided);
                    }
                }
            }
            function checkImportBinding(node) {
                checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
                checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
                checkAliasSymbol(node);
            }
            function checkImportDeclaration(node) {
                if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
                    // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
                    return;
                }
                if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
                    grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
                }
                if (checkExternalImportOrExportDeclaration(node)) {
                    var importClause = node.importClause;
                    if (importClause) {
                        if (importClause.name) {
                            checkImportBinding(importClause);
                        }
                        if (importClause.namedBindings) {
                            if (importClause.namedBindings.kind === 249 /* NamespaceImport */) {
                                checkImportBinding(importClause.namedBindings);
                            }
                            else {
                                var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
                                if (moduleExisted) {
                                    ts.forEach(importClause.namedBindings.elements, checkImportBinding);
                                }
                            }
                        }
                    }
                }
            }
            function checkImportEqualsDeclaration(node) {
                if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
                    // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
                    return;
                }
                checkGrammarDecoratorsAndModifiers(node);
                if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
                    checkImportBinding(node);
                    if (ts.hasModifier(node, 1 /* Export */)) {
                        markExportAsReferenced(node);
                    }
                    if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) {
                        var target = resolveAlias(getSymbolOfNode(node));
                        if (target !== unknownSymbol) {
                            if (target.flags & 67220415 /* Value */) {
                                // Target is a value symbol, check that it is not hidden by a local declaration with the same name
                                var moduleName = getFirstIdentifier(node.moduleReference);
                                if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
                                    error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
                                }
                            }
                            if (target.flags & 67897832 /* Type */) {
                                checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
                            }
                        }
                    }
                    else {
                        if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) {
                            // Import equals declaration is deprecated in es6 or above
                            grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
                        }
                    }
                }
            }
            function checkExportDeclaration(node) {
                if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
                    // If we hit an export in an illegal context, just bail out to avoid cascading errors.
                    return;
                }
                if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
                    grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
                }
                if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
                    if (node.exportClause) {
                        // export { x, y }
                        // export { x, y } from "foo"
                        ts.forEach(node.exportClause.elements, checkExportSpecifier);
                        var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
                        var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ &&
                            !node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
                        if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
                            error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
                        }
                    }
                    else {
                        // export * from "foo"
                        var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
                        if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
                            error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
                        }
                        if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) {
                            checkExternalEmitHelpers(node, 32768 /* ExportStar */);
                        }
                    }
                }
            }
            function checkGrammarModuleElementContext(node, errorMessage) {
                var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */;
                if (!isInAppropriateContext) {
                    grammarErrorOnFirstToken(node, errorMessage);
                }
                return !isInAppropriateContext;
            }
            function checkExportSpecifier(node) {
                checkAliasSymbol(node);
                if (ts.getEmitDeclarations(compilerOptions)) {
                    collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
                }
                if (!node.parent.parent.moduleSpecifier) {
                    var exportedName = node.propertyName || node.name;
                    // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
                    var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
                    /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
                    if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
                        error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
                    }
                    else {
                        markExportAsReferenced(node);
                    }
                }
            }
            function checkExportAssignment(node) {
                if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
                    // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
                    return;
                }
                var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent;
                if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
                    if (node.isExportEquals) {
                        error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
                    }
                    else {
                        error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
                    }
                    return;
                }
                // Grammar checking
                if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
                    grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
                }
                if (node.expression.kind === 71 /* Identifier */) {
                    markExportAsReferenced(node);
                    if (ts.getEmitDeclarations(compilerOptions)) {
                        collectLinkedAliases(node.expression, /*setVisibility*/ true);
                    }
                }
                else {
                    checkExpressionCached(node.expression);
                }
                checkExternalModuleExports(container);
                if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
                    grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
                }
                if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) {
                    if (moduleKind >= ts.ModuleKind.ES2015) {
                        // export assignment is not supported in es6 modules
                        grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
                    }
                    else if (moduleKind === ts.ModuleKind.System) {
                        // system modules does not support export assignment
                        grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
                    }
                }
            }
            function hasExportedMembers(moduleSymbol) {
                return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
            }
            function checkExternalModuleExports(node) {
                var moduleSymbol = getSymbolOfNode(node);
                var links = getSymbolLinks(moduleSymbol);
                if (!links.exportsChecked) {
                    var exportEqualsSymbol = moduleSymbol.exports.get("export=");
                    if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
                        var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
                        if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
                            error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
                        }
                    }
                    // Checks for export * conflicts
                    var exports_1 = getExportsOfModule(moduleSymbol);
                    if (exports_1) {
                        exports_1.forEach(function (_a, id) {
                            var declarations = _a.declarations, flags = _a.flags;
                            if (id === "__export") {
                                return;
                            }
                            // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
                            // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
                            if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
                                return;
                            }
                            var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
                            if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
                                // it is legal to merge type alias with other values
                                // so count should be either 1 (just type alias) or 2 (type alias + merged value)
                                return;
                            }
                            if (exportedDeclarationsCount > 1) {
                                for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
                                    var declaration = declarations_9[_i];
                                    if (isNotOverload(declaration)) {
                                        diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
                                    }
                                }
                            }
                        });
                    }
                    links.exportsChecked = true;
                }
            }
            function isNotAccessor(declaration) {
                // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
                return !ts.isAccessor(declaration);
            }
            function isNotOverload(declaration) {
                return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) ||
                    !!declaration.body;
            }
            function checkSourceElement(node) {
                if (!node) {
                    return;
                }
                if (ts.isInJSFile(node)) {
                    ts.forEach(node.jsDoc, function (_a) {
                        var tags = _a.tags;
                        return ts.forEach(tags, checkSourceElement);
                    });
                }
                var kind = node.kind;
                if (cancellationToken) {
                    // Only bother checking on a few construct kinds.  We don't want to be excessively
                    // hitting the cancellation token on every node we check.
                    switch (kind) {
                        case 242 /* ModuleDeclaration */:
                        case 238 /* ClassDeclaration */:
                        case 239 /* InterfaceDeclaration */:
                        case 237 /* FunctionDeclaration */:
                            cancellationToken.throwIfCancellationRequested();
                    }
                }
                switch (kind) {
                    case 148 /* TypeParameter */:
                        return checkTypeParameter(node);
                    case 149 /* Parameter */:
                        return checkParameter(node);
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                        return checkPropertyDeclaration(node);
                    case 163 /* FunctionType */:
                    case 164 /* ConstructorType */:
                    case 158 /* CallSignature */:
                    case 159 /* ConstructSignature */:
                    case 160 /* IndexSignature */:
                        return checkSignatureDeclaration(node);
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                        return checkMethodDeclaration(node);
                    case 155 /* Constructor */:
                        return checkConstructorDeclaration(node);
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return checkAccessorDeclaration(node);
                    case 162 /* TypeReference */:
                        return checkTypeReferenceNode(node);
                    case 161 /* TypePredicate */:
                        return checkTypePredicate(node);
                    case 165 /* TypeQuery */:
                        return checkTypeQuery(node);
                    case 166 /* TypeLiteral */:
                        return checkTypeLiteral(node);
                    case 167 /* ArrayType */:
                        return checkArrayType(node);
                    case 168 /* TupleType */:
                        return checkTupleType(node);
                    case 171 /* UnionType */:
                    case 172 /* IntersectionType */:
                        return checkUnionOrIntersectionType(node);
                    case 175 /* ParenthesizedType */:
                    case 169 /* OptionalType */:
                    case 170 /* RestType */:
                        return checkSourceElement(node.type);
                    case 176 /* ThisType */:
                        return checkThisType(node);
                    case 177 /* TypeOperator */:
                        return checkTypeOperator(node);
                    case 173 /* ConditionalType */:
                        return checkConditionalType(node);
                    case 174 /* InferType */:
                        return checkInferType(node);
                    case 181 /* ImportType */:
                        return checkImportType(node);
                    case 293 /* JSDocAugmentsTag */:
                        return checkJSDocAugmentsTag(node);
                    case 302 /* JSDocTypedefTag */:
                    case 295 /* JSDocCallbackTag */:
                        return checkJSDocTypeAliasTag(node);
                    case 301 /* JSDocTemplateTag */:
                        return checkJSDocTemplateTag(node);
                    case 300 /* JSDocTypeTag */:
                        return checkJSDocTypeTag(node);
                    case 297 /* JSDocParameterTag */:
                        return checkJSDocParameterTag(node);
                    case 287 /* JSDocFunctionType */:
                        checkSignatureDeclaration(node);
                    // falls through
                    case 285 /* JSDocNonNullableType */:
                    case 284 /* JSDocNullableType */:
                    case 282 /* JSDocAllType */:
                    case 283 /* JSDocUnknownType */:
                    case 290 /* JSDocTypeLiteral */:
                        checkJSDocTypeIsInJsFile(node);
                        ts.forEachChild(node, checkSourceElement);
                        return;
                    case 288 /* JSDocVariadicType */:
                        checkJSDocVariadicType(node);
                        return;
                    case 281 /* JSDocTypeExpression */:
                        return checkSourceElement(node.type);
                    case 178 /* IndexedAccessType */:
                        return checkIndexedAccessType(node);
                    case 179 /* MappedType */:
                        return checkMappedType(node);
                    case 237 /* FunctionDeclaration */:
                        return checkFunctionDeclaration(node);
                    case 216 /* Block */:
                    case 243 /* ModuleBlock */:
                        return checkBlock(node);
                    case 217 /* VariableStatement */:
                        return checkVariableStatement(node);
                    case 219 /* ExpressionStatement */:
                        return checkExpressionStatement(node);
                    case 220 /* IfStatement */:
                        return checkIfStatement(node);
                    case 221 /* DoStatement */:
                        return checkDoStatement(node);
                    case 222 /* WhileStatement */:
                        return checkWhileStatement(node);
                    case 223 /* ForStatement */:
                        return checkForStatement(node);
                    case 224 /* ForInStatement */:
                        return checkForInStatement(node);
                    case 225 /* ForOfStatement */:
                        return checkForOfStatement(node);
                    case 226 /* ContinueStatement */:
                    case 227 /* BreakStatement */:
                        return checkBreakOrContinueStatement(node);
                    case 228 /* ReturnStatement */:
                        return checkReturnStatement(node);
                    case 229 /* WithStatement */:
                        return checkWithStatement(node);
                    case 230 /* SwitchStatement */:
                        return checkSwitchStatement(node);
                    case 231 /* LabeledStatement */:
                        return checkLabeledStatement(node);
                    case 232 /* ThrowStatement */:
                        return checkThrowStatement(node);
                    case 233 /* TryStatement */:
                        return checkTryStatement(node);
                    case 235 /* VariableDeclaration */:
                        return checkVariableDeclaration(node);
                    case 184 /* BindingElement */:
                        return checkBindingElement(node);
                    case 238 /* ClassDeclaration */:
                        return checkClassDeclaration(node);
                    case 239 /* InterfaceDeclaration */:
                        return checkInterfaceDeclaration(node);
                    case 240 /* TypeAliasDeclaration */:
                        return checkTypeAliasDeclaration(node);
                    case 241 /* EnumDeclaration */:
                        return checkEnumDeclaration(node);
                    case 242 /* ModuleDeclaration */:
                        return checkModuleDeclaration(node);
                    case 247 /* ImportDeclaration */:
                        return checkImportDeclaration(node);
                    case 246 /* ImportEqualsDeclaration */:
                        return checkImportEqualsDeclaration(node);
                    case 253 /* ExportDeclaration */:
                        return checkExportDeclaration(node);
                    case 252 /* ExportAssignment */:
                        return checkExportAssignment(node);
                    case 218 /* EmptyStatement */:
                    case 234 /* DebuggerStatement */:
                        checkGrammarStatementInAmbientContext(node);
                        return;
                    case 256 /* MissingDeclaration */:
                        return checkMissingDeclaration(node);
                }
            }
            function checkJSDocTypeIsInJsFile(node) {
                if (!ts.isInJSFile(node)) {
                    grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
                }
            }
            function checkJSDocVariadicType(node) {
                checkJSDocTypeIsInJsFile(node);
                checkSourceElement(node.type);
                // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
                var parent = node.parent;
                if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
                    if (ts.last(parent.parent.parameters) !== parent) {
                        error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
                    }
                    return;
                }
                if (!ts.isJSDocTypeExpression(parent)) {
                    error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
                }
                var paramTag = node.parent.parent;
                if (!ts.isJSDocParameterTag(paramTag)) {
                    error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
                    return;
                }
                var param = ts.getParameterSymbolFromJSDoc(paramTag);
                if (!param) {
                    // We will error in `checkJSDocParameterTag`.
                    return;
                }
                var host = ts.getHostSignatureFromJSDoc(paramTag);
                if (!host || ts.last(host.parameters).symbol !== param) {
                    error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
                }
            }
            function getTypeFromJSDocVariadicType(node) {
                var type = getTypeFromTypeNode(node.type);
                var parent = node.parent;
                var paramTag = node.parent.parent;
                if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
                    // Else we will add a diagnostic, see `checkJSDocVariadicType`.
                    var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
                    if (host_1) {
                        /*
                        Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
                        So in the following situation we will not create an array type:
                            /** @param {...number} a * /
                            function f(a) {}
                        Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
                        */
                        var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
                        var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
                        if (!lastParamDeclaration ||
                            symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
                            return createArrayType(type);
                        }
                    }
                }
                if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
                    return createArrayType(type);
                }
                return addOptionality(type);
            }
            // Function and class expression bodies are checked after all statements in the enclosing body. This is
            // to ensure constructs like the following are permitted:
            //     const foo = function () {
            //        const s = foo();
            //        return "hello";
            //     }
            // Here, performing a full type check of the body of the function expression whilst in the process of
            // determining the type of foo would cause foo to be given type any because of the recursive reference.
            // Delaying the type check of the body ensures foo has been assigned a type.
            function checkNodeDeferred(node) {
                if (deferredNodes) {
                    var id = "" + getNodeId(node);
                    deferredNodes.set(id, node);
                }
            }
            function checkDeferredNodes() {
                deferredNodes.forEach(function (node) {
                    switch (node.kind) {
                        case 194 /* FunctionExpression */:
                        case 195 /* ArrowFunction */:
                        case 154 /* MethodDeclaration */:
                        case 153 /* MethodSignature */:
                            checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
                            break;
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            checkAccessorDeclaration(node);
                            break;
                        case 207 /* ClassExpression */:
                            checkClassExpressionDeferred(node);
                            break;
                        case 259 /* JsxSelfClosingElement */:
                            checkJsxSelfClosingElementDeferred(node);
                            break;
                        case 258 /* JsxElement */:
                            checkJsxElementDeferred(node);
                            break;
                    }
                });
            }
            function checkSourceFile(node) {
                ts.performance.mark("beforeCheck");
                checkSourceFileWorker(node);
                ts.performance.mark("afterCheck");
                ts.performance.measure("Check", "beforeCheck", "afterCheck");
            }
            function unusedIsError(kind) {
                switch (kind) {
                    case 0 /* Local */:
                        return !!compilerOptions.noUnusedLocals;
                    case 1 /* Parameter */:
                        return !!compilerOptions.noUnusedParameters;
                    default:
                        return ts.Debug.assertNever(kind);
                }
            }
            function getPotentiallyUnusedIdentifiers(sourceFile) {
                return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
            }
            // Fully type check a source file and collect the relevant diagnostics.
            function checkSourceFileWorker(node) {
                var links = getNodeLinks(node);
                if (!(links.flags & 1 /* TypeChecked */)) {
                    if (ts.skipTypeChecking(node, compilerOptions)) {
                        return;
                    }
                    // Grammar checking
                    checkGrammarSourceFile(node);
                    ts.clear(potentialThisCollisions);
                    ts.clear(potentialNewTargetCollisions);
                    deferredNodes = ts.createMap();
                    ts.forEach(node.statements, checkSourceElement);
                    checkDeferredNodes();
                    if (ts.isExternalOrCommonJsModule(node)) {
                        registerForUnusedIdentifiersCheck(node);
                    }
                    if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
                        checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
                            if (!ts.containsParseError(containingNode) && unusedIsError(kind)) {
                                diagnostics.add(diag);
                            }
                        });
                    }
                    deferredNodes = undefined;
                    if (ts.isExternalOrCommonJsModule(node)) {
                        checkExternalModuleExports(node);
                    }
                    if (potentialThisCollisions.length) {
                        ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
                        ts.clear(potentialThisCollisions);
                    }
                    if (potentialNewTargetCollisions.length) {
                        ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
                        ts.clear(potentialNewTargetCollisions);
                    }
                    links.flags |= 1 /* TypeChecked */;
                }
            }
            function getDiagnostics(sourceFile, ct) {
                try {
                    // Record the cancellation token so it can be checked later on during checkSourceElement.
                    // Do this in a finally block so we can ensure that it gets reset back to nothing after
                    // this call is done.
                    cancellationToken = ct;
                    return getDiagnosticsWorker(sourceFile);
                }
                finally {
                    cancellationToken = undefined;
                }
            }
            function getDiagnosticsWorker(sourceFile) {
                throwIfNonDiagnosticsProducing();
                if (sourceFile) {
                    // Some global diagnostics are deferred until they are needed and
                    // may not be reported in the firt call to getGlobalDiagnostics.
                    // We should catch these changes and report them.
                    var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
                    var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
                    checkSourceFile(sourceFile);
                    var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
                    var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
                    if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
                        // If the arrays are not the same reference, new diagnostics were added.
                        var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
                        return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
                    }
                    else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
                        // If the arrays are the same reference, but the length has changed, a single
                        // new diagnostic was added as DiagnosticCollection attempts to reuse the
                        // same array.
                        return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
                    }
                    return semanticDiagnostics;
                }
                // Global diagnostics are always added when a file is not provided to
                // getDiagnostics
                ts.forEach(host.getSourceFiles(), checkSourceFile);
                return diagnostics.getDiagnostics();
            }
            function getGlobalDiagnostics() {
                throwIfNonDiagnosticsProducing();
                return diagnostics.getGlobalDiagnostics();
            }
            function throwIfNonDiagnosticsProducing() {
                if (!produceDiagnostics) {
                    throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
                }
            }
            // Language service support
            function getSymbolsInScope(location, meaning) {
                if (location.flags & 8388608 /* InWithStatement */) {
                    // We cannot answer semantic questions within a with block, do not proceed any further
                    return [];
                }
                var symbols = ts.createSymbolTable();
                var isStatic = false;
                populateSymbols();
                symbols.delete("this" /* This */); // Not a symbol, a keyword
                return symbolsToArray(symbols);
                function populateSymbols() {
                    while (location) {
                        if (location.locals && !isGlobalSourceFile(location)) {
                            copySymbols(location.locals, meaning);
                        }
                        switch (location.kind) {
                            case 242 /* ModuleDeclaration */:
                                copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
                                break;
                            case 241 /* EnumDeclaration */:
                                copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
                                break;
                            case 207 /* ClassExpression */:
                                var className = location.name;
                                if (className) {
                                    copySymbol(location.symbol, meaning);
                                }
                            // falls through
                            // this fall-through is necessary because we would like to handle
                            // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration
                            case 238 /* ClassDeclaration */:
                            case 239 /* InterfaceDeclaration */:
                                // If we didn't come from static member of class or interface,
                                // add the type parameters into the symbol table
                                // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
                                // Note: that the memberFlags come from previous iteration.
                                if (!isStatic) {
                                    copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */);
                                }
                                break;
                            case 194 /* FunctionExpression */:
                                var funcName = location.name;
                                if (funcName) {
                                    copySymbol(location.symbol, meaning);
                                }
                                break;
                        }
                        if (ts.introducesArgumentsExoticObject(location)) {
                            copySymbol(argumentsSymbol, meaning);
                        }
                        isStatic = ts.hasModifier(location, 32 /* Static */);
                        location = location.parent;
                    }
                    copySymbols(globals, meaning);
                }
                /**
                 * Copy the given symbol into symbol tables if the symbol has the given meaning
                 * and it doesn't already existed in the symbol table
                 * @param key a key for storing in symbol table; if undefined, use symbol.name
                 * @param symbol the symbol to be added into symbol table
                 * @param meaning meaning of symbol to filter by before adding to symbol table
                 */
                function copySymbol(symbol, meaning) {
                    if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
                        var id = symbol.escapedName;
                        // We will copy all symbol regardless of its reserved name because
                        // symbolsToArray will check whether the key is a reserved name and
                        // it will not copy symbol with reserved name to the array
                        if (!symbols.has(id)) {
                            symbols.set(id, symbol);
                        }
                    }
                }
                function copySymbols(source, meaning) {
                    if (meaning) {
                        source.forEach(function (symbol) {
                            copySymbol(symbol, meaning);
                        });
                    }
                }
            }
            function isTypeDeclarationName(name) {
                return name.kind === 71 /* Identifier */ &&
                    isTypeDeclaration(name.parent) &&
                    name.parent.name === name;
            }
            function isTypeDeclaration(node) {
                switch (node.kind) {
                    case 148 /* TypeParameter */:
                    case 238 /* ClassDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 241 /* EnumDeclaration */:
                        return true;
                    default:
                        return false;
                }
            }
            // True if the given identifier is part of a type reference
            function isTypeReferenceIdentifier(node) {
                while (node.parent.kind === 146 /* QualifiedName */) {
                    node = node.parent;
                }
                return node.parent.kind === 162 /* TypeReference */;
            }
            function isHeritageClauseElementIdentifier(node) {
                while (node.parent.kind === 187 /* PropertyAccessExpression */) {
                    node = node.parent;
                }
                return node.parent.kind === 209 /* ExpressionWithTypeArguments */;
            }
            function forEachEnclosingClass(node, callback) {
                var result;
                while (true) {
                    node = ts.getContainingClass(node);
                    if (!node)
                        break;
                    if (result = callback(node))
                        break;
                }
                return result;
            }
            function isNodeUsedDuringClassInitialization(node) {
                return !!ts.findAncestor(node, function (element) {
                    if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
                        return true;
                    }
                    else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
                        return "quit";
                    }
                    return false;
                });
            }
            function isNodeWithinClass(node, classDeclaration) {
                return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
            }
            function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
                while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) {
                    nodeOnRightSide = nodeOnRightSide.parent;
                }
                if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) {
                    return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
                }
                if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) {
                    return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
                }
                return undefined;
            }
            function isInRightSideOfImportOrExportAssignment(node) {
                return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
            }
            function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
                var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
                switch (specialPropertyAssignmentKind) {
                    case 1 /* ExportsProperty */:
                    case 3 /* PrototypeProperty */:
                        return getSymbolOfNode(entityName.parent);
                    case 4 /* ThisProperty */:
                    case 2 /* ModuleExports */:
                    case 5 /* Property */:
                        return getSymbolOfNode(entityName.parent.parent);
                }
            }
            function isImportTypeQualifierPart(node) {
                var parent = node.parent;
                while (ts.isQualifiedName(parent)) {
                    node = parent;
                    parent = parent.parent;
                }
                if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) {
                    return parent;
                }
                return undefined;
            }
            function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) {
                if (ts.isDeclarationName(entityName)) {
                    return getSymbolOfNode(entityName.parent);
                }
                if (ts.isInJSFile(entityName) &&
                    entityName.parent.kind === 187 /* PropertyAccessExpression */ &&
                    entityName.parent === entityName.parent.parent.left) {
                    // Check if this is a special property assignment
                    var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName);
                    if (specialPropertyAssignmentSymbol) {
                        return specialPropertyAssignmentSymbol;
                    }
                }
                if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) {
                    // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
                    var success = resolveEntityName(entityName, 
                    /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
                    if (success && success !== unknownSymbol) {
                        return success;
                    }
                }
                else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) {
                    // Since we already checked for ExportAssignment, this really could only be an Import
                    var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */);
                    ts.Debug.assert(importEqualsDeclaration !== undefined);
                    return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true);
                }
                if (!ts.isPropertyAccessExpression(entityName)) {
                    var possibleImportNode = isImportTypeQualifierPart(entityName);
                    if (possibleImportNode) {
                        getTypeFromTypeNode(possibleImportNode);
                        var sym = getNodeLinks(entityName).resolvedSymbol;
                        return sym === unknownSymbol ? undefined : sym;
                    }
                }
                while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
                    entityName = entityName.parent;
                }
                if (isHeritageClauseElementIdentifier(entityName)) {
                    var meaning = 0 /* None */;
                    // In an interface or class, we're definitely interested in a type.
                    if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) {
                        meaning = 67897832 /* Type */;
                        // In a class 'extends' clause we are also looking for a value.
                        if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) {
                            meaning |= 67220415 /* Value */;
                        }
                    }
                    else {
                        meaning = 1920 /* Namespace */;
                    }
                    meaning |= 2097152 /* Alias */;
                    var entityNameSymbol = ts.isEntityNameExpression(entityName) ? resolveEntityName(entityName, meaning) : undefined;
                    if (entityNameSymbol) {
                        return entityNameSymbol;
                    }
                }
                if (entityName.parent.kind === 297 /* JSDocParameterTag */) {
                    return ts.getParameterSymbolFromJSDoc(entityName.parent);
                }
                if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) {
                    ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
                    var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
                    return typeParameter && typeParameter.symbol;
                }
                if (ts.isExpressionNode(entityName)) {
                    if (ts.nodeIsMissing(entityName)) {
                        // Missing entity name.
                        return undefined;
                    }
                    if (entityName.kind === 71 /* Identifier */) {
                        if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) {
                            var symbol = getIntrinsicTagSymbol(entityName.parent);
                            return symbol === unknownSymbol ? undefined : symbol;
                        }
                        return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
                    }
                    else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) {
                        var links = getNodeLinks(entityName);
                        if (links.resolvedSymbol) {
                            return links.resolvedSymbol;
                        }
                        if (entityName.kind === 187 /* PropertyAccessExpression */) {
                            checkPropertyAccessExpression(entityName);
                        }
                        else {
                            checkQualifiedName(entityName);
                        }
                        return links.resolvedSymbol;
                    }
                }
                else if (isTypeReferenceIdentifier(entityName)) {
                    var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */;
                    return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
                }
                else if (entityName.parent.kind === 265 /* JsxAttribute */) {
                    return getJsxAttributePropertySymbol(entityName.parent);
                }
                if (entityName.parent.kind === 161 /* TypePredicate */) {
                    return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */);
                }
                // Do we want to return undefined here?
                return undefined;
            }
            function getSymbolAtLocation(node) {
                if (node.kind === 277 /* SourceFile */) {
                    return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
                }
                var parent = node.parent;
                var grandParent = parent.parent;
                if (node.flags & 8388608 /* InWithStatement */) {
                    // We cannot answer semantic questions within a with block, do not proceed any further
                    return undefined;
                }
                if (isDeclarationNameOrImportPropertyName(node)) {
                    // This is a declaration, call getSymbolOfNode
                    return getSymbolOfNode(parent);
                }
                else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
                    return getSymbolOfNode(parent.parent);
                }
                if (node.kind === 71 /* Identifier */) {
                    if (isInRightSideOfImportOrExportAssignment(node)) {
                        return getSymbolOfEntityNameOrPropertyAccessExpression(node);
                    }
                    else if (parent.kind === 184 /* BindingElement */ &&
                        grandParent.kind === 182 /* ObjectBindingPattern */ &&
                        node === parent.propertyName) {
                        var typeOfPattern = getTypeOfNode(grandParent);
                        var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
                        if (propertyDeclaration) {
                            return propertyDeclaration;
                        }
                    }
                }
                switch (node.kind) {
                    case 71 /* Identifier */:
                    case 187 /* PropertyAccessExpression */:
                    case 146 /* QualifiedName */:
                        return getSymbolOfEntityNameOrPropertyAccessExpression(node);
                    case 99 /* ThisKeyword */:
                        var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
                        if (ts.isFunctionLike(container)) {
                            var sig = getSignatureFromDeclaration(container);
                            if (sig.thisParameter) {
                                return sig.thisParameter;
                            }
                        }
                        if (ts.isInExpressionContext(node)) {
                            return checkExpression(node).symbol;
                        }
                    // falls through
                    case 176 /* ThisType */:
                        return getTypeFromThisTypeNode(node).symbol;
                    case 97 /* SuperKeyword */:
                        return checkExpression(node).symbol;
                    case 123 /* ConstructorKeyword */:
                        // constructor keyword for an overload, should take us to the definition if it exist
                        var constructorDeclaration = node.parent;
                        if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) {
                            return constructorDeclaration.parent.symbol;
                        }
                        return undefined;
                    case 9 /* StringLiteral */:
                    case 13 /* NoSubstitutionTemplateLiteral */:
                        // 1). import x = require("./mo/*gotToDefinitionHere*/d")
                        // 2). External module name in an import declaration
                        // 3). Dynamic import call or require in javascript
                        // 4). type A = import("./f/*gotToDefinitionHere*/oo")
                        if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
                            ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
                            ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
                            (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
                            return resolveExternalModuleName(node, node);
                        }
                    // falls through
                    case 8 /* NumericLiteral */:
                        // index access
                        var objectType = ts.isElementAccessExpression(parent)
                            ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
                            : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
                                ? getTypeFromTypeNode(grandParent.objectType)
                                : undefined;
                        return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
                    case 79 /* DefaultKeyword */:
                    case 89 /* FunctionKeyword */:
                    case 36 /* EqualsGreaterThanToken */:
                    case 75 /* ClassKeyword */:
                        return getSymbolOfNode(node.parent);
                    case 181 /* ImportType */:
                        return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined;
                    default:
                        return undefined;
                }
            }
            function getShorthandAssignmentValueSymbol(location) {
                if (location && location.kind === 274 /* ShorthandPropertyAssignment */) {
                    return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */);
                }
                return undefined;
            }
            /** Returns the target of an export specifier without following aliases */
            function getExportSpecifierLocalTargetSymbol(node) {
                return node.parent.parent.moduleSpecifier ?
                    getExternalModuleMember(node.parent.parent, node) :
                    resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
            }
            function getTypeOfNode(node) {
                if (node.flags & 8388608 /* InWithStatement */) {
                    // We cannot answer semantic questions within a with block, do not proceed any further
                    return errorType;
                }
                if (ts.isPartOfTypeNode(node)) {
                    var typeFromTypeNode = getTypeFromTypeNode(node);
                    if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) {
                        return getTypeWithThisArgument(typeFromTypeNode, getTypeOfClassContainingHeritageClause(node).thisType);
                    }
                    return typeFromTypeNode;
                }
                if (ts.isExpressionNode(node)) {
                    return getRegularTypeOfExpression(node);
                }
                if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) {
                    // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
                    // extends clause of a class. We handle that case here.
                    var classType = getTypeOfClassContainingHeritageClause(node);
                    var baseType = ts.firstOrUndefined(getBaseTypes(classType));
                    return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
                }
                if (isTypeDeclaration(node)) {
                    // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
                    var symbol = getSymbolOfNode(node);
                    return getDeclaredTypeOfSymbol(symbol);
                }
                if (isTypeDeclarationName(node)) {
                    var symbol = getSymbolAtLocation(node);
                    return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
                }
                if (ts.isDeclaration(node)) {
                    // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
                    var symbol = getSymbolOfNode(node);
                    return getTypeOfSymbol(symbol);
                }
                if (isDeclarationNameOrImportPropertyName(node)) {
                    var symbol = getSymbolAtLocation(node);
                    return symbol ? getTypeOfSymbol(symbol) : errorType;
                }
                if (ts.isBindingPattern(node)) {
                    return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
                }
                if (isInRightSideOfImportOrExportAssignment(node)) {
                    var symbol = getSymbolAtLocation(node);
                    if (symbol) {
                        var declaredType = getDeclaredTypeOfSymbol(symbol);
                        return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
                    }
                }
                return errorType;
            }
            function getTypeOfClassContainingHeritageClause(node) {
                return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node.parent.parent));
            }
            // Gets the type of object literal or array literal of destructuring assignment.
            // { a } from
            //     for ( { a } of elems) {
            //     }
            // [ a ] from
            //     [a] = [ some array ...]
            function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) {
                ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */);
                // If this is from "for of"
                //     for ( { a } of elems) {
                //     }
                if (expr.parent.kind === 225 /* ForOfStatement */) {
                    var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier);
                    return checkDestructuringAssignment(expr, iteratedType || errorType);
                }
                // If this is from "for" initializer
                //     for ({a } = elems[0];.....) { }
                if (expr.parent.kind === 202 /* BinaryExpression */) {
                    var iteratedType = getTypeOfExpression(expr.parent.right);
                    return checkDestructuringAssignment(expr, iteratedType || errorType);
                }
                // If this is from nested object binding pattern
                //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
                if (expr.parent.kind === 273 /* PropertyAssignment */) {
                    var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent);
                    return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217
                }
                // Array literal assignment - array destructuring pattern
                ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */);
                //    [{ property1: p1, property2 }] = elems;
                var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent);
                var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType;
                return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217
            }
            // Gets the property symbol corresponding to the property in destructuring assignment
            // 'property1' from
            //     for ( { property1: a } of elems) {
            //     }
            // 'property1' at location 'a' from:
            //     [a] = [ property1, property2 ]
            function getPropertySymbolOfDestructuringAssignment(location) {
                // Get the type of the object or array literal and then look for property of given name in the type
                var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent);
                return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
            }
            function getRegularTypeOfExpression(expr) {
                if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
                    expr = expr.parent;
                }
                return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
            }
            /**
             * Gets either the static or instance type of a class element, based on
             * whether the element is declared as "static".
             */
            function getParentTypeOfClassElement(node) {
                var classSymbol = getSymbolOfNode(node.parent);
                return ts.hasModifier(node, 32 /* Static */)
                    ? getTypeOfSymbol(classSymbol)
                    : getDeclaredTypeOfSymbol(classSymbol);
            }
            function getClassElementPropertyKeyType(element) {
                var name = element.name;
                switch (name.kind) {
                    case 71 /* Identifier */:
                        return getLiteralType(ts.idText(name));
                    case 8 /* NumericLiteral */:
                    case 9 /* StringLiteral */:
                        return getLiteralType(name.text);
                    case 147 /* ComputedPropertyName */:
                        var nameType = checkComputedPropertyName(name);
                        return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType;
                    default:
                        ts.Debug.fail("Unsupported property name.");
                        return errorType;
                }
            }
            // Return the list of properties of the given type, augmented with properties from Function
            // if the type has call or construct signatures
            function getAugmentedPropertiesOfType(type) {
                type = getApparentType(type);
                var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
                if (typeHasCallOrConstructSignatures(type)) {
                    ts.forEach(getPropertiesOfType(globalFunctionType), function (p) {
                        if (!propsByName.has(p.escapedName)) {
                            propsByName.set(p.escapedName, p);
                        }
                    });
                }
                return getNamedMembers(propsByName);
            }
            function typeHasCallOrConstructSignatures(type) {
                return ts.typeHasCallOrConstructSignatures(type, checker);
            }
            function getRootSymbols(symbol) {
                var roots = getImmediateRootSymbols(symbol);
                return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
            }
            function getImmediateRootSymbols(symbol) {
                if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
                    return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
                }
                else if (symbol.flags & 33554432 /* Transient */) {
                    var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
                    return leftSpread ? [leftSpread, rightSpread]
                        : syntheticOrigin ? [syntheticOrigin]
                            : ts.singleElementArray(tryGetAliasTarget(symbol));
                }
                return undefined;
            }
            function tryGetAliasTarget(symbol) {
                var target;
                var next = symbol;
                while (next = getSymbolLinks(next).target) {
                    target = next;
                }
                return target;
            }
            // Emitter support
            function isArgumentsLocalBinding(nodeIn) {
                if (!ts.isGeneratedIdentifier(nodeIn)) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
                    if (node) {
                        var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node;
                        return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
                    }
                }
                return false;
            }
            function moduleExportsSomeValue(moduleReferenceExpression) {
                var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
                if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
                    // If the module is not found or is shorthand, assume that it may export a value.
                    return true;
                }
                var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
                // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
                // otherwise it will return moduleSymbol itself
                moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
                var symbolLinks = getSymbolLinks(moduleSymbol);
                if (symbolLinks.exportsSomeValue === undefined) {
                    // for export assignments - check if resolved symbol for RHS is itself a value
                    // otherwise - check if at least one export is value
                    symbolLinks.exportsSomeValue = hasExportAssignment
                        ? !!(moduleSymbol.flags & 67220415 /* Value */)
                        : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
                }
                return symbolLinks.exportsSomeValue;
                function isValue(s) {
                    s = resolveSymbol(s);
                    return s && !!(s.flags & 67220415 /* Value */);
                }
            }
            function isNameOfModuleOrEnumDeclaration(node) {
                return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
            }
            // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
            // node of the exported entity's container. Otherwise, return undefined.
            function getReferencedExportContainer(nodeIn, prefixLocals) {
                var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
                if (node) {
                    // When resolving the export container for the name of a module or enum
                    // declaration, we need to start resolution at the declaration's container.
                    // Otherwise, we could incorrectly resolve the export container as the
                    // declaration if it contains an exported member with the same name.
                    var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
                    if (symbol) {
                        if (symbol.flags & 1048576 /* ExportValue */) {
                            // If we reference an exported entity within the same module declaration, then whether
                            // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
                            // kinds that we do NOT prefix.
                            var exportSymbol = getMergedSymbol(symbol.exportSymbol);
                            if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
                                return undefined;
                            }
                            symbol = exportSymbol;
                        }
                        var parentSymbol_1 = getParentOfSymbol(symbol);
                        if (parentSymbol_1) {
                            if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) {
                                var symbolFile = parentSymbol_1.valueDeclaration;
                                var referenceFile = ts.getSourceFileOfNode(node);
                                // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
                                var symbolIsUmdExport = symbolFile !== referenceFile;
                                return symbolIsUmdExport ? undefined : symbolFile;
                            }
                            return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
                        }
                    }
                }
            }
            // When resolved as an expression identifier, if the given node references an import, return the declaration of
            // that import. Otherwise, return undefined.
            function getReferencedImportDeclaration(nodeIn) {
                var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
                if (node) {
                    var symbol = getReferencedValueSymbol(node);
                    // We should only get the declaration of an alias if there isn't a local value
                    // declaration for the symbol
                    if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) {
                        return getDeclarationOfAliasSymbol(symbol);
                    }
                }
                return undefined;
            }
            function isSymbolOfDeclarationWithCollidingName(symbol) {
                if (symbol.flags & 418 /* BlockScoped */) {
                    var links = getSymbolLinks(symbol);
                    if (links.isDeclarationWithCollidingName === undefined) {
                        var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
                        if (ts.isStatementWithLocals(container)) {
                            var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
                            if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
                                // redeclaration - always should be renamed
                                links.isDeclarationWithCollidingName = true;
                            }
                            else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) {
                                // binding is captured in the function
                                // should be renamed if:
                                // - binding is not top level - top level bindings never collide with anything
                                // AND
                                //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
                                //     let a, b
                                //     { let x = 1; a = () => x; }
                                //     { let x = 100; b = () => x; }
                                //     console.log(a()); // should print '1'
                                //     console.log(b()); // should print '100'
                                //     OR
                                //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
                                //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
                                //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
                                //       they will not collide with anything
                                var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */;
                                var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
                                var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
                                links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
                            }
                            else {
                                links.isDeclarationWithCollidingName = false;
                            }
                        }
                    }
                    return links.isDeclarationWithCollidingName;
                }
                return false;
            }
            // When resolved as an expression identifier, if the given node references a nested block scoped entity with
            // a name that either hides an existing name or might hide it when compiled downlevel,
            // return the declaration of that entity. Otherwise, return undefined.
            function getReferencedDeclarationWithCollidingName(nodeIn) {
                if (!ts.isGeneratedIdentifier(nodeIn)) {
                    var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
                    if (node) {
                        var symbol = getReferencedValueSymbol(node);
                        if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
                            return symbol.valueDeclaration;
                        }
                    }
                }
                return undefined;
            }
            // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
            // existing name or might hide a name when compiled downlevel
            function isDeclarationWithCollidingName(nodeIn) {
                var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
                if (node) {
                    var symbol = getSymbolOfNode(node);
                    if (symbol) {
                        return isSymbolOfDeclarationWithCollidingName(symbol);
                    }
                }
                return false;
            }
            function isValueAliasDeclaration(node) {
                switch (node.kind) {
                    case 246 /* ImportEqualsDeclaration */:
                    case 248 /* ImportClause */:
                    case 249 /* NamespaceImport */:
                    case 251 /* ImportSpecifier */:
                    case 255 /* ExportSpecifier */:
                        return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
                    case 253 /* ExportDeclaration */:
                        var exportClause = node.exportClause;
                        return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration);
                    case 252 /* ExportAssignment */:
                        return node.expression
                            && node.expression.kind === 71 /* Identifier */
                            ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol)
                            : true;
                }
                return false;
            }
            function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
                var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
                if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
                    // parent is not source file or it is not reference to internal module
                    return false;
                }
                var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
                return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
            }
            function isAliasResolvedToValue(symbol) {
                var target = resolveAlias(symbol);
                if (target === unknownSymbol) {
                    return true;
                }
                // const enums and modules that contain only const enums are not considered values from the emit perspective
                // unless 'preserveConstEnums' option is set to true
                return !!(target.flags & 67220415 /* Value */) &&
                    (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
            }
            function isConstEnumOrConstEnumOnlyModule(s) {
                return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
            }
            function isReferencedAliasDeclaration(node, checkChildren) {
                if (ts.isAliasSymbolDeclaration(node)) {
                    var symbol = getSymbolOfNode(node);
                    if (symbol && getSymbolLinks(symbol).referenced) {
                        return true;
                    }
                    var target = getSymbolLinks(symbol).target; // TODO: GH#18217
                    if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
                        target.flags & 67220415 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
                        // An `export import ... =` of a value symbol is always considered referenced
                        return true;
                    }
                }
                if (checkChildren) {
                    return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
                }
                return false;
            }
            function isImplementationOfOverload(node) {
                if (ts.nodeIsPresent(node.body)) {
                    if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
                        return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
                    var symbol = getSymbolOfNode(node);
                    var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
                    // If this function body corresponds to function with multiple signature, it is implementation of overload
                    // e.g.: function foo(a: string): string;
                    //       function foo(a: number): number;
                    //       function foo(a: any) { // This is implementation of the overloads
                    //           return a;
                    //       }
                    return signaturesOfSymbol.length > 1 ||
                        // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
                        // e.g.: function foo(a: string): string;
                        //       function foo(a: any) { // This is implementation of the overloads
                        //           return a;
                        //       }
                        (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
                }
                return false;
            }
            function isRequiredInitializedParameter(parameter) {
                return !!strictNullChecks &&
                    !isOptionalParameter(parameter) &&
                    !ts.isJSDocParameterTag(parameter) &&
                    !!parameter.initializer &&
                    !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
            }
            function isOptionalUninitializedParameterProperty(parameter) {
                return strictNullChecks &&
                    isOptionalParameter(parameter) &&
                    !parameter.initializer &&
                    ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
            }
            function isExpandoFunctionDeclaration(node) {
                var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
                if (!declaration) {
                    return false;
                }
                var symbol = getSymbolOfNode(declaration);
                if (!symbol || !(symbol.flags & 16 /* Function */)) {
                    return false;
                }
                return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); });
            }
            function getPropertiesOfContainerFunction(node) {
                var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
                if (!declaration) {
                    return ts.emptyArray;
                }
                var symbol = getSymbolOfNode(declaration);
                return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
            }
            function getNodeCheckFlags(node) {
                return getNodeLinks(node).flags || 0;
            }
            function getEnumMemberValue(node) {
                computeEnumMemberValues(node.parent);
                return getNodeLinks(node).enumMemberValue;
            }
            function canHaveConstantValue(node) {
                switch (node.kind) {
                    case 276 /* EnumMember */:
                    case 187 /* PropertyAccessExpression */:
                    case 188 /* ElementAccessExpression */:
                        return true;
                }
                return false;
            }
            function getConstantValue(node) {
                if (node.kind === 276 /* EnumMember */) {
                    return getEnumMemberValue(node);
                }
                var symbol = getNodeLinks(node).resolvedSymbol;
                if (symbol && (symbol.flags & 8 /* EnumMember */)) {
                    // inline property\index accesses only for const enums
                    var member = symbol.valueDeclaration;
                    if (ts.isEnumConst(member.parent)) {
                        return getEnumMemberValue(member);
                    }
                }
                return undefined;
            }
            function isFunctionType(type) {
                return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
            }
            function getTypeReferenceSerializationKind(typeNameIn, location) {
                // ensure both `typeName` and `location` are parse tree nodes.
                var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
                if (!typeName)
                    return ts.TypeReferenceSerializationKind.Unknown;
                if (location) {
                    location = ts.getParseTreeNode(location);
                    if (!location)
                        return ts.TypeReferenceSerializationKind.Unknown;
                }
                // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
                var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
                // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
                var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
                if (valueSymbol && valueSymbol === typeSymbol) {
                    var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
                    if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
                        return ts.TypeReferenceSerializationKind.Promise;
                    }
                    var constructorType = getTypeOfSymbol(valueSymbol);
                    if (constructorType && isConstructorType(constructorType)) {
                        return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
                    }
                }
                // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
                if (!typeSymbol) {
                    return ts.TypeReferenceSerializationKind.Unknown;
                }
                var type = getDeclaredTypeOfSymbol(typeSymbol);
                if (type === errorType) {
                    return ts.TypeReferenceSerializationKind.Unknown;
                }
                else if (type.flags & 3 /* AnyOrUnknown */) {
                    return ts.TypeReferenceSerializationKind.ObjectType;
                }
                else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) {
                    return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
                }
                else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) {
                    return ts.TypeReferenceSerializationKind.BooleanType;
                }
                else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) {
                    return ts.TypeReferenceSerializationKind.NumberLikeType;
                }
                else if (isTypeAssignableToKind(type, 68 /* StringLike */)) {
                    return ts.TypeReferenceSerializationKind.StringLikeType;
                }
                else if (isTupleType(type)) {
                    return ts.TypeReferenceSerializationKind.ArrayLikeType;
                }
                else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) {
                    return ts.TypeReferenceSerializationKind.ESSymbolType;
                }
                else if (isFunctionType(type)) {
                    return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
                }
                else if (isArrayType(type)) {
                    return ts.TypeReferenceSerializationKind.ArrayLikeType;
                }
                else {
                    return ts.TypeReferenceSerializationKind.ObjectType;
                }
            }
            function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
                var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
                if (!declaration) {
                    return ts.createToken(119 /* AnyKeyword */);
                }
                // Get type of the symbol if this is the valid symbol otherwise get type at location
                var symbol = getSymbolOfNode(declaration);
                var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
                    ? getWidenedLiteralType(getTypeOfSymbol(symbol))
                    : errorType;
                if (type.flags & 2048 /* UniqueESSymbol */ &&
                    type.symbol === symbol) {
                    flags |= 1048576 /* AllowUniqueESSymbolType */;
                }
                if (addUndefined) {
                    type = getOptionalType(type);
                }
                return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
            }
            function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
                var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
                if (!signatureDeclaration) {
                    return ts.createToken(119 /* AnyKeyword */);
                }
                var signature = getSignatureFromDeclaration(signatureDeclaration);
                return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
            }
            function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
                var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
                if (!expr) {
                    return ts.createToken(119 /* AnyKeyword */);
                }
                var type = getWidenedType(getRegularTypeOfExpression(expr));
                return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
            }
            function hasGlobalName(name) {
                return globals.has(ts.escapeLeadingUnderscores(name));
            }
            function getReferencedValueSymbol(reference, startInDeclarationContainer) {
                var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
                if (resolvedSymbol) {
                    return resolvedSymbol;
                }
                var location = reference;
                if (startInDeclarationContainer) {
                    // When resolving the name of a declaration as a value, we need to start resolution
                    // at a point outside of the declaration.
                    var parent = reference.parent;
                    if (ts.isDeclaration(parent) && reference === parent.name) {
                        location = getDeclarationContainer(parent);
                    }
                }
                return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
            }
            function getReferencedValueDeclaration(referenceIn) {
                if (!ts.isGeneratedIdentifier(referenceIn)) {
                    var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
                    if (reference) {
                        var symbol = getReferencedValueSymbol(reference);
                        if (symbol) {
                            return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
                        }
                    }
                }
                return undefined;
            }
            function isLiteralConstDeclaration(node) {
                if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
                    var type = getTypeOfSymbol(getSymbolOfNode(node));
                    return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */);
                }
                return false;
            }
            function literalTypeToNode(type, enclosing) {
                var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing)
                    : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
                return enumResult || ts.createLiteral(type.value);
            }
            function createLiteralConstValue(node) {
                var type = getTypeOfSymbol(getSymbolOfNode(node));
                return literalTypeToNode(type, node);
            }
            function createResolver() {
                // this variable and functions that use it are deliberately moved here from the outer scope
                // to avoid scope pollution
                var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
                var fileToDirective;
                if (resolvedTypeReferenceDirectives) {
                    // populate reverse mapping: file path -> type reference directive that was resolved to this file
                    fileToDirective = ts.createMap();
                    resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
                        if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
                            return;
                        }
                        var file = host.getSourceFile(resolvedDirective.resolvedFileName);
                        fileToDirective.set(file.path, key);
                    });
                }
                return {
                    getReferencedExportContainer: getReferencedExportContainer,
                    getReferencedImportDeclaration: getReferencedImportDeclaration,
                    getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
                    isDeclarationWithCollidingName: isDeclarationWithCollidingName,
                    isValueAliasDeclaration: function (node) {
                        node = ts.getParseTreeNode(node);
                        // Synthesized nodes are always treated like values.
                        return node ? isValueAliasDeclaration(node) : true;
                    },
                    hasGlobalName: hasGlobalName,
                    isReferencedAliasDeclaration: function (node, checkChildren) {
                        node = ts.getParseTreeNode(node);
                        // Synthesized nodes are always treated as referenced.
                        return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
                    },
                    getNodeCheckFlags: function (node) {
                        node = ts.getParseTreeNode(node);
                        return node ? getNodeCheckFlags(node) : 0;
                    },
                    isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
                    isDeclarationVisible: isDeclarationVisible,
                    isImplementationOfOverload: isImplementationOfOverload,
                    isRequiredInitializedParameter: isRequiredInitializedParameter,
                    isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
                    isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
                    getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
                    createTypeOfDeclaration: createTypeOfDeclaration,
                    createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
                    createTypeOfExpression: createTypeOfExpression,
                    createLiteralConstValue: createLiteralConstValue,
                    isSymbolAccessible: isSymbolAccessible,
                    isEntityNameVisible: isEntityNameVisible,
                    getConstantValue: function (nodeIn) {
                        var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
                        return node ? getConstantValue(node) : undefined;
                    },
                    collectLinkedAliases: collectLinkedAliases,
                    getReferencedValueDeclaration: getReferencedValueDeclaration,
                    getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
                    isOptionalParameter: isOptionalParameter,
                    moduleExportsSomeValue: moduleExportsSomeValue,
                    isArgumentsLocalBinding: isArgumentsLocalBinding,
                    getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
                    getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
                    getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
                    isLiteralConstDeclaration: isLiteralConstDeclaration,
                    isLateBound: function (nodeIn) {
                        var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
                        var symbol = node && getSymbolOfNode(node);
                        return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
                    },
                    getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; },
                    getAllAccessorDeclarations: function (accessor) {
                        accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
                        var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */;
                        var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
                        var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
                        var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
                        var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor;
                        var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor;
                        return {
                            firstAccessor: firstAccessor,
                            secondAccessor: secondAccessor,
                            setAccessor: setAccessor,
                            getAccessor: getAccessor
                        };
                    },
                    getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }
                };
                function isInHeritageClause(node) {
                    return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */;
                }
                // defined here to avoid outer scope pollution
                function getTypeReferenceDirectivesForEntityName(node) {
                    // program does not have any files with type reference directives - bail out
                    if (!fileToDirective) {
                        return undefined;
                    }
                    // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
                    // qualified names can only be used as types\namespaces
                    // identifiers are treated as values only if they appear in type queries
                    var meaning = 67897832 /* Type */ | 1920 /* Namespace */;
                    if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
                        meaning = 67220415 /* Value */ | 1048576 /* ExportValue */;
                    }
                    var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
                    return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
                }
                // defined here to avoid outer scope pollution
                function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
                    // program does not have any files with type reference directives - bail out
                    if (!fileToDirective) {
                        return undefined;
                    }
                    if (!isSymbolFromTypeDeclarationFile(symbol)) {
                        return undefined;
                    }
                    // check what declarations in the symbol can contribute to the target meaning
                    var typeReferenceDirectives;
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        // check meaning of the local symbol to see if declaration needs to be analyzed further
                        if (decl.symbol && decl.symbol.flags & meaning) {
                            var file = ts.getSourceFileOfNode(decl);
                            var typeReferenceDirective = fileToDirective.get(file.path);
                            if (typeReferenceDirective) {
                                (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
                            }
                            else {
                                // found at least one entry that does not originate from type reference directive
                                return undefined;
                            }
                        }
                    }
                    return typeReferenceDirectives;
                }
                function isSymbolFromTypeDeclarationFile(symbol) {
                    // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
                    if (!symbol.declarations) {
                        return false;
                    }
                    // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
                    // external modules cannot define or contribute to type declaration files
                    var current = symbol;
                    while (true) {
                        var parent = getParentOfSymbol(current);
                        if (parent) {
                            current = parent;
                        }
                        else {
                            break;
                        }
                    }
                    if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
                        return false;
                    }
                    // check that at least one declaration of top level symbol originates from type declaration file
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        var file = ts.getSourceFileOfNode(decl);
                        if (fileToDirective.has(file.path)) {
                            return true;
                        }
                    }
                    return false;
                }
            }
            function getExternalModuleFileFromDeclaration(declaration) {
                var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
                var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
                if (!moduleSymbol) {
                    return undefined;
                }
                return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */);
            }
            function initializeTypeChecker() {
                // Bind all source files and propagate errors
                for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
                    var file = _a[_i];
                    ts.bindSourceFile(file, compilerOptions);
                }
                amalgamatedDuplicates = ts.createMap();
                // Initialize global symbol table
                var augmentations;
                for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
                    var file = _c[_b];
                    if (file.redirectInfo) {
                        continue;
                    }
                    if (!ts.isExternalOrCommonJsModule(file)) {
                        mergeSymbolTable(globals, file.locals);
                    }
                    if (file.jsGlobalAugmentations) {
                        mergeSymbolTable(globals, file.jsGlobalAugmentations);
                    }
                    if (file.patternAmbientModules && file.patternAmbientModules.length) {
                        patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
                    }
                    if (file.moduleAugmentations.length) {
                        (augmentations || (augmentations = [])).push(file.moduleAugmentations);
                    }
                    if (file.symbol && file.symbol.globalExports) {
                        // Merge in UMD exports with first-in-wins semantics (see #9771)
                        var source = file.symbol.globalExports;
                        source.forEach(function (sourceSymbol, id) {
                            if (!globals.has(id)) {
                                globals.set(id, sourceSymbol);
                            }
                        });
                    }
                }
                // We do global augmentations separately from module augmentations (and before creating global types) because they
                //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
                //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
                //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
                //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
                //       did module augmentations prior to finalizing the global types.
                if (augmentations) {
                    // merge _global_ module augmentations.
                    // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
                    for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) {
                        var list = augmentations_1[_d];
                        for (var _e = 0, list_1 = list; _e < list_1.length; _e++) {
                            var augmentation = list_1[_e];
                            if (!ts.isGlobalScopeAugmentation(augmentation.parent))
                                continue;
                            mergeModuleAugmentation(augmentation);
                        }
                    }
                }
                // Setup global builtins
                addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
                getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
                getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
                getSymbolLinks(unknownSymbol).type = errorType;
                // Initialize special types
                globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
                globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
                globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
                globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
                globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
                globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
                globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
                anyArrayType = createArrayType(anyType);
                autoArrayType = createArrayType(autoType);
                if (autoArrayType === emptyObjectType) {
                    // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
                    autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
                }
                globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1);
                anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
                globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
                if (augmentations) {
                    // merge _nonglobal_ module augmentations.
                    // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
                    for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) {
                        var list = augmentations_2[_f];
                        for (var _g = 0, list_2 = list; _g < list_2.length; _g++) {
                            var augmentation = list_2[_g];
                            if (ts.isGlobalScopeAugmentation(augmentation.parent))
                                continue;
                            mergeModuleAugmentation(augmentation);
                        }
                    }
                }
                amalgamatedDuplicates.forEach(function (_a) {
                    var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances;
                    var conflictingKeys = ts.arrayFrom(firstFileInstances.keys());
                    // If not many things conflict, issue individual errors
                    if (conflictingKeys.length < 8) {
                        addErrorsForDuplicates(firstFileInstances, secondFileInstances);
                        addErrorsForDuplicates(secondFileInstances, firstFileInstances);
                        return;
                    }
                    // Otheriwse issue top-level error since the files appear very identical in terms of what they appear
                    var list = conflictingKeys.join(", ");
                    diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file)));
                    diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file)));
                });
                amalgamatedDuplicates = undefined;
                function addErrorsForDuplicates(secondFileInstances, firstFileInstances) {
                    secondFileInstances.forEach(function (locations, symbolName) {
                        var firstFileEquivalent = firstFileInstances.get(symbolName);
                        var message = locations.blockScoped
                            ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
                            : ts.Diagnostics.Duplicate_identifier_0;
                        locations.instances.forEach(function (node) {
                            addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]);
                        });
                    });
                }
            }
            function checkExternalEmitHelpers(location, helpers) {
                if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
                    var sourceFile = ts.getSourceFileOfNode(location);
                    if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) {
                        var helpersModule = resolveHelpersModule(sourceFile, location);
                        if (helpersModule !== unknownSymbol) {
                            var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
                            for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) {
                                if (uncheckedHelpers & helper) {
                                    var name = getHelperName(helper);
                                    var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */);
                                    if (!symbol) {
                                        error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name);
                                    }
                                }
                            }
                        }
                        requestedExternalEmitHelpers |= helpers;
                    }
                }
            }
            function getHelperName(helper) {
                switch (helper) {
                    case 1 /* Extends */: return "__extends";
                    case 2 /* Assign */: return "__assign";
                    case 4 /* Rest */: return "__rest";
                    case 8 /* Decorate */: return "__decorate";
                    case 16 /* Metadata */: return "__metadata";
                    case 32 /* Param */: return "__param";
                    case 64 /* Awaiter */: return "__awaiter";
                    case 128 /* Generator */: return "__generator";
                    case 256 /* Values */: return "__values";
                    case 512 /* Read */: return "__read";
                    case 1024 /* Spread */: return "__spread";
                    case 2048 /* Await */: return "__await";
                    case 4096 /* AsyncGenerator */: return "__asyncGenerator";
                    case 8192 /* AsyncDelegator */: return "__asyncDelegator";
                    case 16384 /* AsyncValues */: return "__asyncValues";
                    case 32768 /* ExportStar */: return "__exportStar";
                    case 65536 /* MakeTemplateObject */: return "__makeTemplateObject";
                    default: return ts.Debug.fail("Unrecognized helper");
                }
            }
            function resolveHelpersModule(node, errorNode) {
                if (!externalHelpersModule) {
                    externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
                }
                return externalHelpersModule;
            }
            // GRAMMAR CHECKING
            function checkGrammarDecoratorsAndModifiers(node) {
                return checkGrammarDecorators(node) || checkGrammarModifiers(node);
            }
            function checkGrammarDecorators(node) {
                if (!node.decorators) {
                    return false;
                }
                if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
                    if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
                        return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
                    }
                    else {
                        return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
                    }
                }
                else if (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) {
                    var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
                    if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
                        return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
                    }
                }
                return false;
            }
            function checkGrammarModifiers(node) {
                var quickResult = reportObviousModifierErrors(node);
                if (quickResult !== undefined) {
                    return quickResult;
                }
                var lastStatic, lastDeclare, lastAsync, lastReadonly;
                var flags = 0 /* None */;
                for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
                    var modifier = _a[_i];
                    if (modifier.kind !== 132 /* ReadonlyKeyword */) {
                        if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) {
                            return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
                        }
                        if (node.kind === 160 /* IndexSignature */) {
                            return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
                        }
                    }
                    switch (modifier.kind) {
                        case 76 /* ConstKeyword */:
                            if (node.kind !== 241 /* EnumDeclaration */) {
                                return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */));
                            }
                            break;
                        case 114 /* PublicKeyword */:
                        case 113 /* ProtectedKeyword */:
                        case 112 /* PrivateKeyword */:
                            var text = visibilityToString(ts.modifierToFlag(modifier.kind));
                            if (flags & 28 /* AccessibilityModifier */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
                            }
                            else if (flags & 32 /* Static */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
                            }
                            else if (flags & 64 /* Readonly */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
                            }
                            else if (flags & 256 /* Async */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
                            }
                            else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
                            }
                            else if (flags & 128 /* Abstract */) {
                                if (modifier.kind === 112 /* PrivateKeyword */) {
                                    return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
                                }
                                else {
                                    return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
                                }
                            }
                            flags |= ts.modifierToFlag(modifier.kind);
                            break;
                        case 115 /* StaticKeyword */:
                            if (flags & 32 /* Static */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
                            }
                            else if (flags & 64 /* Readonly */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
                            }
                            else if (flags & 256 /* Async */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
                            }
                            else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
                            }
                            else if (node.kind === 149 /* Parameter */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
                            }
                            else if (flags & 128 /* Abstract */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
                            }
                            flags |= 32 /* Static */;
                            lastStatic = modifier;
                            break;
                        case 132 /* ReadonlyKeyword */:
                            if (flags & 64 /* Readonly */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
                            }
                            else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) {
                                // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
                                return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
                            }
                            flags |= 64 /* Readonly */;
                            lastReadonly = modifier;
                            break;
                        case 84 /* ExportKeyword */:
                            if (flags & 1 /* Export */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
                            }
                            else if (flags & 2 /* Ambient */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
                            }
                            else if (flags & 128 /* Abstract */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
                            }
                            else if (flags & 256 /* Async */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
                            }
                            else if (node.parent.kind === 238 /* ClassDeclaration */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
                            }
                            else if (node.kind === 149 /* Parameter */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
                            }
                            flags |= 1 /* Export */;
                            break;
                        case 79 /* DefaultKeyword */:
                            var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent;
                            if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
                            }
                            flags |= 512 /* Default */;
                            break;
                        case 124 /* DeclareKeyword */:
                            if (flags & 2 /* Ambient */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
                            }
                            else if (flags & 256 /* Async */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
                            }
                            else if (node.parent.kind === 238 /* ClassDeclaration */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
                            }
                            else if (node.kind === 149 /* Parameter */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
                            }
                            else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
                            }
                            flags |= 2 /* Ambient */;
                            lastDeclare = modifier;
                            break;
                        case 117 /* AbstractKeyword */:
                            if (flags & 128 /* Abstract */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
                            }
                            if (node.kind !== 238 /* ClassDeclaration */) {
                                if (node.kind !== 154 /* MethodDeclaration */ &&
                                    node.kind !== 152 /* PropertyDeclaration */ &&
                                    node.kind !== 156 /* GetAccessor */ &&
                                    node.kind !== 157 /* SetAccessor */) {
                                    return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
                                }
                                if (!(node.parent.kind === 238 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
                                    return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
                                }
                                if (flags & 32 /* Static */) {
                                    return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
                                }
                                if (flags & 8 /* Private */) {
                                    return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
                                }
                            }
                            flags |= 128 /* Abstract */;
                            break;
                        case 120 /* AsyncKeyword */:
                            if (flags & 256 /* Async */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
                            }
                            else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
                            }
                            else if (node.kind === 149 /* Parameter */) {
                                return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
                            }
                            flags |= 256 /* Async */;
                            lastAsync = modifier;
                            break;
                    }
                }
                if (node.kind === 155 /* Constructor */) {
                    if (flags & 32 /* Static */) {
                        return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
                    }
                    if (flags & 128 /* Abstract */) {
                        return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
                    }
                    else if (flags & 256 /* Async */) {
                        return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
                    }
                    else if (flags & 64 /* Readonly */) {
                        return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
                    }
                    return false;
                }
                else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
                    return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
                }
                else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
                    return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
                }
                else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
                    return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
                }
                if (flags & 256 /* Async */) {
                    return checkGrammarAsyncModifier(node, lastAsync);
                }
                return false;
            }
            /**
             * true | false: Early return this value from checkGrammarModifiers.
             * undefined: Need to do full checking on the modifiers.
             */
            function reportObviousModifierErrors(node) {
                return !node.modifiers
                    ? false
                    : shouldReportBadModifier(node)
                        ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
                        : undefined;
            }
            function shouldReportBadModifier(node) {
                switch (node.kind) {
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 155 /* Constructor */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 160 /* IndexSignature */:
                    case 242 /* ModuleDeclaration */:
                    case 247 /* ImportDeclaration */:
                    case 246 /* ImportEqualsDeclaration */:
                    case 253 /* ExportDeclaration */:
                    case 252 /* ExportAssignment */:
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                    case 149 /* Parameter */:
                        return false;
                    default:
                        if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) {
                            return false;
                        }
                        switch (node.kind) {
                            case 237 /* FunctionDeclaration */:
                                return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */);
                            case 238 /* ClassDeclaration */:
                                return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */);
                            case 239 /* InterfaceDeclaration */:
                            case 217 /* VariableStatement */:
                            case 240 /* TypeAliasDeclaration */:
                                return true;
                            case 241 /* EnumDeclaration */:
                                return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */);
                            default:
                                ts.Debug.fail();
                                return false;
                        }
                }
            }
            function nodeHasAnyModifiersExcept(node, allowedModifier) {
                return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
            }
            function checkGrammarAsyncModifier(node, asyncModifier) {
                switch (node.kind) {
                    case 154 /* MethodDeclaration */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        return false;
                }
                return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
            }
            function checkGrammarForDisallowedTrailingComma(list, diag) {
                if (diag === void 0) {
                    diag = ts.Diagnostics.Trailing_comma_not_allowed;
                }
                if (list && list.hasTrailingComma) {
                    return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
                }
                return false;
            }
            function checkGrammarTypeParameterList(typeParameters, file) {
                if (typeParameters && typeParameters.length === 0) {
                    var start = typeParameters.pos - "<".length;
                    var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
                    return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
                }
                return false;
            }
            function checkGrammarParameterList(parameters) {
                var seenOptionalParameter = false;
                var parameterCount = parameters.length;
                for (var i = 0; i < parameterCount; i++) {
                    var parameter = parameters[i];
                    if (parameter.dotDotDotToken) {
                        if (i !== (parameterCount - 1)) {
                            return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
                        }
                        if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
                            checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
                        }
                        if (ts.isBindingPattern(parameter.name)) {
                            return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
                        }
                        if (parameter.questionToken) {
                            return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
                        }
                        if (parameter.initializer) {
                            return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
                        }
                    }
                    else if (parameter.questionToken) {
                        seenOptionalParameter = true;
                        if (parameter.initializer) {
                            return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
                        }
                    }
                    else if (seenOptionalParameter && !parameter.initializer) {
                        return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
                    }
                }
            }
            function getNonSimpleParameters(parameters) {
                return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
            }
            function checkGrammarForUseStrictSimpleParameterList(node) {
                if (languageVersion >= 3 /* ES2016 */) {
                    var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
                    if (useStrictDirective_1) {
                        var nonSimpleParameters = getNonSimpleParameters(node.parameters);
                        if (ts.length(nonSimpleParameters)) {
                            ts.forEach(nonSimpleParameters, function (parameter) {
                                addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
                            });
                            var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
                            addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
                            return true;
                        }
                    }
                }
                return false;
            }
            function checkGrammarFunctionLikeDeclaration(node) {
                // Prevent cascading error by short-circuit
                var file = ts.getSourceFileOfNode(node);
                return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
                    checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
                    (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
            }
            function checkGrammarClassLikeDeclaration(node) {
                var file = ts.getSourceFileOfNode(node);
                return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
            }
            function checkGrammarArrowFunction(node, file) {
                if (!ts.isArrowFunction(node)) {
                    return false;
                }
                var equalsGreaterThanToken = node.equalsGreaterThanToken;
                var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
                var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
                return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
            }
            function checkGrammarIndexSignatureParameters(node) {
                var parameter = node.parameters[0];
                if (node.parameters.length !== 1) {
                    if (parameter) {
                        return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
                    }
                    else {
                        return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
                    }
                }
                if (parameter.dotDotDotToken) {
                    return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
                }
                if (ts.hasModifiers(parameter)) {
                    return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
                }
                if (parameter.questionToken) {
                    return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
                }
                if (parameter.initializer) {
                    return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
                }
                if (!parameter.type) {
                    return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
                }
                if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) {
                    var type = getTypeFromTypeNode(parameter.type);
                    if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
                        return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type)));
                    }
                    if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) {
                        return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
                    }
                    return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number);
                }
                if (!node.type) {
                    return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
                }
                return false;
            }
            function checkGrammarIndexSignature(node) {
                // Prevent cascading error by short-circuit
                return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
            }
            function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
                if (typeArguments && typeArguments.length === 0) {
                    var sourceFile = ts.getSourceFileOfNode(node);
                    var start = typeArguments.pos - "<".length;
                    var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
                    return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
                }
                return false;
            }
            function checkGrammarTypeArguments(node, typeArguments) {
                return checkGrammarForDisallowedTrailingComma(typeArguments) ||
                    checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
            }
            function checkGrammarForOmittedArgument(args) {
                if (args) {
                    for (var _i = 0, args_5 = args; _i < args_5.length; _i++) {
                        var arg = args_5[_i];
                        if (arg.kind === 208 /* OmittedExpression */) {
                            return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
                        }
                    }
                }
                return false;
            }
            function checkGrammarArguments(args) {
                return checkGrammarForOmittedArgument(args);
            }
            function checkGrammarHeritageClause(node) {
                var types = node.types;
                if (checkGrammarForDisallowedTrailingComma(types)) {
                    return true;
                }
                if (types && types.length === 0) {
                    var listType = ts.tokenToString(node.token);
                    return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
                }
                return ts.some(types, checkGrammarExpressionWithTypeArguments);
            }
            function checkGrammarExpressionWithTypeArguments(node) {
                return checkGrammarTypeArguments(node, node.typeArguments);
            }
            function checkGrammarClassDeclarationHeritageClauses(node) {
                var seenExtendsClause = false;
                var seenImplementsClause = false;
                if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
                    for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
                        var heritageClause = _a[_i];
                        if (heritageClause.token === 85 /* ExtendsKeyword */) {
                            if (seenExtendsClause) {
                                return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
                            }
                            if (seenImplementsClause) {
                                return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
                            }
                            if (heritageClause.types.length > 1) {
                                return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
                            }
                            seenExtendsClause = true;
                        }
                        else {
                            ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */);
                            if (seenImplementsClause) {
                                return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
                            }
                            seenImplementsClause = true;
                        }
                        // Grammar checking heritageClause inside class declaration
                        checkGrammarHeritageClause(heritageClause);
                    }
                }
            }
            function checkGrammarInterfaceDeclaration(node) {
                var seenExtendsClause = false;
                if (node.heritageClauses) {
                    for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
                        var heritageClause = _a[_i];
                        if (heritageClause.token === 85 /* ExtendsKeyword */) {
                            if (seenExtendsClause) {
                                return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
                            }
                            seenExtendsClause = true;
                        }
                        else {
                            ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */);
                            return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
                        }
                        // Grammar checking heritageClause inside class declaration
                        checkGrammarHeritageClause(heritageClause);
                    }
                }
                return false;
            }
            function checkGrammarComputedPropertyName(node) {
                // If node is not a computedPropertyName, just skip the grammar checking
                if (node.kind !== 147 /* ComputedPropertyName */) {
                    return false;
                }
                var computedPropertyName = node;
                if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) {
                    return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
                }
                return false;
            }
            function checkGrammarForGenerator(node) {
                if (node.asteriskToken) {
                    ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ ||
                        node.kind === 194 /* FunctionExpression */ ||
                        node.kind === 154 /* MethodDeclaration */);
                    if (node.flags & 4194304 /* Ambient */) {
                        return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
                    }
                    if (!node.body) {
                        return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
                    }
                }
            }
            function checkGrammarForInvalidQuestionMark(questionToken, message) {
                return !!questionToken && grammarErrorOnNode(questionToken, message);
            }
            function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
                return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
            }
            function checkGrammarObjectLiteralExpression(node, inDestructuring) {
                var Flags;
                (function (Flags) {
                    Flags[Flags["Property"] = 1] = "Property";
                    Flags[Flags["GetAccessor"] = 2] = "GetAccessor";
                    Flags[Flags["SetAccessor"] = 4] = "SetAccessor";
                    Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor";
                })(Flags || (Flags = {}));
                var seen = ts.createUnderscoreEscapedMap();
                for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
                    var prop = _a[_i];
                    if (prop.kind === 275 /* SpreadAssignment */) {
                        continue;
                    }
                    var name = prop.name;
                    if (name.kind === 147 /* ComputedPropertyName */) {
                        // If the name is not a ComputedPropertyName, the grammar checking will skip it
                        checkGrammarComputedPropertyName(name);
                    }
                    if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
                        // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
                        // outside of destructuring it is a syntax error
                        return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
                    }
                    // Modifiers are never allowed on properties except for 'async' on a method declaration
                    if (prop.modifiers) {
                        for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
                            var mod = _c[_b];
                            if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) {
                                grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
                            }
                        }
                    }
                    // ECMA-262 11.1.5 Object Initializer
                    // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
                    // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
                    // IsDataDescriptor(propId.descriptor) is true.
                    //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
                    //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
                    //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
                    // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
                    var currentKind = void 0;
                    switch (prop.kind) {
                        case 274 /* ShorthandPropertyAssignment */:
                            checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
                        /* tslint:disable:no-switch-case-fall-through */
                        case 273 /* PropertyAssignment */:
                            // Grammar checking for computedPropertyName and shorthandPropertyAssignment
                            checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
                            if (name.kind === 8 /* NumericLiteral */) {
                                checkGrammarNumericLiteral(name);
                            }
                        // falls through
                        case 154 /* MethodDeclaration */:
                            currentKind = 1 /* Property */;
                            break;
                        case 156 /* GetAccessor */:
                            currentKind = 2 /* GetAccessor */;
                            break;
                        case 157 /* SetAccessor */:
                            currentKind = 4 /* SetAccessor */;
                            break;
                        default:
                            throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
                    }
                    var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
                    if (effectiveName === undefined) {
                        continue;
                    }
                    var existingKind = seen.get(effectiveName);
                    if (!existingKind) {
                        seen.set(effectiveName, currentKind);
                    }
                    else {
                        if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
                            grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
                        }
                        else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) {
                            if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) {
                                seen.set(effectiveName, currentKind | existingKind);
                            }
                            else {
                                return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
                            }
                        }
                        else {
                            return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
                        }
                    }
                }
            }
            function checkGrammarJsxElement(node) {
                checkGrammarTypeArguments(node, node.typeArguments);
                var seen = ts.createUnderscoreEscapedMap();
                for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
                    var attr = _a[_i];
                    if (attr.kind === 267 /* JsxSpreadAttribute */) {
                        continue;
                    }
                    var name = attr.name, initializer = attr.initializer;
                    if (!seen.get(name.escapedText)) {
                        seen.set(name.escapedText, true);
                    }
                    else {
                        return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
                    }
                    if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) {
                        return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
                    }
                }
            }
            function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
                if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
                    return true;
                }
                if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
                    if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) {
                        return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
                    }
                }
                if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) {
                    var variableList = forInOrOfStatement.initializer;
                    if (!checkGrammarVariableDeclarationList(variableList)) {
                        var declarations = variableList.declarations;
                        // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
                        // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
                        // For example:
                        //      var let = 10;
                        //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
                        //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
                        // We will then want to skip on grammar checking on variableList declaration
                        if (!declarations.length) {
                            return false;
                        }
                        if (declarations.length > 1) {
                            var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */
                                ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
                                : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
                            return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
                        }
                        var firstDeclaration = declarations[0];
                        if (firstDeclaration.initializer) {
                            var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */
                                ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
                                : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
                            return grammarErrorOnNode(firstDeclaration.name, diagnostic);
                        }
                        if (firstDeclaration.type) {
                            var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */
                                ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
                                : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
                            return grammarErrorOnNode(firstDeclaration, diagnostic);
                        }
                    }
                }
                return false;
            }
            function checkGrammarAccessor(accessor) {
                var kind = accessor.kind;
                if (languageVersion < 1 /* ES5 */) {
                    return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
                }
                else if (accessor.flags & 4194304 /* Ambient */) {
                    return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context);
                }
                else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
                    return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
                }
                else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
                    return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
                }
                else if (accessor.typeParameters) {
                    return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
                }
                else if (!doesAccessorHaveCorrectParameterCount(accessor)) {
                    return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ?
                        ts.Diagnostics.A_get_accessor_cannot_have_parameters :
                        ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
                }
                else if (kind === 157 /* SetAccessor */) {
                    if (accessor.type) {
                        return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
                    }
                    else {
                        var parameter = accessor.parameters[0];
                        if (parameter.dotDotDotToken) {
                            return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
                        }
                        else if (parameter.questionToken) {
                            return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
                        }
                        else if (parameter.initializer) {
                            return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
                        }
                    }
                }
                return false;
            }
            /** Does the accessor have the right number of parameters?
             * A get accessor has no parameters or a single `this` parameter.
             * A set accessor has one parameter or a `this` parameter and one more parameter.
             */
            function doesAccessorHaveCorrectParameterCount(accessor) {
                return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1);
            }
            function getAccessorThisParameter(accessor) {
                if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) {
                    return ts.getThisParameter(accessor);
                }
            }
            function checkGrammarTypeOperatorNode(node) {
                if (node.operator === 141 /* UniqueKeyword */) {
                    if (node.type.kind !== 138 /* SymbolKeyword */) {
                        return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(138 /* SymbolKeyword */));
                    }
                    var parent = ts.walkUpParenthesizedTypes(node.parent);
                    switch (parent.kind) {
                        case 235 /* VariableDeclaration */:
                            var decl = parent;
                            if (decl.name.kind !== 71 /* Identifier */) {
                                return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
                            }
                            if (!ts.isVariableDeclarationInVariableStatement(decl)) {
                                return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
                            }
                            if (!(decl.parent.flags & 2 /* Const */)) {
                                return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
                            }
                            break;
                        case 152 /* PropertyDeclaration */:
                            if (!ts.hasModifier(parent, 32 /* Static */) ||
                                !ts.hasModifier(parent, 64 /* Readonly */)) {
                                return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
                            }
                            break;
                        case 151 /* PropertySignature */:
                            if (!ts.hasModifier(parent, 64 /* Readonly */)) {
                                return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
                            }
                            break;
                        default:
                            return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
                    }
                }
            }
            function checkGrammarForInvalidDynamicName(node, message) {
                if (isNonBindableDynamicName(node)) {
                    return grammarErrorOnNode(node, message);
                }
            }
            function checkGrammarMethod(node) {
                if (checkGrammarFunctionLikeDeclaration(node)) {
                    return true;
                }
                if (node.kind === 154 /* MethodDeclaration */) {
                    if (node.parent.kind === 186 /* ObjectLiteralExpression */) {
                        // We only disallow modifier on a method declaration if it is a property of object-literal-expression
                        if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) {
                            return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
                        }
                        else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
                            return true;
                        }
                        else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
                            return true;
                        }
                        else if (node.body === undefined) {
                            return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
                        }
                    }
                    if (checkGrammarForGenerator(node)) {
                        return true;
                    }
                }
                if (ts.isClassLike(node.parent)) {
                    // Technically, computed properties in ambient contexts is disallowed
                    // for property declarations and accessors too, not just methods.
                    // However, property declarations disallow computed names in general,
                    // and accessors are not allowed in ambient contexts in general,
                    // so this error only really matters for methods.
                    if (node.flags & 4194304 /* Ambient */) {
                        return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
                    }
                    else if (node.kind === 154 /* MethodDeclaration */ && !node.body) {
                        return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
                    }
                }
                else if (node.parent.kind === 239 /* InterfaceDeclaration */) {
                    return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
                }
                else if (node.parent.kind === 166 /* TypeLiteral */) {
                    return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
                }
            }
            function checkGrammarBreakOrContinueStatement(node) {
                var current = node;
                while (current) {
                    if (ts.isFunctionLike(current)) {
                        return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
                    }
                    switch (current.kind) {
                        case 231 /* LabeledStatement */:
                            if (node.label && current.label.escapedText === node.label.escapedText) {
                                // found matching label - verify that label usage is correct
                                // continue can only target labels that are on iteration statements
                                var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */
                                    && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
                                if (isMisplacedContinueLabel) {
                                    return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
                                }
                                return false;
                            }
                            break;
                        case 230 /* SwitchStatement */:
                            if (node.kind === 227 /* BreakStatement */ && !node.label) {
                                // unlabeled break within switch statement - ok
                                return false;
                            }
                            break;
                        default:
                            if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
                                // unlabeled break or continue within iteration statement - ok
                                return false;
                            }
                            break;
                    }
                    current = current.parent;
                }
                if (node.label) {
                    var message = node.kind === 227 /* BreakStatement */
                        ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
                        : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
                    return grammarErrorOnNode(node, message);
                }
                else {
                    var message = node.kind === 227 /* BreakStatement */
                        ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
                        : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
                    return grammarErrorOnNode(node, message);
                }
            }
            function checkGrammarBindingElement(node) {
                if (node.dotDotDotToken) {
                    var elements = node.parent.elements;
                    if (node !== ts.last(elements)) {
                        return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
                    }
                    checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
                    if (node.propertyName) {
                        return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
                    }
                    if (node.initializer) {
                        // Error on equals token which immediately precedes the initializer
                        return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
                    }
                }
            }
            function isStringOrNumberLiteralExpression(expr) {
                return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ ||
                    expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ &&
                        expr.operand.kind === 8 /* NumericLiteral */;
            }
            function isSimpleLiteralEnumReference(expr) {
                if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
                    ts.isEntityNameExpression(expr.expression))
                    return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */);
            }
            function checkAmbientInitializer(node) {
                if (node.initializer) {
                    var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */);
                    var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
                    if (isConstOrReadonly && !node.type) {
                        if (isInvalidInitializer) {
                            return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
                        }
                    }
                    else {
                        return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
                    }
                    if (!isConstOrReadonly || isInvalidInitializer) {
                        return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
                    }
                }
            }
            function checkGrammarVariableDeclaration(node) {
                if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) {
                    if (node.flags & 4194304 /* Ambient */) {
                        checkAmbientInitializer(node);
                    }
                    else if (!node.initializer) {
                        if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
                            return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
                        }
                        if (ts.isVarConst(node)) {
                            return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
                        }
                    }
                }
                if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) {
                    return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
                }
                if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit &&
                    !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
                    checkESModuleMarker(node.name);
                }
                var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
                // 1. LexicalDeclaration : LetOrConst BindingList ;
                // It is a Syntax Error if the BoundNames of BindingList contains "let".
                // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
                // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
                // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
                // and its Identifier is eval or arguments
                return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
            }
            function checkESModuleMarker(name) {
                if (name.kind === 71 /* Identifier */) {
                    if (ts.idText(name) === "__esModule") {
                        return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
                    }
                }
                else {
                    var elements = name.elements;
                    for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
                        var element = elements_1[_i];
                        if (!ts.isOmittedExpression(element)) {
                            return checkESModuleMarker(element.name);
                        }
                    }
                }
                return false;
            }
            function checkGrammarNameInLetOrConstDeclarations(name) {
                if (name.kind === 71 /* Identifier */) {
                    if (name.originalKeywordKind === 110 /* LetKeyword */) {
                        return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
                    }
                }
                else {
                    var elements = name.elements;
                    for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
                        var element = elements_2[_i];
                        if (!ts.isOmittedExpression(element)) {
                            checkGrammarNameInLetOrConstDeclarations(element.name);
                        }
                    }
                }
                return false;
            }
            function checkGrammarVariableDeclarationList(declarationList) {
                var declarations = declarationList.declarations;
                if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
                    return true;
                }
                if (!declarationList.declarations.length) {
                    return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
                }
                return false;
            }
            function allowLetAndConstDeclarations(parent) {
                switch (parent.kind) {
                    case 220 /* IfStatement */:
                    case 221 /* DoStatement */:
                    case 222 /* WhileStatement */:
                    case 229 /* WithStatement */:
                    case 223 /* ForStatement */:
                    case 224 /* ForInStatement */:
                    case 225 /* ForOfStatement */:
                        return false;
                    case 231 /* LabeledStatement */:
                        return allowLetAndConstDeclarations(parent.parent);
                }
                return true;
            }
            function checkGrammarForDisallowedLetOrConstStatement(node) {
                if (!allowLetAndConstDeclarations(node.parent)) {
                    if (ts.isLet(node.declarationList)) {
                        return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
                    }
                    else if (ts.isVarConst(node.declarationList)) {
                        return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
                    }
                }
            }
            function checkGrammarMetaProperty(node) {
                var escapedText = node.name.escapedText;
                switch (node.keywordToken) {
                    case 94 /* NewKeyword */:
                        if (escapedText !== "target") {
                            return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target");
                        }
                        break;
                    case 91 /* ImportKeyword */:
                        if (escapedText !== "meta") {
                            return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta");
                        }
                        break;
                }
            }
            function hasParseDiagnostics(sourceFile) {
                return sourceFile.parseDiagnostics.length > 0;
            }
            function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
                var sourceFile = ts.getSourceFileOfNode(node);
                if (!hasParseDiagnostics(sourceFile)) {
                    var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
                    diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
                    return true;
                }
                return false;
            }
            function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
                var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
                if (!hasParseDiagnostics(sourceFile)) {
                    diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
                    return true;
                }
                return false;
            }
            function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
                var sourceFile = ts.getSourceFileOfNode(node);
                if (!hasParseDiagnostics(sourceFile)) {
                    diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
                    return true;
                }
                return false;
            }
            function checkGrammarConstructorTypeParameters(node) {
                var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
                var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
                if (range) {
                    var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
                    return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
                }
            }
            function checkGrammarConstructorTypeAnnotation(node) {
                var type = ts.getEffectiveReturnTypeNode(node);
                if (type) {
                    return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
                }
            }
            function checkGrammarProperty(node) {
                if (ts.isClassLike(node.parent)) {
                    if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
                        return true;
                    }
                }
                else if (node.parent.kind === 239 /* InterfaceDeclaration */) {
                    if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
                        return true;
                    }
                    if (node.initializer) {
                        return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
                    }
                }
                else if (node.parent.kind === 166 /* TypeLiteral */) {
                    if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
                        return true;
                    }
                    if (node.initializer) {
                        return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
                    }
                }
                if (node.flags & 4194304 /* Ambient */) {
                    checkAmbientInitializer(node);
                }
                if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
                    node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
                    return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
                }
            }
            function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
                // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
                // interfaces and imports categories:
                //
                //  DeclarationElement:
                //     ExportAssignment
                //     export_opt   InterfaceDeclaration
                //     export_opt   TypeAliasDeclaration
                //     export_opt   ImportDeclaration
                //     export_opt   ExternalImportDeclaration
                //     export_opt   AmbientDeclaration
                //
                // TODO: The spec needs to be amended to reflect this grammar.
                if (node.kind === 239 /* InterfaceDeclaration */ ||
                    node.kind === 240 /* TypeAliasDeclaration */ ||
                    node.kind === 247 /* ImportDeclaration */ ||
                    node.kind === 246 /* ImportEqualsDeclaration */ ||
                    node.kind === 253 /* ExportDeclaration */ ||
                    node.kind === 252 /* ExportAssignment */ ||
                    node.kind === 245 /* NamespaceExportDeclaration */ ||
                    ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
                    return false;
                }
                return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file);
            }
            function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
                for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
                    var decl = _a[_i];
                    if (ts.isDeclaration(decl) || decl.kind === 217 /* VariableStatement */) {
                        if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
                            return true;
                        }
                    }
                }
                return false;
            }
            function checkGrammarSourceFile(node) {
                return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
            }
            function checkGrammarStatementInAmbientContext(node) {
                if (node.flags & 4194304 /* Ambient */) {
                    // An accessors is already reported about the ambient context
                    if (ts.isAccessor(node.parent)) {
                        return getNodeLinks(node).hasReportedStatementInAmbientContext = true;
                    }
                    // Find containing block which is either Block, ModuleBlock, SourceFile
                    var links = getNodeLinks(node);
                    if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) {
                        return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
                    }
                    // We are either parented by another statement, or some sort of block.
                    // If we're in a block, we only want to really report an error once
                    // to prevent noisiness.  So use a bit on the block to indicate if
                    // this has already been reported, and don't report if it has.
                    //
                    if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) {
                        var links_2 = getNodeLinks(node.parent);
                        // Check if the containing block ever report this error
                        if (!links_2.hasReportedStatementInAmbientContext) {
                            return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
                        }
                    }
                    else {
                        // We must be parented by a statement.  If so, there's no need
                        // to report the error as our parent will have already done it.
                        // Debug.assert(isStatement(node.parent));
                    }
                }
                return false;
            }
            function checkGrammarNumericLiteral(node) {
                // Grammar checking
                if (node.numericLiteralFlags & 32 /* Octal */) {
                    var diagnosticMessage = void 0;
                    if (languageVersion >= 1 /* ES5 */) {
                        diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
                    }
                    else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) {
                        diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
                    }
                    else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) {
                        diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
                    }
                    if (diagnosticMessage) {
                        var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */;
                        var literal = (withMinus ? "-" : "") + "0o" + node.text;
                        return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
                    }
                }
                return false;
            }
            function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
                var sourceFile = ts.getSourceFileOfNode(node);
                if (!hasParseDiagnostics(sourceFile)) {
                    var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
                    diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
                    return true;
                }
                return false;
            }
            function getAmbientModules() {
                if (!ambientModulesCache) {
                    ambientModulesCache = [];
                    globals.forEach(function (global, sym) {
                        // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
                        if (ambientModuleSymbolRegex.test(sym)) {
                            ambientModulesCache.push(global);
                        }
                    });
                }
                return ambientModulesCache;
            }
            function checkGrammarImportCallExpression(node) {
                if (moduleKind === ts.ModuleKind.ES2015) {
                    return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext);
                }
                if (node.typeArguments) {
                    return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
                }
                var nodeArguments = node.arguments;
                if (nodeArguments.length !== 1) {
                    return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
                }
                // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
                // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
                if (ts.isSpreadElement(nodeArguments[0])) {
                    return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
                }
                return false;
            }
        }
        ts.createTypeChecker = createTypeChecker;
        /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
        function isDeclarationNameOrImportPropertyName(name) {
            switch (name.parent.kind) {
                case 251 /* ImportSpecifier */:
                case 255 /* ExportSpecifier */:
                    return ts.isIdentifier(name);
                default:
                    return ts.isDeclarationName(name);
            }
        }
        function isSomeImportDeclaration(decl) {
            switch (decl.kind) {
                case 248 /* ImportClause */: // For default import
                case 246 /* ImportEqualsDeclaration */:
                case 249 /* NamespaceImport */:
                case 251 /* ImportSpecifier */: // For rename import `x as y`
                    return true;
                case 71 /* Identifier */:
                    // For regular import, `decl` is an Identifier under the ImportSpecifier.
                    return decl.parent.kind === 251 /* ImportSpecifier */;
                default:
                    return false;
            }
        }
        var JsxNames;
        (function (JsxNames) {
            // tslint:disable variable-name
            JsxNames.JSX = "JSX";
            JsxNames.IntrinsicElements = "IntrinsicElements";
            JsxNames.ElementClass = "ElementClass";
            JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
            JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
            JsxNames.Element = "Element";
            JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
            JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
            JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
            // tslint:enable variable-name
        })(JsxNames || (JsxNames = {}));
        function typeIsLiteralType(type) {
            return !!(type.flags & 448 /* Literal */);
        }
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        function createSynthesizedNode(kind) {
            var node = ts.createNode(kind, -1, -1);
            node.flags |= 8 /* Synthesized */;
            return node;
        }
        /* @internal */
        function updateNode(updated, original) {
            if (updated !== original) {
                setOriginalNode(updated, original);
                setTextRange(updated, original);
                ts.aggregateTransformFlags(updated);
            }
            return updated;
        }
        ts.updateNode = updateNode;
        /**
         * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
         */
        function createNodeArray(elements, hasTrailingComma) {
            if (!elements || elements === ts.emptyArray) {
                elements = [];
            }
            else if (ts.isNodeArray(elements)) {
                return elements;
            }
            var array = elements;
            array.pos = -1;
            array.end = -1;
            array.hasTrailingComma = hasTrailingComma;
            return array;
        }
        ts.createNodeArray = createNodeArray;
        /**
         * Creates a shallow, memberwise clone of a node with no source map location.
         */
        /* @internal */
        function getSynthesizedClone(node) {
            // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
            // the original node. We also need to exclude specific properties and only include own-
            // properties (to skip members already defined on the shared prototype).
            if (node === undefined) {
                return node;
            }
            var clone = createSynthesizedNode(node.kind);
            clone.flags |= node.flags;
            setOriginalNode(clone, node);
            for (var key in node) {
                if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
                    continue;
                }
                clone[key] = node[key];
            }
            return clone;
        }
        ts.getSynthesizedClone = getSynthesizedClone;
        function createLiteral(value, isSingleQuote) {
            if (typeof value === "number") {
                return createNumericLiteral(value + "");
            }
            if (typeof value === "boolean") {
                return value ? createTrue() : createFalse();
            }
            if (ts.isString(value)) {
                var res = createStringLiteral(value);
                if (isSingleQuote)
                    res.singleQuote = true;
                return res;
            }
            return createLiteralFromNode(value);
        }
        ts.createLiteral = createLiteral;
        function createNumericLiteral(value) {
            var node = createSynthesizedNode(8 /* NumericLiteral */);
            node.text = value;
            node.numericLiteralFlags = 0;
            return node;
        }
        ts.createNumericLiteral = createNumericLiteral;
        function createStringLiteral(text) {
            var node = createSynthesizedNode(9 /* StringLiteral */);
            node.text = text;
            return node;
        }
        ts.createStringLiteral = createStringLiteral;
        function createRegularExpressionLiteral(text) {
            var node = createSynthesizedNode(12 /* RegularExpressionLiteral */);
            node.text = text;
            return node;
        }
        ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
        function createLiteralFromNode(sourceNode) {
            var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
            node.textSourceNode = sourceNode;
            return node;
        }
        function createIdentifier(text, typeArguments) {
            var node = createSynthesizedNode(71 /* Identifier */);
            node.escapedText = ts.escapeLeadingUnderscores(text);
            node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
            node.autoGenerateFlags = 0 /* None */;
            node.autoGenerateId = 0;
            if (typeArguments) {
                node.typeArguments = createNodeArray(typeArguments);
            }
            return node;
        }
        ts.createIdentifier = createIdentifier;
        function updateIdentifier(node, typeArguments) {
            return node.typeArguments !== typeArguments
                ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
                : node;
        }
        ts.updateIdentifier = updateIdentifier;
        var nextAutoGenerateId = 0;
        function createTempVariable(recordTempVariable, reservedInNestedScopes) {
            var name = createIdentifier("");
            name.autoGenerateFlags = 1 /* Auto */;
            name.autoGenerateId = nextAutoGenerateId;
            nextAutoGenerateId++;
            if (recordTempVariable) {
                recordTempVariable(name);
            }
            if (reservedInNestedScopes) {
                name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
            }
            return name;
        }
        ts.createTempVariable = createTempVariable;
        /** Create a unique temporary variable for use in a loop. */
        function createLoopVariable() {
            var name = createIdentifier("");
            name.autoGenerateFlags = 2 /* Loop */;
            name.autoGenerateId = nextAutoGenerateId;
            nextAutoGenerateId++;
            return name;
        }
        ts.createLoopVariable = createLoopVariable;
        /** Create a unique name based on the supplied text. */
        function createUniqueName(text) {
            var name = createIdentifier(text);
            name.autoGenerateFlags = 3 /* Unique */;
            name.autoGenerateId = nextAutoGenerateId;
            nextAutoGenerateId++;
            return name;
        }
        ts.createUniqueName = createUniqueName;
        function createOptimisticUniqueName(text) {
            var name = createIdentifier(text);
            name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
            name.autoGenerateId = nextAutoGenerateId;
            nextAutoGenerateId++;
            return name;
        }
        ts.createOptimisticUniqueName = createOptimisticUniqueName;
        /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
        function createFileLevelUniqueName(text) {
            var name = createOptimisticUniqueName(text);
            name.autoGenerateFlags |= 32 /* FileLevel */;
            return name;
        }
        ts.createFileLevelUniqueName = createFileLevelUniqueName;
        function getGeneratedNameForNode(node, flags) {
            var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
            name.autoGenerateFlags = 4 /* Node */ | flags;
            name.autoGenerateId = nextAutoGenerateId;
            name.original = node;
            nextAutoGenerateId++;
            return name;
        }
        ts.getGeneratedNameForNode = getGeneratedNameForNode;
        // Punctuation
        function createToken(token) {
            return createSynthesizedNode(token);
        }
        ts.createToken = createToken;
        // Reserved words
        function createSuper() {
            return createSynthesizedNode(97 /* SuperKeyword */);
        }
        ts.createSuper = createSuper;
        function createThis() {
            return createSynthesizedNode(99 /* ThisKeyword */);
        }
        ts.createThis = createThis;
        function createNull() {
            return createSynthesizedNode(95 /* NullKeyword */);
        }
        ts.createNull = createNull;
        function createTrue() {
            return createSynthesizedNode(101 /* TrueKeyword */);
        }
        ts.createTrue = createTrue;
        function createFalse() {
            return createSynthesizedNode(86 /* FalseKeyword */);
        }
        ts.createFalse = createFalse;
        // Modifiers
        function createModifier(kind) {
            return createToken(kind);
        }
        ts.createModifier = createModifier;
        function createModifiersFromModifierFlags(flags) {
            var result = [];
            if (flags & 1 /* Export */) {
                result.push(createModifier(84 /* ExportKeyword */));
            }
            if (flags & 2 /* Ambient */) {
                result.push(createModifier(124 /* DeclareKeyword */));
            }
            if (flags & 512 /* Default */) {
                result.push(createModifier(79 /* DefaultKeyword */));
            }
            if (flags & 2048 /* Const */) {
                result.push(createModifier(76 /* ConstKeyword */));
            }
            if (flags & 4 /* Public */) {
                result.push(createModifier(114 /* PublicKeyword */));
            }
            if (flags & 8 /* Private */) {
                result.push(createModifier(112 /* PrivateKeyword */));
            }
            if (flags & 16 /* Protected */) {
                result.push(createModifier(113 /* ProtectedKeyword */));
            }
            if (flags & 128 /* Abstract */) {
                result.push(createModifier(117 /* AbstractKeyword */));
            }
            if (flags & 32 /* Static */) {
                result.push(createModifier(115 /* StaticKeyword */));
            }
            if (flags & 64 /* Readonly */) {
                result.push(createModifier(132 /* ReadonlyKeyword */));
            }
            if (flags & 256 /* Async */) {
                result.push(createModifier(120 /* AsyncKeyword */));
            }
            return result;
        }
        ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
        // Names
        function createQualifiedName(left, right) {
            var node = createSynthesizedNode(146 /* QualifiedName */);
            node.left = left;
            node.right = asName(right);
            return node;
        }
        ts.createQualifiedName = createQualifiedName;
        function updateQualifiedName(node, left, right) {
            return node.left !== left
                || node.right !== right
                ? updateNode(createQualifiedName(left, right), node)
                : node;
        }
        ts.updateQualifiedName = updateQualifiedName;
        function parenthesizeForComputedName(expression) {
            return ts.isCommaSequence(expression)
                ? createParen(expression)
                : expression;
        }
        function createComputedPropertyName(expression) {
            var node = createSynthesizedNode(147 /* ComputedPropertyName */);
            node.expression = parenthesizeForComputedName(expression);
            return node;
        }
        ts.createComputedPropertyName = createComputedPropertyName;
        function updateComputedPropertyName(node, expression) {
            return node.expression !== expression
                ? updateNode(createComputedPropertyName(expression), node)
                : node;
        }
        ts.updateComputedPropertyName = updateComputedPropertyName;
        // Signature elements
        function createTypeParameterDeclaration(name, constraint, defaultType) {
            var node = createSynthesizedNode(148 /* TypeParameter */);
            node.name = asName(name);
            node.constraint = constraint;
            node.default = defaultType;
            return node;
        }
        ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
        function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
            return node.name !== name
                || node.constraint !== constraint
                || node.default !== defaultType
                ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
                : node;
        }
        ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
        function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
            var node = createSynthesizedNode(149 /* Parameter */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.dotDotDotToken = dotDotDotToken;
            node.name = asName(name);
            node.questionToken = questionToken;
            node.type = type;
            node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
            return node;
        }
        ts.createParameter = createParameter;
        function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.dotDotDotToken !== dotDotDotToken
                || node.name !== name
                || node.questionToken !== questionToken
                || node.type !== type
                || node.initializer !== initializer
                ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
                : node;
        }
        ts.updateParameter = updateParameter;
        function createDecorator(expression) {
            var node = createSynthesizedNode(150 /* Decorator */);
            node.expression = ts.parenthesizeForAccess(expression);
            return node;
        }
        ts.createDecorator = createDecorator;
        function updateDecorator(node, expression) {
            return node.expression !== expression
                ? updateNode(createDecorator(expression), node)
                : node;
        }
        ts.updateDecorator = updateDecorator;
        // Type Elements
        function createPropertySignature(modifiers, name, questionToken, type, initializer) {
            var node = createSynthesizedNode(151 /* PropertySignature */);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.questionToken = questionToken;
            node.type = type;
            node.initializer = initializer;
            return node;
        }
        ts.createPropertySignature = createPropertySignature;
        function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
            return node.modifiers !== modifiers
                || node.name !== name
                || node.questionToken !== questionToken
                || node.type !== type
                || node.initializer !== initializer
                ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
                : node;
        }
        ts.updatePropertySignature = updatePropertySignature;
        function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
            var node = createSynthesizedNode(152 /* PropertyDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined;
            node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
            node.type = type;
            node.initializer = initializer;
            return node;
        }
        ts.createProperty = createProperty;
        function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 55 /* QuestionToken */ ? questionOrExclamationToken : undefined)
                || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 51 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
                || node.type !== type
                || node.initializer !== initializer
                ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
                : node;
        }
        ts.updateProperty = updateProperty;
        function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
            var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type);
            node.name = asName(name);
            node.questionToken = questionToken;
            return node;
        }
        ts.createMethodSignature = createMethodSignature;
        function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
            return node.typeParameters !== typeParameters
                || node.parameters !== parameters
                || node.type !== type
                || node.name !== name
                || node.questionToken !== questionToken
                ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
                : node;
        }
        ts.updateMethodSignature = updateMethodSignature;
        function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
            var node = createSynthesizedNode(154 /* MethodDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.asteriskToken = asteriskToken;
            node.name = asName(name);
            node.questionToken = questionToken;
            node.typeParameters = asNodeArray(typeParameters);
            node.parameters = createNodeArray(parameters);
            node.type = type;
            node.body = body;
            return node;
        }
        ts.createMethod = createMethod;
        function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.asteriskToken !== asteriskToken
                || node.name !== name
                || node.questionToken !== questionToken
                || node.typeParameters !== typeParameters
                || node.parameters !== parameters
                || node.type !== type
                || node.body !== body
                ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
                : node;
        }
        ts.updateMethod = updateMethod;
        function createConstructor(decorators, modifiers, parameters, body) {
            var node = createSynthesizedNode(155 /* Constructor */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.typeParameters = undefined;
            node.parameters = createNodeArray(parameters);
            node.type = undefined;
            node.body = body;
            return node;
        }
        ts.createConstructor = createConstructor;
        function updateConstructor(node, decorators, modifiers, parameters, body) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.parameters !== parameters
                || node.body !== body
                ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
                : node;
        }
        ts.updateConstructor = updateConstructor;
        function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
            var node = createSynthesizedNode(156 /* GetAccessor */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.typeParameters = undefined;
            node.parameters = createNodeArray(parameters);
            node.type = type;
            node.body = body;
            return node;
        }
        ts.createGetAccessor = createGetAccessor;
        function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.parameters !== parameters
                || node.type !== type
                || node.body !== body
                ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
                : node;
        }
        ts.updateGetAccessor = updateGetAccessor;
        function createSetAccessor(decorators, modifiers, name, parameters, body) {
            var node = createSynthesizedNode(157 /* SetAccessor */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.typeParameters = undefined;
            node.parameters = createNodeArray(parameters);
            node.body = body;
            return node;
        }
        ts.createSetAccessor = createSetAccessor;
        function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.parameters !== parameters
                || node.body !== body
                ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
                : node;
        }
        ts.updateSetAccessor = updateSetAccessor;
        function createCallSignature(typeParameters, parameters, type) {
            return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type);
        }
        ts.createCallSignature = createCallSignature;
        function updateCallSignature(node, typeParameters, parameters, type) {
            return updateSignatureDeclaration(node, typeParameters, parameters, type);
        }
        ts.updateCallSignature = updateCallSignature;
        function createConstructSignature(typeParameters, parameters, type) {
            return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type);
        }
        ts.createConstructSignature = createConstructSignature;
        function updateConstructSignature(node, typeParameters, parameters, type) {
            return updateSignatureDeclaration(node, typeParameters, parameters, type);
        }
        ts.updateConstructSignature = updateConstructSignature;
        function createIndexSignature(decorators, modifiers, parameters, type) {
            var node = createSynthesizedNode(160 /* IndexSignature */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.parameters = createNodeArray(parameters);
            node.type = type;
            return node;
        }
        ts.createIndexSignature = createIndexSignature;
        function updateIndexSignature(node, decorators, modifiers, parameters, type) {
            return node.parameters !== parameters
                || node.type !== type
                || node.decorators !== decorators
                || node.modifiers !== modifiers
                ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
                : node;
        }
        ts.updateIndexSignature = updateIndexSignature;
        /* @internal */
        function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
            var node = createSynthesizedNode(kind);
            node.typeParameters = asNodeArray(typeParameters);
            node.parameters = asNodeArray(parameters);
            node.type = type;
            node.typeArguments = asNodeArray(typeArguments);
            return node;
        }
        ts.createSignatureDeclaration = createSignatureDeclaration;
        function updateSignatureDeclaration(node, typeParameters, parameters, type) {
            return node.typeParameters !== typeParameters
                || node.parameters !== parameters
                || node.type !== type
                ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
                : node;
        }
        // Types
        function createKeywordTypeNode(kind) {
            return createSynthesizedNode(kind);
        }
        ts.createKeywordTypeNode = createKeywordTypeNode;
        function createTypePredicateNode(parameterName, type) {
            var node = createSynthesizedNode(161 /* TypePredicate */);
            node.parameterName = asName(parameterName);
            node.type = type;
            return node;
        }
        ts.createTypePredicateNode = createTypePredicateNode;
        function updateTypePredicateNode(node, parameterName, type) {
            return node.parameterName !== parameterName
                || node.type !== type
                ? updateNode(createTypePredicateNode(parameterName, type), node)
                : node;
        }
        ts.updateTypePredicateNode = updateTypePredicateNode;
        function createTypeReferenceNode(typeName, typeArguments) {
            var node = createSynthesizedNode(162 /* TypeReference */);
            node.typeName = asName(typeName);
            node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
            return node;
        }
        ts.createTypeReferenceNode = createTypeReferenceNode;
        function updateTypeReferenceNode(node, typeName, typeArguments) {
            return node.typeName !== typeName
                || node.typeArguments !== typeArguments
                ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
                : node;
        }
        ts.updateTypeReferenceNode = updateTypeReferenceNode;
        function createFunctionTypeNode(typeParameters, parameters, type) {
            return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type);
        }
        ts.createFunctionTypeNode = createFunctionTypeNode;
        function updateFunctionTypeNode(node, typeParameters, parameters, type) {
            return updateSignatureDeclaration(node, typeParameters, parameters, type);
        }
        ts.updateFunctionTypeNode = updateFunctionTypeNode;
        function createConstructorTypeNode(typeParameters, parameters, type) {
            return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type);
        }
        ts.createConstructorTypeNode = createConstructorTypeNode;
        function updateConstructorTypeNode(node, typeParameters, parameters, type) {
            return updateSignatureDeclaration(node, typeParameters, parameters, type);
        }
        ts.updateConstructorTypeNode = updateConstructorTypeNode;
        function createTypeQueryNode(exprName) {
            var node = createSynthesizedNode(165 /* TypeQuery */);
            node.exprName = exprName;
            return node;
        }
        ts.createTypeQueryNode = createTypeQueryNode;
        function updateTypeQueryNode(node, exprName) {
            return node.exprName !== exprName
                ? updateNode(createTypeQueryNode(exprName), node)
                : node;
        }
        ts.updateTypeQueryNode = updateTypeQueryNode;
        function createTypeLiteralNode(members) {
            var node = createSynthesizedNode(166 /* TypeLiteral */);
            node.members = createNodeArray(members);
            return node;
        }
        ts.createTypeLiteralNode = createTypeLiteralNode;
        function updateTypeLiteralNode(node, members) {
            return node.members !== members
                ? updateNode(createTypeLiteralNode(members), node)
                : node;
        }
        ts.updateTypeLiteralNode = updateTypeLiteralNode;
        function createArrayTypeNode(elementType) {
            var node = createSynthesizedNode(167 /* ArrayType */);
            node.elementType = ts.parenthesizeArrayTypeMember(elementType);
            return node;
        }
        ts.createArrayTypeNode = createArrayTypeNode;
        function updateArrayTypeNode(node, elementType) {
            return node.elementType !== elementType
                ? updateNode(createArrayTypeNode(elementType), node)
                : node;
        }
        ts.updateArrayTypeNode = updateArrayTypeNode;
        function createTupleTypeNode(elementTypes) {
            var node = createSynthesizedNode(168 /* TupleType */);
            node.elementTypes = createNodeArray(elementTypes);
            return node;
        }
        ts.createTupleTypeNode = createTupleTypeNode;
        function updateTupleTypeNode(node, elementTypes) {
            return node.elementTypes !== elementTypes
                ? updateNode(createTupleTypeNode(elementTypes), node)
                : node;
        }
        ts.updateTupleTypeNode = updateTupleTypeNode;
        function createOptionalTypeNode(type) {
            var node = createSynthesizedNode(169 /* OptionalType */);
            node.type = ts.parenthesizeArrayTypeMember(type);
            return node;
        }
        ts.createOptionalTypeNode = createOptionalTypeNode;
        function updateOptionalTypeNode(node, type) {
            return node.type !== type
                ? updateNode(createOptionalTypeNode(type), node)
                : node;
        }
        ts.updateOptionalTypeNode = updateOptionalTypeNode;
        function createRestTypeNode(type) {
            var node = createSynthesizedNode(170 /* RestType */);
            node.type = type;
            return node;
        }
        ts.createRestTypeNode = createRestTypeNode;
        function updateRestTypeNode(node, type) {
            return node.type !== type
                ? updateNode(createRestTypeNode(type), node)
                : node;
        }
        ts.updateRestTypeNode = updateRestTypeNode;
        function createUnionTypeNode(types) {
            return createUnionOrIntersectionTypeNode(171 /* UnionType */, types);
        }
        ts.createUnionTypeNode = createUnionTypeNode;
        function updateUnionTypeNode(node, types) {
            return updateUnionOrIntersectionTypeNode(node, types);
        }
        ts.updateUnionTypeNode = updateUnionTypeNode;
        function createIntersectionTypeNode(types) {
            return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types);
        }
        ts.createIntersectionTypeNode = createIntersectionTypeNode;
        function updateIntersectionTypeNode(node, types) {
            return updateUnionOrIntersectionTypeNode(node, types);
        }
        ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
        function createUnionOrIntersectionTypeNode(kind, types) {
            var node = createSynthesizedNode(kind);
            node.types = ts.parenthesizeElementTypeMembers(types);
            return node;
        }
        ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
        function updateUnionOrIntersectionTypeNode(node, types) {
            return node.types !== types
                ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
                : node;
        }
        function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
            var node = createSynthesizedNode(173 /* ConditionalType */);
            node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
            node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
            node.trueType = trueType;
            node.falseType = falseType;
            return node;
        }
        ts.createConditionalTypeNode = createConditionalTypeNode;
        function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
            return node.checkType !== checkType
                || node.extendsType !== extendsType
                || node.trueType !== trueType
                || node.falseType !== falseType
                ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
                : node;
        }
        ts.updateConditionalTypeNode = updateConditionalTypeNode;
        function createInferTypeNode(typeParameter) {
            var node = createSynthesizedNode(174 /* InferType */);
            node.typeParameter = typeParameter;
            return node;
        }
        ts.createInferTypeNode = createInferTypeNode;
        function updateInferTypeNode(node, typeParameter) {
            return node.typeParameter !== typeParameter
                ? updateNode(createInferTypeNode(typeParameter), node)
                : node;
        }
        ts.updateInferTypeNode = updateInferTypeNode;
        function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
            var node = createSynthesizedNode(181 /* ImportType */);
            node.argument = argument;
            node.qualifier = qualifier;
            node.typeArguments = asNodeArray(typeArguments);
            node.isTypeOf = isTypeOf;
            return node;
        }
        ts.createImportTypeNode = createImportTypeNode;
        function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
            return node.argument !== argument
                || node.qualifier !== qualifier
                || node.typeArguments !== typeArguments
                || node.isTypeOf !== isTypeOf
                ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
                : node;
        }
        ts.updateImportTypeNode = updateImportTypeNode;
        function createParenthesizedType(type) {
            var node = createSynthesizedNode(175 /* ParenthesizedType */);
            node.type = type;
            return node;
        }
        ts.createParenthesizedType = createParenthesizedType;
        function updateParenthesizedType(node, type) {
            return node.type !== type
                ? updateNode(createParenthesizedType(type), node)
                : node;
        }
        ts.updateParenthesizedType = updateParenthesizedType;
        function createThisTypeNode() {
            return createSynthesizedNode(176 /* ThisType */);
        }
        ts.createThisTypeNode = createThisTypeNode;
        function createTypeOperatorNode(operatorOrType, type) {
            var node = createSynthesizedNode(177 /* TypeOperator */);
            node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */;
            node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
            return node;
        }
        ts.createTypeOperatorNode = createTypeOperatorNode;
        function updateTypeOperatorNode(node, type) {
            return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
        }
        ts.updateTypeOperatorNode = updateTypeOperatorNode;
        function createIndexedAccessTypeNode(objectType, indexType) {
            var node = createSynthesizedNode(178 /* IndexedAccessType */);
            node.objectType = ts.parenthesizeElementTypeMember(objectType);
            node.indexType = indexType;
            return node;
        }
        ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
        function updateIndexedAccessTypeNode(node, objectType, indexType) {
            return node.objectType !== objectType
                || node.indexType !== indexType
                ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
                : node;
        }
        ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
        function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
            var node = createSynthesizedNode(179 /* MappedType */);
            node.readonlyToken = readonlyToken;
            node.typeParameter = typeParameter;
            node.questionToken = questionToken;
            node.type = type;
            return node;
        }
        ts.createMappedTypeNode = createMappedTypeNode;
        function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
            return node.readonlyToken !== readonlyToken
                || node.typeParameter !== typeParameter
                || node.questionToken !== questionToken
                || node.type !== type
                ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
                : node;
        }
        ts.updateMappedTypeNode = updateMappedTypeNode;
        function createLiteralTypeNode(literal) {
            var node = createSynthesizedNode(180 /* LiteralType */);
            node.literal = literal;
            return node;
        }
        ts.createLiteralTypeNode = createLiteralTypeNode;
        function updateLiteralTypeNode(node, literal) {
            return node.literal !== literal
                ? updateNode(createLiteralTypeNode(literal), node)
                : node;
        }
        ts.updateLiteralTypeNode = updateLiteralTypeNode;
        // Binding Patterns
        function createObjectBindingPattern(elements) {
            var node = createSynthesizedNode(182 /* ObjectBindingPattern */);
            node.elements = createNodeArray(elements);
            return node;
        }
        ts.createObjectBindingPattern = createObjectBindingPattern;
        function updateObjectBindingPattern(node, elements) {
            return node.elements !== elements
                ? updateNode(createObjectBindingPattern(elements), node)
                : node;
        }
        ts.updateObjectBindingPattern = updateObjectBindingPattern;
        function createArrayBindingPattern(elements) {
            var node = createSynthesizedNode(183 /* ArrayBindingPattern */);
            node.elements = createNodeArray(elements);
            return node;
        }
        ts.createArrayBindingPattern = createArrayBindingPattern;
        function updateArrayBindingPattern(node, elements) {
            return node.elements !== elements
                ? updateNode(createArrayBindingPattern(elements), node)
                : node;
        }
        ts.updateArrayBindingPattern = updateArrayBindingPattern;
        function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
            var node = createSynthesizedNode(184 /* BindingElement */);
            node.dotDotDotToken = dotDotDotToken;
            node.propertyName = asName(propertyName);
            node.name = asName(name);
            node.initializer = initializer;
            return node;
        }
        ts.createBindingElement = createBindingElement;
        function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
            return node.propertyName !== propertyName
                || node.dotDotDotToken !== dotDotDotToken
                || node.name !== name
                || node.initializer !== initializer
                ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
                : node;
        }
        ts.updateBindingElement = updateBindingElement;
        // Expression
        function createArrayLiteral(elements, multiLine) {
            var node = createSynthesizedNode(185 /* ArrayLiteralExpression */);
            node.elements = ts.parenthesizeListElements(createNodeArray(elements));
            if (multiLine)
                node.multiLine = true;
            return node;
        }
        ts.createArrayLiteral = createArrayLiteral;
        function updateArrayLiteral(node, elements) {
            return node.elements !== elements
                ? updateNode(createArrayLiteral(elements, node.multiLine), node)
                : node;
        }
        ts.updateArrayLiteral = updateArrayLiteral;
        function createObjectLiteral(properties, multiLine) {
            var node = createSynthesizedNode(186 /* ObjectLiteralExpression */);
            node.properties = createNodeArray(properties);
            if (multiLine)
                node.multiLine = true;
            return node;
        }
        ts.createObjectLiteral = createObjectLiteral;
        function updateObjectLiteral(node, properties) {
            return node.properties !== properties
                ? updateNode(createObjectLiteral(properties, node.multiLine), node)
                : node;
        }
        ts.updateObjectLiteral = updateObjectLiteral;
        function createPropertyAccess(expression, name) {
            var node = createSynthesizedNode(187 /* PropertyAccessExpression */);
            node.expression = ts.parenthesizeForAccess(expression);
            node.name = asName(name); // TODO: GH#18217
            setEmitFlags(node, 131072 /* NoIndentation */);
            return node;
        }
        ts.createPropertyAccess = createPropertyAccess;
        function updatePropertyAccess(node, expression, name) {
            // Because we are updating existed propertyAccess we want to inherit its emitFlags
            // instead of using the default from createPropertyAccess
            return node.expression !== expression
                || node.name !== name
                ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
                : node;
        }
        ts.updatePropertyAccess = updatePropertyAccess;
        function createElementAccess(expression, index) {
            var node = createSynthesizedNode(188 /* ElementAccessExpression */);
            node.expression = ts.parenthesizeForAccess(expression);
            node.argumentExpression = asExpression(index);
            return node;
        }
        ts.createElementAccess = createElementAccess;
        function updateElementAccess(node, expression, argumentExpression) {
            return node.expression !== expression
                || node.argumentExpression !== argumentExpression
                ? updateNode(createElementAccess(expression, argumentExpression), node)
                : node;
        }
        ts.updateElementAccess = updateElementAccess;
        function createCall(expression, typeArguments, argumentsArray) {
            var node = createSynthesizedNode(189 /* CallExpression */);
            node.expression = ts.parenthesizeForAccess(expression);
            node.typeArguments = asNodeArray(typeArguments);
            node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
            return node;
        }
        ts.createCall = createCall;
        function updateCall(node, expression, typeArguments, argumentsArray) {
            return node.expression !== expression
                || node.typeArguments !== typeArguments
                || node.arguments !== argumentsArray
                ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
                : node;
        }
        ts.updateCall = updateCall;
        function createNew(expression, typeArguments, argumentsArray) {
            var node = createSynthesizedNode(190 /* NewExpression */);
            node.expression = ts.parenthesizeForNew(expression);
            node.typeArguments = asNodeArray(typeArguments);
            node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
            return node;
        }
        ts.createNew = createNew;
        function updateNew(node, expression, typeArguments, argumentsArray) {
            return node.expression !== expression
                || node.typeArguments !== typeArguments
                || node.arguments !== argumentsArray
                ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
                : node;
        }
        ts.updateNew = updateNew;
        function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
            var node = createSynthesizedNode(191 /* TaggedTemplateExpression */);
            node.tag = ts.parenthesizeForAccess(tag);
            if (template) {
                node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
                node.template = template;
            }
            else {
                node.typeArguments = undefined;
                node.template = typeArgumentsOrTemplate;
            }
            return node;
        }
        ts.createTaggedTemplate = createTaggedTemplate;
        function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
            return node.tag !== tag
                || (template
                    ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
                    : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
                ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
                : node;
        }
        ts.updateTaggedTemplate = updateTaggedTemplate;
        function createTypeAssertion(type, expression) {
            var node = createSynthesizedNode(192 /* TypeAssertionExpression */);
            node.type = type;
            node.expression = ts.parenthesizePrefixOperand(expression);
            return node;
        }
        ts.createTypeAssertion = createTypeAssertion;
        function updateTypeAssertion(node, type, expression) {
            return node.type !== type
                || node.expression !== expression
                ? updateNode(createTypeAssertion(type, expression), node)
                : node;
        }
        ts.updateTypeAssertion = updateTypeAssertion;
        function createParen(expression) {
            var node = createSynthesizedNode(193 /* ParenthesizedExpression */);
            node.expression = expression;
            return node;
        }
        ts.createParen = createParen;
        function updateParen(node, expression) {
            return node.expression !== expression
                ? updateNode(createParen(expression), node)
                : node;
        }
        ts.updateParen = updateParen;
        function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
            var node = createSynthesizedNode(194 /* FunctionExpression */);
            node.modifiers = asNodeArray(modifiers);
            node.asteriskToken = asteriskToken;
            node.name = asName(name);
            node.typeParameters = asNodeArray(typeParameters);
            node.parameters = createNodeArray(parameters);
            node.type = type;
            node.body = body;
            return node;
        }
        ts.createFunctionExpression = createFunctionExpression;
        function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
            return node.name !== name
                || node.modifiers !== modifiers
                || node.asteriskToken !== asteriskToken
                || node.typeParameters !== typeParameters
                || node.parameters !== parameters
                || node.type !== type
                || node.body !== body
                ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
                : node;
        }
        ts.updateFunctionExpression = updateFunctionExpression;
        function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
            var node = createSynthesizedNode(195 /* ArrowFunction */);
            node.modifiers = asNodeArray(modifiers);
            node.typeParameters = asNodeArray(typeParameters);
            node.parameters = createNodeArray(parameters);
            node.type = type;
            node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36 /* EqualsGreaterThanToken */);
            node.body = ts.parenthesizeConciseBody(body);
            return node;
        }
        ts.createArrowFunction = createArrowFunction;
        function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
            return node.modifiers !== modifiers
                || node.typeParameters !== typeParameters
                || node.parameters !== parameters
                || node.type !== type
                || node.equalsGreaterThanToken !== equalsGreaterThanToken
                || node.body !== body
                ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
                : node;
        }
        ts.updateArrowFunction = updateArrowFunction;
        function createDelete(expression) {
            var node = createSynthesizedNode(196 /* DeleteExpression */);
            node.expression = ts.parenthesizePrefixOperand(expression);
            return node;
        }
        ts.createDelete = createDelete;
        function updateDelete(node, expression) {
            return node.expression !== expression
                ? updateNode(createDelete(expression), node)
                : node;
        }
        ts.updateDelete = updateDelete;
        function createTypeOf(expression) {
            var node = createSynthesizedNode(197 /* TypeOfExpression */);
            node.expression = ts.parenthesizePrefixOperand(expression);
            return node;
        }
        ts.createTypeOf = createTypeOf;
        function updateTypeOf(node, expression) {
            return node.expression !== expression
                ? updateNode(createTypeOf(expression), node)
                : node;
        }
        ts.updateTypeOf = updateTypeOf;
        function createVoid(expression) {
            var node = createSynthesizedNode(198 /* VoidExpression */);
            node.expression = ts.parenthesizePrefixOperand(expression);
            return node;
        }
        ts.createVoid = createVoid;
        function updateVoid(node, expression) {
            return node.expression !== expression
                ? updateNode(createVoid(expression), node)
                : node;
        }
        ts.updateVoid = updateVoid;
        function createAwait(expression) {
            var node = createSynthesizedNode(199 /* AwaitExpression */);
            node.expression = ts.parenthesizePrefixOperand(expression);
            return node;
        }
        ts.createAwait = createAwait;
        function updateAwait(node, expression) {
            return node.expression !== expression
                ? updateNode(createAwait(expression), node)
                : node;
        }
        ts.updateAwait = updateAwait;
        function createPrefix(operator, operand) {
            var node = createSynthesizedNode(200 /* PrefixUnaryExpression */);
            node.operator = operator;
            node.operand = ts.parenthesizePrefixOperand(operand);
            return node;
        }
        ts.createPrefix = createPrefix;
        function updatePrefix(node, operand) {
            return node.operand !== operand
                ? updateNode(createPrefix(node.operator, operand), node)
                : node;
        }
        ts.updatePrefix = updatePrefix;
        function createPostfix(operand, operator) {
            var node = createSynthesizedNode(201 /* PostfixUnaryExpression */);
            node.operand = ts.parenthesizePostfixOperand(operand);
            node.operator = operator;
            return node;
        }
        ts.createPostfix = createPostfix;
        function updatePostfix(node, operand) {
            return node.operand !== operand
                ? updateNode(createPostfix(operand, node.operator), node)
                : node;
        }
        ts.updatePostfix = updatePostfix;
        function createBinary(left, operator, right) {
            var node = createSynthesizedNode(202 /* BinaryExpression */);
            var operatorToken = asToken(operator);
            var operatorKind = operatorToken.kind;
            node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
            node.operatorToken = operatorToken;
            node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
            return node;
        }
        ts.createBinary = createBinary;
        function updateBinary(node, left, right, operator) {
            return node.left !== left
                || node.right !== right
                ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
                : node;
        }
        ts.updateBinary = updateBinary;
        function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
            var node = createSynthesizedNode(203 /* ConditionalExpression */);
            node.condition = ts.parenthesizeForConditionalHead(condition);
            node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */);
            node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
            node.colonToken = whenFalse ? colonToken : createToken(56 /* ColonToken */);
            node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
            return node;
        }
        ts.createConditional = createConditional;
        function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
            return node.condition !== condition
                || node.questionToken !== questionToken
                || node.whenTrue !== whenTrue
                || node.colonToken !== colonToken
                || node.whenFalse !== whenFalse
                ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
                : node;
        }
        ts.updateConditional = updateConditional;
        function createTemplateExpression(head, templateSpans) {
            var node = createSynthesizedNode(204 /* TemplateExpression */);
            node.head = head;
            node.templateSpans = createNodeArray(templateSpans);
            return node;
        }
        ts.createTemplateExpression = createTemplateExpression;
        function updateTemplateExpression(node, head, templateSpans) {
            return node.head !== head
                || node.templateSpans !== templateSpans
                ? updateNode(createTemplateExpression(head, templateSpans), node)
                : node;
        }
        ts.updateTemplateExpression = updateTemplateExpression;
        function createTemplateHead(text) {
            var node = createSynthesizedNode(14 /* TemplateHead */);
            node.text = text;
            return node;
        }
        ts.createTemplateHead = createTemplateHead;
        function createTemplateMiddle(text) {
            var node = createSynthesizedNode(15 /* TemplateMiddle */);
            node.text = text;
            return node;
        }
        ts.createTemplateMiddle = createTemplateMiddle;
        function createTemplateTail(text) {
            var node = createSynthesizedNode(16 /* TemplateTail */);
            node.text = text;
            return node;
        }
        ts.createTemplateTail = createTemplateTail;
        function createNoSubstitutionTemplateLiteral(text) {
            var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */);
            node.text = text;
            return node;
        }
        ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
        function createYield(asteriskTokenOrExpression, expression) {
            var node = createSynthesizedNode(205 /* YieldExpression */);
            node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
            node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
            return node;
        }
        ts.createYield = createYield;
        function updateYield(node, asteriskToken, expression) {
            return node.expression !== expression
                || node.asteriskToken !== asteriskToken
                ? updateNode(createYield(asteriskToken, expression), node)
                : node;
        }
        ts.updateYield = updateYield;
        function createSpread(expression) {
            var node = createSynthesizedNode(206 /* SpreadElement */);
            node.expression = ts.parenthesizeExpressionForList(expression);
            return node;
        }
        ts.createSpread = createSpread;
        function updateSpread(node, expression) {
            return node.expression !== expression
                ? updateNode(createSpread(expression), node)
                : node;
        }
        ts.updateSpread = updateSpread;
        function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
            var node = createSynthesizedNode(207 /* ClassExpression */);
            node.decorators = undefined;
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.typeParameters = asNodeArray(typeParameters);
            node.heritageClauses = asNodeArray(heritageClauses);
            node.members = createNodeArray(members);
            return node;
        }
        ts.createClassExpression = createClassExpression;
        function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
            return node.modifiers !== modifiers
                || node.name !== name
                || node.typeParameters !== typeParameters
                || node.heritageClauses !== heritageClauses
                || node.members !== members
                ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
                : node;
        }
        ts.updateClassExpression = updateClassExpression;
        function createOmittedExpression() {
            return createSynthesizedNode(208 /* OmittedExpression */);
        }
        ts.createOmittedExpression = createOmittedExpression;
        function createExpressionWithTypeArguments(typeArguments, expression) {
            var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */);
            node.expression = ts.parenthesizeForAccess(expression);
            node.typeArguments = asNodeArray(typeArguments);
            return node;
        }
        ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
        function updateExpressionWithTypeArguments(node, typeArguments, expression) {
            return node.typeArguments !== typeArguments
                || node.expression !== expression
                ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
                : node;
        }
        ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
        function createAsExpression(expression, type) {
            var node = createSynthesizedNode(210 /* AsExpression */);
            node.expression = expression;
            node.type = type;
            return node;
        }
        ts.createAsExpression = createAsExpression;
        function updateAsExpression(node, expression, type) {
            return node.expression !== expression
                || node.type !== type
                ? updateNode(createAsExpression(expression, type), node)
                : node;
        }
        ts.updateAsExpression = updateAsExpression;
        function createNonNullExpression(expression) {
            var node = createSynthesizedNode(211 /* NonNullExpression */);
            node.expression = ts.parenthesizeForAccess(expression);
            return node;
        }
        ts.createNonNullExpression = createNonNullExpression;
        function updateNonNullExpression(node, expression) {
            return node.expression !== expression
                ? updateNode(createNonNullExpression(expression), node)
                : node;
        }
        ts.updateNonNullExpression = updateNonNullExpression;
        function createMetaProperty(keywordToken, name) {
            var node = createSynthesizedNode(212 /* MetaProperty */);
            node.keywordToken = keywordToken;
            node.name = name;
            return node;
        }
        ts.createMetaProperty = createMetaProperty;
        function updateMetaProperty(node, name) {
            return node.name !== name
                ? updateNode(createMetaProperty(node.keywordToken, name), node)
                : node;
        }
        ts.updateMetaProperty = updateMetaProperty;
        // Misc
        function createTemplateSpan(expression, literal) {
            var node = createSynthesizedNode(214 /* TemplateSpan */);
            node.expression = expression;
            node.literal = literal;
            return node;
        }
        ts.createTemplateSpan = createTemplateSpan;
        function updateTemplateSpan(node, expression, literal) {
            return node.expression !== expression
                || node.literal !== literal
                ? updateNode(createTemplateSpan(expression, literal), node)
                : node;
        }
        ts.updateTemplateSpan = updateTemplateSpan;
        function createSemicolonClassElement() {
            return createSynthesizedNode(215 /* SemicolonClassElement */);
        }
        ts.createSemicolonClassElement = createSemicolonClassElement;
        // Element
        function createBlock(statements, multiLine) {
            var block = createSynthesizedNode(216 /* Block */);
            block.statements = createNodeArray(statements);
            if (multiLine)
                block.multiLine = multiLine;
            return block;
        }
        ts.createBlock = createBlock;
        function updateBlock(node, statements) {
            return node.statements !== statements
                ? updateNode(createBlock(statements, node.multiLine), node)
                : node;
        }
        ts.updateBlock = updateBlock;
        function createVariableStatement(modifiers, declarationList) {
            var node = createSynthesizedNode(217 /* VariableStatement */);
            node.decorators = undefined;
            node.modifiers = asNodeArray(modifiers);
            node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
            return node;
        }
        ts.createVariableStatement = createVariableStatement;
        function updateVariableStatement(node, modifiers, declarationList) {
            return node.modifiers !== modifiers
                || node.declarationList !== declarationList
                ? updateNode(createVariableStatement(modifiers, declarationList), node)
                : node;
        }
        ts.updateVariableStatement = updateVariableStatement;
        function createEmptyStatement() {
            return createSynthesizedNode(218 /* EmptyStatement */);
        }
        ts.createEmptyStatement = createEmptyStatement;
        function createExpressionStatement(expression) {
            var node = createSynthesizedNode(219 /* ExpressionStatement */);
            node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
            return node;
        }
        ts.createExpressionStatement = createExpressionStatement;
        function updateExpressionStatement(node, expression) {
            return node.expression !== expression
                ? updateNode(createExpressionStatement(expression), node)
                : node;
        }
        ts.updateExpressionStatement = updateExpressionStatement;
        /** @deprecated Use `createExpressionStatement` instead.  */
        ts.createStatement = createExpressionStatement;
        /** @deprecated Use `updateExpressionStatement` instead.  */
        ts.updateStatement = updateExpressionStatement;
        function createIf(expression, thenStatement, elseStatement) {
            var node = createSynthesizedNode(220 /* IfStatement */);
            node.expression = expression;
            node.thenStatement = thenStatement;
            node.elseStatement = elseStatement;
            return node;
        }
        ts.createIf = createIf;
        function updateIf(node, expression, thenStatement, elseStatement) {
            return node.expression !== expression
                || node.thenStatement !== thenStatement
                || node.elseStatement !== elseStatement
                ? updateNode(createIf(expression, thenStatement, elseStatement), node)
                : node;
        }
        ts.updateIf = updateIf;
        function createDo(statement, expression) {
            var node = createSynthesizedNode(221 /* DoStatement */);
            node.statement = statement;
            node.expression = expression;
            return node;
        }
        ts.createDo = createDo;
        function updateDo(node, statement, expression) {
            return node.statement !== statement
                || node.expression !== expression
                ? updateNode(createDo(statement, expression), node)
                : node;
        }
        ts.updateDo = updateDo;
        function createWhile(expression, statement) {
            var node = createSynthesizedNode(222 /* WhileStatement */);
            node.expression = expression;
            node.statement = statement;
            return node;
        }
        ts.createWhile = createWhile;
        function updateWhile(node, expression, statement) {
            return node.expression !== expression
                || node.statement !== statement
                ? updateNode(createWhile(expression, statement), node)
                : node;
        }
        ts.updateWhile = updateWhile;
        function createFor(initializer, condition, incrementor, statement) {
            var node = createSynthesizedNode(223 /* ForStatement */);
            node.initializer = initializer;
            node.condition = condition;
            node.incrementor = incrementor;
            node.statement = statement;
            return node;
        }
        ts.createFor = createFor;
        function updateFor(node, initializer, condition, incrementor, statement) {
            return node.initializer !== initializer
                || node.condition !== condition
                || node.incrementor !== incrementor
                || node.statement !== statement
                ? updateNode(createFor(initializer, condition, incrementor, statement), node)
                : node;
        }
        ts.updateFor = updateFor;
        function createForIn(initializer, expression, statement) {
            var node = createSynthesizedNode(224 /* ForInStatement */);
            node.initializer = initializer;
            node.expression = expression;
            node.statement = statement;
            return node;
        }
        ts.createForIn = createForIn;
        function updateForIn(node, initializer, expression, statement) {
            return node.initializer !== initializer
                || node.expression !== expression
                || node.statement !== statement
                ? updateNode(createForIn(initializer, expression, statement), node)
                : node;
        }
        ts.updateForIn = updateForIn;
        function createForOf(awaitModifier, initializer, expression, statement) {
            var node = createSynthesizedNode(225 /* ForOfStatement */);
            node.awaitModifier = awaitModifier;
            node.initializer = initializer;
            node.expression = expression;
            node.statement = statement;
            return node;
        }
        ts.createForOf = createForOf;
        function updateForOf(node, awaitModifier, initializer, expression, statement) {
            return node.awaitModifier !== awaitModifier
                || node.initializer !== initializer
                || node.expression !== expression
                || node.statement !== statement
                ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
                : node;
        }
        ts.updateForOf = updateForOf;
        function createContinue(label) {
            var node = createSynthesizedNode(226 /* ContinueStatement */);
            node.label = asName(label);
            return node;
        }
        ts.createContinue = createContinue;
        function updateContinue(node, label) {
            return node.label !== label
                ? updateNode(createContinue(label), node)
                : node;
        }
        ts.updateContinue = updateContinue;
        function createBreak(label) {
            var node = createSynthesizedNode(227 /* BreakStatement */);
            node.label = asName(label);
            return node;
        }
        ts.createBreak = createBreak;
        function updateBreak(node, label) {
            return node.label !== label
                ? updateNode(createBreak(label), node)
                : node;
        }
        ts.updateBreak = updateBreak;
        function createReturn(expression) {
            var node = createSynthesizedNode(228 /* ReturnStatement */);
            node.expression = expression;
            return node;
        }
        ts.createReturn = createReturn;
        function updateReturn(node, expression) {
            return node.expression !== expression
                ? updateNode(createReturn(expression), node)
                : node;
        }
        ts.updateReturn = updateReturn;
        function createWith(expression, statement) {
            var node = createSynthesizedNode(229 /* WithStatement */);
            node.expression = expression;
            node.statement = statement;
            return node;
        }
        ts.createWith = createWith;
        function updateWith(node, expression, statement) {
            return node.expression !== expression
                || node.statement !== statement
                ? updateNode(createWith(expression, statement), node)
                : node;
        }
        ts.updateWith = updateWith;
        function createSwitch(expression, caseBlock) {
            var node = createSynthesizedNode(230 /* SwitchStatement */);
            node.expression = ts.parenthesizeExpressionForList(expression);
            node.caseBlock = caseBlock;
            return node;
        }
        ts.createSwitch = createSwitch;
        function updateSwitch(node, expression, caseBlock) {
            return node.expression !== expression
                || node.caseBlock !== caseBlock
                ? updateNode(createSwitch(expression, caseBlock), node)
                : node;
        }
        ts.updateSwitch = updateSwitch;
        function createLabel(label, statement) {
            var node = createSynthesizedNode(231 /* LabeledStatement */);
            node.label = asName(label);
            node.statement = statement;
            return node;
        }
        ts.createLabel = createLabel;
        function updateLabel(node, label, statement) {
            return node.label !== label
                || node.statement !== statement
                ? updateNode(createLabel(label, statement), node)
                : node;
        }
        ts.updateLabel = updateLabel;
        function createThrow(expression) {
            var node = createSynthesizedNode(232 /* ThrowStatement */);
            node.expression = expression;
            return node;
        }
        ts.createThrow = createThrow;
        function updateThrow(node, expression) {
            return node.expression !== expression
                ? updateNode(createThrow(expression), node)
                : node;
        }
        ts.updateThrow = updateThrow;
        function createTry(tryBlock, catchClause, finallyBlock) {
            var node = createSynthesizedNode(233 /* TryStatement */);
            node.tryBlock = tryBlock;
            node.catchClause = catchClause;
            node.finallyBlock = finallyBlock;
            return node;
        }
        ts.createTry = createTry;
        function updateTry(node, tryBlock, catchClause, finallyBlock) {
            return node.tryBlock !== tryBlock
                || node.catchClause !== catchClause
                || node.finallyBlock !== finallyBlock
                ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
                : node;
        }
        ts.updateTry = updateTry;
        function createDebuggerStatement() {
            return createSynthesizedNode(234 /* DebuggerStatement */);
        }
        ts.createDebuggerStatement = createDebuggerStatement;
        function createVariableDeclaration(name, type, initializer) {
            var node = createSynthesizedNode(235 /* VariableDeclaration */);
            node.name = asName(name);
            node.type = type;
            node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
            return node;
        }
        ts.createVariableDeclaration = createVariableDeclaration;
        function updateVariableDeclaration(node, name, type, initializer) {
            return node.name !== name
                || node.type !== type
                || node.initializer !== initializer
                ? updateNode(createVariableDeclaration(name, type, initializer), node)
                : node;
        }
        ts.updateVariableDeclaration = updateVariableDeclaration;
        function createVariableDeclarationList(declarations, flags) {
            if (flags === void 0) {
                flags = 0 /* None */;
            }
            var node = createSynthesizedNode(236 /* VariableDeclarationList */);
            node.flags |= flags & 3 /* BlockScoped */;
            node.declarations = createNodeArray(declarations);
            return node;
        }
        ts.createVariableDeclarationList = createVariableDeclarationList;
        function updateVariableDeclarationList(node, declarations) {
            return node.declarations !== declarations
                ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
                : node;
        }
        ts.updateVariableDeclarationList = updateVariableDeclarationList;
        function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
            var node = createSynthesizedNode(237 /* FunctionDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.asteriskToken = asteriskToken;
            node.name = asName(name);
            node.typeParameters = asNodeArray(typeParameters);
            node.parameters = createNodeArray(parameters);
            node.type = type;
            node.body = body;
            return node;
        }
        ts.createFunctionDeclaration = createFunctionDeclaration;
        function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.asteriskToken !== asteriskToken
                || node.name !== name
                || node.typeParameters !== typeParameters
                || node.parameters !== parameters
                || node.type !== type
                || node.body !== body
                ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
                : node;
        }
        ts.updateFunctionDeclaration = updateFunctionDeclaration;
        function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
            var node = createSynthesizedNode(238 /* ClassDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.typeParameters = asNodeArray(typeParameters);
            node.heritageClauses = asNodeArray(heritageClauses);
            node.members = createNodeArray(members);
            return node;
        }
        ts.createClassDeclaration = createClassDeclaration;
        function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.typeParameters !== typeParameters
                || node.heritageClauses !== heritageClauses
                || node.members !== members
                ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
                : node;
        }
        ts.updateClassDeclaration = updateClassDeclaration;
        function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
            var node = createSynthesizedNode(239 /* InterfaceDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.typeParameters = asNodeArray(typeParameters);
            node.heritageClauses = asNodeArray(heritageClauses);
            node.members = createNodeArray(members);
            return node;
        }
        ts.createInterfaceDeclaration = createInterfaceDeclaration;
        function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.typeParameters !== typeParameters
                || node.heritageClauses !== heritageClauses
                || node.members !== members
                ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
                : node;
        }
        ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
        function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
            var node = createSynthesizedNode(240 /* TypeAliasDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.typeParameters = asNodeArray(typeParameters);
            node.type = type;
            return node;
        }
        ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
        function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.typeParameters !== typeParameters
                || node.type !== type
                ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
                : node;
        }
        ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
        function createEnumDeclaration(decorators, modifiers, name, members) {
            var node = createSynthesizedNode(241 /* EnumDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.members = createNodeArray(members);
            return node;
        }
        ts.createEnumDeclaration = createEnumDeclaration;
        function updateEnumDeclaration(node, decorators, modifiers, name, members) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.members !== members
                ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
                : node;
        }
        ts.updateEnumDeclaration = updateEnumDeclaration;
        function createModuleDeclaration(decorators, modifiers, name, body, flags) {
            if (flags === void 0) {
                flags = 0 /* None */;
            }
            var node = createSynthesizedNode(242 /* ModuleDeclaration */);
            node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = name;
            node.body = body;
            return node;
        }
        ts.createModuleDeclaration = createModuleDeclaration;
        function updateModuleDeclaration(node, decorators, modifiers, name, body) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.body !== body
                ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
                : node;
        }
        ts.updateModuleDeclaration = updateModuleDeclaration;
        function createModuleBlock(statements) {
            var node = createSynthesizedNode(243 /* ModuleBlock */);
            node.statements = createNodeArray(statements);
            return node;
        }
        ts.createModuleBlock = createModuleBlock;
        function updateModuleBlock(node, statements) {
            return node.statements !== statements
                ? updateNode(createModuleBlock(statements), node)
                : node;
        }
        ts.updateModuleBlock = updateModuleBlock;
        function createCaseBlock(clauses) {
            var node = createSynthesizedNode(244 /* CaseBlock */);
            node.clauses = createNodeArray(clauses);
            return node;
        }
        ts.createCaseBlock = createCaseBlock;
        function updateCaseBlock(node, clauses) {
            return node.clauses !== clauses
                ? updateNode(createCaseBlock(clauses), node)
                : node;
        }
        ts.updateCaseBlock = updateCaseBlock;
        function createNamespaceExportDeclaration(name) {
            var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */);
            node.name = asName(name);
            return node;
        }
        ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
        function updateNamespaceExportDeclaration(node, name) {
            return node.name !== name
                ? updateNode(createNamespaceExportDeclaration(name), node)
                : node;
        }
        ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
        function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
            var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.name = asName(name);
            node.moduleReference = moduleReference;
            return node;
        }
        ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
        function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.name !== name
                || node.moduleReference !== moduleReference
                ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
                : node;
        }
        ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
        function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
            var node = createSynthesizedNode(247 /* ImportDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.importClause = importClause;
            node.moduleSpecifier = moduleSpecifier;
            return node;
        }
        ts.createImportDeclaration = createImportDeclaration;
        function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.importClause !== importClause
                || node.moduleSpecifier !== moduleSpecifier
                ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
                : node;
        }
        ts.updateImportDeclaration = updateImportDeclaration;
        function createImportClause(name, namedBindings) {
            var node = createSynthesizedNode(248 /* ImportClause */);
            node.name = name;
            node.namedBindings = namedBindings;
            return node;
        }
        ts.createImportClause = createImportClause;
        function updateImportClause(node, name, namedBindings) {
            return node.name !== name
                || node.namedBindings !== namedBindings
                ? updateNode(createImportClause(name, namedBindings), node)
                : node;
        }
        ts.updateImportClause = updateImportClause;
        function createNamespaceImport(name) {
            var node = createSynthesizedNode(249 /* NamespaceImport */);
            node.name = name;
            return node;
        }
        ts.createNamespaceImport = createNamespaceImport;
        function updateNamespaceImport(node, name) {
            return node.name !== name
                ? updateNode(createNamespaceImport(name), node)
                : node;
        }
        ts.updateNamespaceImport = updateNamespaceImport;
        function createNamedImports(elements) {
            var node = createSynthesizedNode(250 /* NamedImports */);
            node.elements = createNodeArray(elements);
            return node;
        }
        ts.createNamedImports = createNamedImports;
        function updateNamedImports(node, elements) {
            return node.elements !== elements
                ? updateNode(createNamedImports(elements), node)
                : node;
        }
        ts.updateNamedImports = updateNamedImports;
        function createImportSpecifier(propertyName, name) {
            var node = createSynthesizedNode(251 /* ImportSpecifier */);
            node.propertyName = propertyName;
            node.name = name;
            return node;
        }
        ts.createImportSpecifier = createImportSpecifier;
        function updateImportSpecifier(node, propertyName, name) {
            return node.propertyName !== propertyName
                || node.name !== name
                ? updateNode(createImportSpecifier(propertyName, name), node)
                : node;
        }
        ts.updateImportSpecifier = updateImportSpecifier;
        function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
            var node = createSynthesizedNode(252 /* ExportAssignment */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.isExportEquals = isExportEquals;
            node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
            return node;
        }
        ts.createExportAssignment = createExportAssignment;
        function updateExportAssignment(node, decorators, modifiers, expression) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.expression !== expression
                ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
                : node;
        }
        ts.updateExportAssignment = updateExportAssignment;
        function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) {
            var node = createSynthesizedNode(253 /* ExportDeclaration */);
            node.decorators = asNodeArray(decorators);
            node.modifiers = asNodeArray(modifiers);
            node.exportClause = exportClause;
            node.moduleSpecifier = moduleSpecifier;
            return node;
        }
        ts.createExportDeclaration = createExportDeclaration;
        function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) {
            return node.decorators !== decorators
                || node.modifiers !== modifiers
                || node.exportClause !== exportClause
                || node.moduleSpecifier !== moduleSpecifier
                ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node)
                : node;
        }
        ts.updateExportDeclaration = updateExportDeclaration;
        function createNamedExports(elements) {
            var node = createSynthesizedNode(254 /* NamedExports */);
            node.elements = createNodeArray(elements);
            return node;
        }
        ts.createNamedExports = createNamedExports;
        function updateNamedExports(node, elements) {
            return node.elements !== elements
                ? updateNode(createNamedExports(elements), node)
                : node;
        }
        ts.updateNamedExports = updateNamedExports;
        function createExportSpecifier(propertyName, name) {
            var node = createSynthesizedNode(255 /* ExportSpecifier */);
            node.propertyName = asName(propertyName);
            node.name = asName(name);
            return node;
        }
        ts.createExportSpecifier = createExportSpecifier;
        function updateExportSpecifier(node, propertyName, name) {
            return node.propertyName !== propertyName
                || node.name !== name
                ? updateNode(createExportSpecifier(propertyName, name), node)
                : node;
        }
        ts.updateExportSpecifier = updateExportSpecifier;
        // Module references
        function createExternalModuleReference(expression) {
            var node = createSynthesizedNode(257 /* ExternalModuleReference */);
            node.expression = expression;
            return node;
        }
        ts.createExternalModuleReference = createExternalModuleReference;
        function updateExternalModuleReference(node, expression) {
            return node.expression !== expression
                ? updateNode(createExternalModuleReference(expression), node)
                : node;
        }
        ts.updateExternalModuleReference = updateExternalModuleReference;
        // JSX
        function createJsxElement(openingElement, children, closingElement) {
            var node = createSynthesizedNode(258 /* JsxElement */);
            node.openingElement = openingElement;
            node.children = createNodeArray(children);
            node.closingElement = closingElement;
            return node;
        }
        ts.createJsxElement = createJsxElement;
        function updateJsxElement(node, openingElement, children, closingElement) {
            return node.openingElement !== openingElement
                || node.children !== children
                || node.closingElement !== closingElement
                ? updateNode(createJsxElement(openingElement, children, closingElement), node)
                : node;
        }
        ts.updateJsxElement = updateJsxElement;
        function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
            var node = createSynthesizedNode(259 /* JsxSelfClosingElement */);
            node.tagName = tagName;
            node.typeArguments = asNodeArray(typeArguments);
            node.attributes = attributes;
            return node;
        }
        ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
        function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
            return node.tagName !== tagName
                || node.typeArguments !== typeArguments
                || node.attributes !== attributes
                ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
                : node;
        }
        ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
        function createJsxOpeningElement(tagName, typeArguments, attributes) {
            var node = createSynthesizedNode(260 /* JsxOpeningElement */);
            node.tagName = tagName;
            node.typeArguments = asNodeArray(typeArguments);
            node.attributes = attributes;
            return node;
        }
        ts.createJsxOpeningElement = createJsxOpeningElement;
        function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
            return node.tagName !== tagName
                || node.typeArguments !== typeArguments
                || node.attributes !== attributes
                ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
                : node;
        }
        ts.updateJsxOpeningElement = updateJsxOpeningElement;
        function createJsxClosingElement(tagName) {
            var node = createSynthesizedNode(261 /* JsxClosingElement */);
            node.tagName = tagName;
            return node;
        }
        ts.createJsxClosingElement = createJsxClosingElement;
        function updateJsxClosingElement(node, tagName) {
            return node.tagName !== tagName
                ? updateNode(createJsxClosingElement(tagName), node)
                : node;
        }
        ts.updateJsxClosingElement = updateJsxClosingElement;
        function createJsxFragment(openingFragment, children, closingFragment) {
            var node = createSynthesizedNode(262 /* JsxFragment */);
            node.openingFragment = openingFragment;
            node.children = createNodeArray(children);
            node.closingFragment = closingFragment;
            return node;
        }
        ts.createJsxFragment = createJsxFragment;
        function updateJsxFragment(node, openingFragment, children, closingFragment) {
            return node.openingFragment !== openingFragment
                || node.children !== children
                || node.closingFragment !== closingFragment
                ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
                : node;
        }
        ts.updateJsxFragment = updateJsxFragment;
        function createJsxAttribute(name, initializer) {
            var node = createSynthesizedNode(265 /* JsxAttribute */);
            node.name = name;
            node.initializer = initializer;
            return node;
        }
        ts.createJsxAttribute = createJsxAttribute;
        function updateJsxAttribute(node, name, initializer) {
            return node.name !== name
                || node.initializer !== initializer
                ? updateNode(createJsxAttribute(name, initializer), node)
                : node;
        }
        ts.updateJsxAttribute = updateJsxAttribute;
        function createJsxAttributes(properties) {
            var node = createSynthesizedNode(266 /* JsxAttributes */);
            node.properties = createNodeArray(properties);
            return node;
        }
        ts.createJsxAttributes = createJsxAttributes;
        function updateJsxAttributes(node, properties) {
            return node.properties !== properties
                ? updateNode(createJsxAttributes(properties), node)
                : node;
        }
        ts.updateJsxAttributes = updateJsxAttributes;
        function createJsxSpreadAttribute(expression) {
            var node = createSynthesizedNode(267 /* JsxSpreadAttribute */);
            node.expression = expression;
            return node;
        }
        ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
        function updateJsxSpreadAttribute(node, expression) {
            return node.expression !== expression
                ? updateNode(createJsxSpreadAttribute(expression), node)
                : node;
        }
        ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
        function createJsxExpression(dotDotDotToken, expression) {
            var node = createSynthesizedNode(268 /* JsxExpression */);
            node.dotDotDotToken = dotDotDotToken;
            node.expression = expression;
            return node;
        }
        ts.createJsxExpression = createJsxExpression;
        function updateJsxExpression(node, expression) {
            return node.expression !== expression
                ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
                : node;
        }
        ts.updateJsxExpression = updateJsxExpression;
        // Clauses
        function createCaseClause(expression, statements) {
            var node = createSynthesizedNode(269 /* CaseClause */);
            node.expression = ts.parenthesizeExpressionForList(expression);
            node.statements = createNodeArray(statements);
            return node;
        }
        ts.createCaseClause = createCaseClause;
        function updateCaseClause(node, expression, statements) {
            return node.expression !== expression
                || node.statements !== statements
                ? updateNode(createCaseClause(expression, statements), node)
                : node;
        }
        ts.updateCaseClause = updateCaseClause;
        function createDefaultClause(statements) {
            var node = createSynthesizedNode(270 /* DefaultClause */);
            node.statements = createNodeArray(statements);
            return node;
        }
        ts.createDefaultClause = createDefaultClause;
        function updateDefaultClause(node, statements) {
            return node.statements !== statements
                ? updateNode(createDefaultClause(statements), node)
                : node;
        }
        ts.updateDefaultClause = updateDefaultClause;
        function createHeritageClause(token, types) {
            var node = createSynthesizedNode(271 /* HeritageClause */);
            node.token = token;
            node.types = createNodeArray(types);
            return node;
        }
        ts.createHeritageClause = createHeritageClause;
        function updateHeritageClause(node, types) {
            return node.types !== types
                ? updateNode(createHeritageClause(node.token, types), node)
                : node;
        }
        ts.updateHeritageClause = updateHeritageClause;
        function createCatchClause(variableDeclaration, block) {
            var node = createSynthesizedNode(272 /* CatchClause */);
            node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
            node.block = block;
            return node;
        }
        ts.createCatchClause = createCatchClause;
        function updateCatchClause(node, variableDeclaration, block) {
            return node.variableDeclaration !== variableDeclaration
                || node.block !== block
                ? updateNode(createCatchClause(variableDeclaration, block), node)
                : node;
        }
        ts.updateCatchClause = updateCatchClause;
        // Property assignments
        function createPropertyAssignment(name, initializer) {
            var node = createSynthesizedNode(273 /* PropertyAssignment */);
            node.name = asName(name);
            node.questionToken = undefined;
            node.initializer = ts.parenthesizeExpressionForList(initializer);
            return node;
        }
        ts.createPropertyAssignment = createPropertyAssignment;
        function updatePropertyAssignment(node, name, initializer) {
            return node.name !== name
                || node.initializer !== initializer
                ? updateNode(createPropertyAssignment(name, initializer), node)
                : node;
        }
        ts.updatePropertyAssignment = updatePropertyAssignment;
        function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
            var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */);
            node.name = asName(name);
            node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
            return node;
        }
        ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
        function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
            return node.name !== name
                || node.objectAssignmentInitializer !== objectAssignmentInitializer
                ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
                : node;
        }
        ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
        function createSpreadAssignment(expression) {
            var node = createSynthesizedNode(275 /* SpreadAssignment */);
            node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217
            return node;
        }
        ts.createSpreadAssignment = createSpreadAssignment;
        function updateSpreadAssignment(node, expression) {
            return node.expression !== expression
                ? updateNode(createSpreadAssignment(expression), node)
                : node;
        }
        ts.updateSpreadAssignment = updateSpreadAssignment;
        // Enum
        function createEnumMember(name, initializer) {
            var node = createSynthesizedNode(276 /* EnumMember */);
            node.name = asName(name);
            node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
            return node;
        }
        ts.createEnumMember = createEnumMember;
        function updateEnumMember(node, name, initializer) {
            return node.name !== name
                || node.initializer !== initializer
                ? updateNode(createEnumMember(name, initializer), node)
                : node;
        }
        ts.updateEnumMember = updateEnumMember;
        // Top-level nodes
        function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
            if (node.statements !== statements ||
                (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
                (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
                (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
                (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
                (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
                var updated = createSynthesizedNode(277 /* SourceFile */);
                updated.flags |= node.flags;
                updated.statements = createNodeArray(statements);
                updated.endOfFileToken = node.endOfFileToken;
                updated.fileName = node.fileName;
                updated.path = node.path;
                updated.text = node.text;
                updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
                updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
                updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
                updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
                updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
                if (node.amdDependencies !== undefined)
                    updated.amdDependencies = node.amdDependencies;
                if (node.moduleName !== undefined)
                    updated.moduleName = node.moduleName;
                if (node.languageVariant !== undefined)
                    updated.languageVariant = node.languageVariant;
                if (node.renamedDependencies !== undefined)
                    updated.renamedDependencies = node.renamedDependencies;
                if (node.languageVersion !== undefined)
                    updated.languageVersion = node.languageVersion;
                if (node.scriptKind !== undefined)
                    updated.scriptKind = node.scriptKind;
                if (node.externalModuleIndicator !== undefined)
                    updated.externalModuleIndicator = node.externalModuleIndicator;
                if (node.commonJsModuleIndicator !== undefined)
                    updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
                if (node.identifiers !== undefined)
                    updated.identifiers = node.identifiers;
                if (node.nodeCount !== undefined)
                    updated.nodeCount = node.nodeCount;
                if (node.identifierCount !== undefined)
                    updated.identifierCount = node.identifierCount;
                if (node.symbolCount !== undefined)
                    updated.symbolCount = node.symbolCount;
                if (node.parseDiagnostics !== undefined)
                    updated.parseDiagnostics = node.parseDiagnostics;
                if (node.bindDiagnostics !== undefined)
                    updated.bindDiagnostics = node.bindDiagnostics;
                if (node.bindSuggestionDiagnostics !== undefined)
                    updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
                if (node.lineMap !== undefined)
                    updated.lineMap = node.lineMap;
                if (node.classifiableNames !== undefined)
                    updated.classifiableNames = node.classifiableNames;
                if (node.resolvedModules !== undefined)
                    updated.resolvedModules = node.resolvedModules;
                if (node.resolvedTypeReferenceDirectiveNames !== undefined)
                    updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
                if (node.imports !== undefined)
                    updated.imports = node.imports;
                if (node.moduleAugmentations !== undefined)
                    updated.moduleAugmentations = node.moduleAugmentations;
                if (node.pragmas !== undefined)
                    updated.pragmas = node.pragmas;
                if (node.localJsxFactory !== undefined)
                    updated.localJsxFactory = node.localJsxFactory;
                if (node.localJsxNamespace !== undefined)
                    updated.localJsxNamespace = node.localJsxNamespace;
                return updateNode(updated, node);
            }
            return node;
        }
        ts.updateSourceFileNode = updateSourceFileNode;
        /**
         * Creates a shallow, memberwise clone of a node for mutation.
         */
        function getMutableClone(node) {
            var clone = getSynthesizedClone(node);
            clone.pos = node.pos;
            clone.end = node.end;
            clone.parent = node.parent;
            return clone;
        }
        ts.getMutableClone = getMutableClone;
        // Transformation nodes
        /**
         * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
         * order to preserve comments.
         *
         * @param original The original statement.
         */
        function createNotEmittedStatement(original) {
            var node = createSynthesizedNode(305 /* NotEmittedStatement */);
            node.original = original;
            setTextRange(node, original);
            return node;
        }
        ts.createNotEmittedStatement = createNotEmittedStatement;
        /**
         * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
         * order to properly emit exports.
         */
        /* @internal */
        function createEndOfDeclarationMarker(original) {
            var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */);
            node.emitNode = {};
            node.original = original;
            return node;
        }
        ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
        /**
         * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
         * order to properly emit exports.
         */
        /* @internal */
        function createMergeDeclarationMarker(original) {
            var node = createSynthesizedNode(308 /* MergeDeclarationMarker */);
            node.emitNode = {};
            node.original = original;
            return node;
        }
        ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
        /**
         * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
         * order to preserve comments or sourcemap positions.
         *
         * @param expression The inner expression to emit.
         * @param original The original outer expression.
         * @param location The location for the expression. Defaults to the positions from "original" if provided.
         */
        function createPartiallyEmittedExpression(expression, original) {
            var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */);
            node.expression = expression;
            node.original = original;
            setTextRange(node, original);
            return node;
        }
        ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
        function updatePartiallyEmittedExpression(node, expression) {
            if (node.expression !== expression) {
                return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
            }
            return node;
        }
        ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
        function flattenCommaElements(node) {
            if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
                if (node.kind === 307 /* CommaListExpression */) {
                    return node.elements;
                }
                if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) {
                    return [node.left, node.right];
                }
            }
            return node;
        }
        function createCommaList(elements) {
            var node = createSynthesizedNode(307 /* CommaListExpression */);
            node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
            return node;
        }
        ts.createCommaList = createCommaList;
        function updateCommaList(node, elements) {
            return node.elements !== elements
                ? updateNode(createCommaList(elements), node)
                : node;
        }
        ts.updateCommaList = updateCommaList;
        function createBundle(sourceFiles, prepends) {
            if (prepends === void 0) {
                prepends = ts.emptyArray;
            }
            var node = ts.createNode(278 /* Bundle */);
            node.prepends = prepends;
            node.sourceFiles = sourceFiles;
            return node;
        }
        ts.createBundle = createBundle;
        function createUnparsedSourceFile(text, mapPath, map) {
            var node = ts.createNode(279 /* UnparsedSource */);
            node.text = text;
            node.sourceMapPath = mapPath;
            node.sourceMapText = map;
            return node;
        }
        ts.createUnparsedSourceFile = createUnparsedSourceFile;
        function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) {
            var node = ts.createNode(280 /* InputFiles */);
            node.javascriptText = javascript;
            node.javascriptMapPath = javascriptMapPath;
            node.javascriptMapText = javascriptMapText;
            node.declarationText = declaration;
            node.declarationMapPath = declarationMapPath;
            node.declarationMapText = declarationMapText;
            return node;
        }
        ts.createInputFiles = createInputFiles;
        function updateBundle(node, sourceFiles, prepends) {
            if (prepends === void 0) {
                prepends = ts.emptyArray;
            }
            if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
                return createBundle(sourceFiles, prepends);
            }
            return node;
        }
        ts.updateBundle = updateBundle;
        function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
            return createCall(createFunctionExpression(
            /*modifiers*/ undefined, 
            /*asteriskToken*/ undefined, 
            /*name*/ undefined, 
            /*typeParameters*/ undefined, 
            /*parameters*/ param ? [param] : [], 
            /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
            /*typeArguments*/ undefined, 
            /*argumentsArray*/ paramValue ? [paramValue] : []);
        }
        ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
        function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
            return createCall(createArrowFunction(
            /*modifiers*/ undefined, 
            /*typeParameters*/ undefined, 
            /*parameters*/ param ? [param] : [], 
            /*type*/ undefined, 
            /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
            /*typeArguments*/ undefined, 
            /*argumentsArray*/ paramValue ? [paramValue] : []);
        }
        ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
        function createComma(left, right) {
            return createBinary(left, 26 /* CommaToken */, right);
        }
        ts.createComma = createComma;
        function createLessThan(left, right) {
            return createBinary(left, 27 /* LessThanToken */, right);
        }
        ts.createLessThan = createLessThan;
        function createAssignment(left, right) {
            return createBinary(left, 58 /* EqualsToken */, right);
        }
        ts.createAssignment = createAssignment;
        function createStrictEquality(left, right) {
            return createBinary(left, 34 /* EqualsEqualsEqualsToken */, right);
        }
        ts.createStrictEquality = createStrictEquality;
        function createStrictInequality(left, right) {
            return createBinary(left, 35 /* ExclamationEqualsEqualsToken */, right);
        }
        ts.createStrictInequality = createStrictInequality;
        function createAdd(left, right) {
            return createBinary(left, 37 /* PlusToken */, right);
        }
        ts.createAdd = createAdd;
        function createSubtract(left, right) {
            return createBinary(left, 38 /* MinusToken */, right);
        }
        ts.createSubtract = createSubtract;
        function createPostfixIncrement(operand) {
            return createPostfix(operand, 43 /* PlusPlusToken */);
        }
        ts.createPostfixIncrement = createPostfixIncrement;
        function createLogicalAnd(left, right) {
            return createBinary(left, 53 /* AmpersandAmpersandToken */, right);
        }
        ts.createLogicalAnd = createLogicalAnd;
        function createLogicalOr(left, right) {
            return createBinary(left, 54 /* BarBarToken */, right);
        }
        ts.createLogicalOr = createLogicalOr;
        function createLogicalNot(operand) {
            return createPrefix(51 /* ExclamationToken */, operand);
        }
        ts.createLogicalNot = createLogicalNot;
        function createVoidZero() {
            return createVoid(createLiteral(0));
        }
        ts.createVoidZero = createVoidZero;
        function createExportDefault(expression) {
            return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
        }
        ts.createExportDefault = createExportDefault;
        function createExternalModuleExport(exportName) {
            return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
        }
        ts.createExternalModuleExport = createExternalModuleExport;
        // Utilities
        function asName(name) {
            return ts.isString(name) ? createIdentifier(name) : name;
        }
        function asExpression(value) {
            return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value;
        }
        function asNodeArray(array) {
            return array ? createNodeArray(array) : undefined;
        }
        function asToken(value) {
            return typeof value === "number" ? createToken(value) : value;
        }
        /**
         * Clears any EmitNode entries from parse-tree nodes.
         * @param sourceFile A source file.
         */
        function disposeEmitNodes(sourceFile) {
            // During transformation we may need to annotate a parse tree node with transient
            // transformation properties. As parse tree nodes live longer than transformation
            // nodes, we need to make sure we reclaim any memory allocated for custom ranges
            // from these nodes to ensure we do not hold onto entire subtrees just for position
            // information. We also need to reset these nodes to a pre-transformation state
            // for incremental parsing scenarios so that we do not impact later emit.
            sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
            var emitNode = sourceFile && sourceFile.emitNode;
            var annotatedNodes = emitNode && emitNode.annotatedNodes;
            if (annotatedNodes) {
                for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
                    var node = annotatedNodes_1[_i];
                    node.emitNode = undefined;
                }
            }
        }
        ts.disposeEmitNodes = disposeEmitNodes;
        /**
         * Associates a node with the current transformation, initializing
         * various transient transformation properties.
         */
        /* @internal */
        function getOrCreateEmitNode(node) {
            if (!node.emitNode) {
                if (ts.isParseTreeNode(node)) {
                    // To avoid holding onto transformation artifacts, we keep track of any
                    // parse tree node we are annotating. This allows us to clean them up after
                    // all transformations have completed.
                    if (node.kind === 277 /* SourceFile */) {
                        return node.emitNode = { annotatedNodes: [node] };
                    }
                    var sourceFile = ts.getSourceFileOfNode(node);
                    getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
                }
                node.emitNode = {};
            }
            return node.emitNode;
        }
        ts.getOrCreateEmitNode = getOrCreateEmitNode;
        function setTextRange(range, location) {
            if (location) {
                range.pos = location.pos;
                range.end = location.end;
            }
            return range;
        }
        ts.setTextRange = setTextRange;
        /**
         * Sets flags that control emit behavior of a node.
         */
        function setEmitFlags(node, emitFlags) {
            getOrCreateEmitNode(node).flags = emitFlags;
            return node;
        }
        ts.setEmitFlags = setEmitFlags;
        /**
         * Sets flags that control emit behavior of a node.
         */
        /* @internal */
        function addEmitFlags(node, emitFlags) {
            var emitNode = getOrCreateEmitNode(node);
            emitNode.flags = emitNode.flags | emitFlags;
            return node;
        }
        ts.addEmitFlags = addEmitFlags;
        /**
         * Gets a custom text range to use when emitting source maps.
         */
        function getSourceMapRange(node) {
            var emitNode = node.emitNode;
            return (emitNode && emitNode.sourceMapRange) || node;
        }
        ts.getSourceMapRange = getSourceMapRange;
        /**
         * Sets a custom text range to use when emitting source maps.
         */
        function setSourceMapRange(node, range) {
            getOrCreateEmitNode(node).sourceMapRange = range;
            return node;
        }
        ts.setSourceMapRange = setSourceMapRange;
        // tslint:disable-next-line variable-name
        var SourceMapSource;
        /**
         * Create an external source map source file reference
         */
        function createSourceMapSource(fileName, text, skipTrivia) {
            return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
        }
        ts.createSourceMapSource = createSourceMapSource;
        /**
         * Gets the TextRange to use for source maps for a token of a node.
         */
        function getTokenSourceMapRange(node, token) {
            var emitNode = node.emitNode;
            var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
            return tokenSourceMapRanges && tokenSourceMapRanges[token];
        }
        ts.getTokenSourceMapRange = getTokenSourceMapRange;
        /**
         * Sets the TextRange to use for source maps for a token of a node.
         */
        function setTokenSourceMapRange(node, token, range) {
            var emitNode = getOrCreateEmitNode(node);
            var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
            tokenSourceMapRanges[token] = range;
            return node;
        }
        ts.setTokenSourceMapRange = setTokenSourceMapRange;
        /**
         * Gets a custom text range to use when emitting comments.
         */
        /*@internal*/
        function getStartsOnNewLine(node) {
            var emitNode = node.emitNode;
            return emitNode && emitNode.startsOnNewLine;
        }
        ts.getStartsOnNewLine = getStartsOnNewLine;
        /**
         * Sets a custom text range to use when emitting comments.
         */
        /*@internal*/
        function setStartsOnNewLine(node, newLine) {
            getOrCreateEmitNode(node).startsOnNewLine = newLine;
            return node;
        }
        ts.setStartsOnNewLine = setStartsOnNewLine;
        /**
         * Gets a custom text range to use when emitting comments.
         */
        function getCommentRange(node) {
            var emitNode = node.emitNode;
            return (emitNode && emitNode.commentRange) || node;
        }
        ts.getCommentRange = getCommentRange;
        /**
         * Sets a custom text range to use when emitting comments.
         */
        function setCommentRange(node, range) {
            getOrCreateEmitNode(node).commentRange = range;
            return node;
        }
        ts.setCommentRange = setCommentRange;
        function getSyntheticLeadingComments(node) {
            var emitNode = node.emitNode;
            return emitNode && emitNode.leadingComments;
        }
        ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
        function setSyntheticLeadingComments(node, comments) {
            getOrCreateEmitNode(node).leadingComments = comments;
            return node;
        }
        ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
        function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
            return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
        }
        ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
        function getSyntheticTrailingComments(node) {
            var emitNode = node.emitNode;
            return emitNode && emitNode.trailingComments;
        }
        ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
        function setSyntheticTrailingComments(node, comments) {
            getOrCreateEmitNode(node).trailingComments = comments;
            return node;
        }
        ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
        function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
            return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
        }
        ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
        function moveSyntheticComments(node, original) {
            setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
            setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
            var emit = getOrCreateEmitNode(original);
            emit.leadingComments = undefined;
            emit.trailingComments = undefined;
            return node;
        }
        ts.moveSyntheticComments = moveSyntheticComments;
        /**
         * Gets the constant value to emit for an expression.
         */
        function getConstantValue(node) {
            var emitNode = node.emitNode;
            return emitNode && emitNode.constantValue;
        }
        ts.getConstantValue = getConstantValue;
        /**
         * Sets the constant value to emit for an expression.
         */
        function setConstantValue(node, value) {
            var emitNode = getOrCreateEmitNode(node);
            emitNode.constantValue = value;
            return node;
        }
        ts.setConstantValue = setConstantValue;
        /**
         * Adds an EmitHelper to a node.
         */
        function addEmitHelper(node, helper) {
            var emitNode = getOrCreateEmitNode(node);
            emitNode.helpers = ts.append(emitNode.helpers, helper);
            return node;
        }
        ts.addEmitHelper = addEmitHelper;
        /**
         * Add EmitHelpers to a node.
         */
        function addEmitHelpers(node, helpers) {
            if (ts.some(helpers)) {
                var emitNode = getOrCreateEmitNode(node);
                for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
                    var helper = helpers_1[_i];
                    emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
                }
            }
            return node;
        }
        ts.addEmitHelpers = addEmitHelpers;
        /**
         * Removes an EmitHelper from a node.
         */
        function removeEmitHelper(node, helper) {
            var emitNode = node.emitNode;
            if (emitNode) {
                var helpers = emitNode.helpers;
                if (helpers) {
                    return ts.orderedRemoveItem(helpers, helper);
                }
            }
            return false;
        }
        ts.removeEmitHelper = removeEmitHelper;
        /**
         * Gets the EmitHelpers of a node.
         */
        function getEmitHelpers(node) {
            var emitNode = node.emitNode;
            return emitNode && emitNode.helpers;
        }
        ts.getEmitHelpers = getEmitHelpers;
        /**
         * Moves matching emit helpers from a source node to a target node.
         */
        function moveEmitHelpers(source, target, predicate) {
            var sourceEmitNode = source.emitNode;
            var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
            if (!ts.some(sourceEmitHelpers))
                return;
            var targetEmitNode = getOrCreateEmitNode(target);
            var helpersRemoved = 0;
            for (var i = 0; i < sourceEmitHelpers.length; i++) {
                var helper = sourceEmitHelpers[i];
                if (predicate(helper)) {
                    helpersRemoved++;
                    targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
                }
                else if (helpersRemoved > 0) {
                    sourceEmitHelpers[i - helpersRemoved] = helper;
                }
            }
            if (helpersRemoved > 0) {
                sourceEmitHelpers.length -= helpersRemoved;
            }
        }
        ts.moveEmitHelpers = moveEmitHelpers;
        /* @internal */
        function compareEmitHelpers(x, y) {
            if (x === y)
                return 0 /* EqualTo */;
            if (x.priority === y.priority)
                return 0 /* EqualTo */;
            if (x.priority === undefined)
                return 1 /* GreaterThan */;
            if (y.priority === undefined)
                return -1 /* LessThan */;
            return ts.compareValues(x.priority, y.priority);
        }
        ts.compareEmitHelpers = compareEmitHelpers;
        function setOriginalNode(node, original) {
            node.original = original;
            if (original) {
                var emitNode = original.emitNode;
                if (emitNode)
                    node.emitNode = mergeEmitNode(emitNode, node.emitNode);
            }
            return node;
        }
        ts.setOriginalNode = setOriginalNode;
        function mergeEmitNode(sourceEmitNode, destEmitNode) {
            var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine;
            if (!destEmitNode)
                destEmitNode = {};
            // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
            if (leadingComments)
                destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
            if (trailingComments)
                destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
            if (flags)
                destEmitNode.flags = flags;
            if (commentRange)
                destEmitNode.commentRange = commentRange;
            if (sourceMapRange)
                destEmitNode.sourceMapRange = sourceMapRange;
            if (tokenSourceMapRanges)
                destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
            if (constantValue !== undefined)
                destEmitNode.constantValue = constantValue;
            if (helpers)
                destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
            if (startsOnNewLine !== undefined)
                destEmitNode.startsOnNewLine = startsOnNewLine;
            return destEmitNode;
        }
        function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
            if (!destRanges)
                destRanges = [];
            for (var key in sourceRanges) {
                destRanges[key] = sourceRanges[key];
            }
            return destRanges;
        }
    })(ts || (ts = {}));
    /* @internal */
    (function (ts) {
        ts.nullTransformationContext = {
            enableEmitNotification: ts.noop,
            enableSubstitution: ts.noop,
            endLexicalEnvironment: function () { return undefined; },
            getCompilerOptions: ts.notImplemented,
            getEmitHost: ts.notImplemented,
            getEmitResolver: ts.notImplemented,
            hoistFunctionDeclaration: ts.noop,
            hoistVariableDeclaration: ts.noop,
            isEmitNotificationEnabled: ts.notImplemented,
            isSubstitutionEnabled: ts.notImplemented,
            onEmitNode: ts.noop,
            onSubstituteNode: ts.notImplemented,
            readEmitHelpers: ts.notImplemented,
            requestEmitHelper: ts.noop,
            resumeLexicalEnvironment: ts.noop,
            startLexicalEnvironment: ts.noop,
            suspendLexicalEnvironment: ts.noop,
            addDiagnostic: ts.noop,
        };
        function createTypeCheck(value, tag) {
            return tag === "undefined"
                ? ts.createStrictEquality(value, ts.createVoidZero())
                : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
        }
        ts.createTypeCheck = createTypeCheck;
        function createMemberAccessForPropertyName(target, memberName, location) {
            if (ts.isComputedPropertyName(memberName)) {
                return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
            }
            else {
                var expression = ts.setTextRange(ts.isIdentifier(memberName)
                    ? ts.createPropertyAccess(target, memberName)
                    : ts.createElementAccess(target, memberName), memberName);
                ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
                return expression;
            }
        }
        ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
        function createFunctionCall(func, thisArg, argumentsList, location) {
            return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), 
            /*typeArguments*/ undefined, [
                thisArg
            ].concat(argumentsList)), location);
        }
        ts.createFunctionCall = createFunctionCall;
        function createFunctionApply(func, thisArg, argumentsExpression, location) {
            return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), 
            /*typeArguments*/ undefined, [
                thisArg,
                argumentsExpression
            ]), location);
        }
        ts.createFunctionApply = createFunctionApply;
        function createArraySlice(array, start) {
            var argumentsList = [];
            if (start !== undefined) {
                argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
            }
            return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
        }
        ts.createArraySlice = createArraySlice;
        function createArrayConcat(array, values) {
            return ts.createCall(ts.createPropertyAccess(array, "concat"), 
            /*typeArguments*/ undefined, values);
        }
        ts.createArrayConcat = createArrayConcat;
        function createMathPow(left, right, location) {
            return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), 
            /*typeArguments*/ undefined, [left, right]), location);
        }
        ts.createMathPow = createMathPow;
        function createReactNamespace(reactNamespace, parent) {
            // To ensure the emit resolver can properly resolve the namespace, we need to
            // treat this identifier as if it were a source tree node by clearing the `Synthesized`
            // flag and setting a parent node.
            var react = ts.createIdentifier(reactNamespace || "React");
            react.flags &= ~8 /* Synthesized */;
            // Set the parent that is in parse tree
            // this makes sure that parent chain is intact for checker to traverse complete scope tree
            react.parent = ts.getParseTreeNode(parent);
            return react;
        }
        function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
            if (ts.isQualifiedName(jsxFactory)) {
                var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
                var right = ts.createIdentifier(ts.idText(jsxFactory.right));
                right.escapedText = jsxFactory.right.escapedText;
                return ts.createPropertyAccess(left, right);
            }
            else {
                return createReactNamespace(ts.idText(jsxFactory), parent);
            }
        }
        function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
            return jsxFactoryEntity ?
                createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
                ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
        }
        function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
            var argumentsList = [tagName];
            if (props) {
                argumentsList.push(props);
            }
            if (children && children.length > 0) {
                if (!props) {
                    argumentsList.push(ts.createNull());
                }
                if (children.length > 1) {
                    for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
                        var child = children_1[_i];
                        startOnNewLine(child);
                        argumentsList.push(child);
                    }
                }
                else {
                    argumentsList.push(children[0]);
                }
            }
            return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
            /*typeArguments*/ undefined, argumentsList), location);
        }
        ts.createExpressionForJsxElement = createExpressionForJsxElement;
        function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
            var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
            var argumentsList = [tagName];
            argumentsList.push(ts.createNull());
            if (children && children.length > 0) {
                if (children.length > 1) {
                    for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
                        var child = children_2[_i];
                        startOnNewLine(child);
                        argumentsList.push(child);
                    }
                }
                else {
                    argumentsList.push(children[0]);
                }
            }
            return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
            /*typeArguments*/ undefined, argumentsList), location);
        }
        ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
        // Helpers
        function getHelperName(name) {
            return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
        }
        ts.getHelperName = getHelperName;
        var valuesHelper = {
            name: "typescript:values",
            scoped: false,
            text: "\n            var __values = (this && this.__values) || function (o) {\n                var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n                if (m) return m.call(o);\n                return {\n                    next: function () {\n                        if (o && i >= o.length) o = void 0;\n                        return { value: o && o[i++], done: !o };\n                    }\n                };\n            };"
        };
        function createValuesHelper(context, expression, location) {
            context.requestEmitHelper(valuesHelper);
            return ts.setTextRange(ts.createCall(getHelperName("__values"), 
            /*typeArguments*/ undefined, [expression]), location);
        }
        ts.createValuesHelper = createValuesHelper;
        var readHelper = {
            name: "typescript:read",
            scoped: false,
            text: "\n            var __read = (this && this.__read) || function (o, n) {\n                var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n                if (!m) return o;\n                var i = m.call(o), r, ar = [], e;\n                try {\n                    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n                }\n                catch (error) { e = { error: error }; }\n                finally {\n                    try {\n                        if (r && !r.done && (m = i[\"return\"])) m.call(i);\n                    }\n                    finally { if (e) throw e.error; }\n                }\n                return ar;\n            };"
        };
        function createReadHelper(context, iteratorRecord, count, location) {
            context.requestEmitHelper(readHelper);
            return ts.setTextRange(ts.createCall(getHelperName("__read"), 
            /*typeArguments*/ undefined, count !== undefined
                ? [iteratorRecord, ts.createLiteral(count)]
                : [iteratorRecord]), location);
        }
        ts.createReadHelper = createReadHelper;
        var spreadHelper = {
            name: "typescript:spread",
            scoped: false,
            text: "\n            var __spread = (this && this.__spread) || function () {\n                for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n                return ar;\n            };"
        };
        function createSpreadHelper(context, argumentList, location) {
            context.requestEmitHelper(readHelper);
            context.requestEmitHelper(spreadHelper);
            return ts.setTextRange(ts.createCall(getHelperName("__spread"), 
            /*typeArguments*/ undefined, argumentList), location);
        }
        ts.createSpreadHelper = createSpreadHelper;
        // Utilities
        function createForOfBindingStatement(node, boundValue) {
            if (ts.isVariableDeclarationList(node)) {
                var firstDeclaration = ts.first(node.declarations);
                var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
                /*typeNode*/ undefined, boundValue);
                return ts.setTextRange(ts.createVariableStatement(
                /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), 
                /*location*/ node);
            }
            else {
                var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
                return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
            }
        }
        ts.createForOfBindingStatement = createForOfBindingStatement;
        function insertLeadingStatement(dest, source) {
            if (ts.isBlock(dest)) {
                return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements));
            }
            else {
                return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
            }
        }
        ts.insertLeadingStatement = insertLeadingStatement;
        function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
            if (!outermostLabeledStatement) {
                return node;
            }
            var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */
                ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
                : node);
            if (afterRestoreLabelCallback) {
                afterRestoreLabelCallback(outermostLabeledStatement);
            }
            return updated;
        }
        ts.restoreEnclosingLabel = restoreEnclosingLabel;
        function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
            var target = ts.skipParentheses(node);
            switch (target.kind) {
                case 71 /* Identifier */:
                    return cacheIdentifiers;
                case 99 /* ThisKeyword */:
                case 8 /* NumericLiteral */:
                case 9 /* StringLiteral */:
                    return false;
                case 185 /* ArrayLiteralExpression */:
                    var elements = target.elements;
                    if (elements.length === 0) {
                        return false;
                    }
                    return true;
                case 186 /* ObjectLiteralExpression */:
                    return target.properties.length > 0;
                default:
                    return true;
            }
        }
        function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
            if (cacheIdentifiers === void 0) {
                cacheIdentifiers = false;
            }
            var callee = skipOuterExpressions(expression, 7 /* All */);
            var thisArg;
            var target;
            if (ts.isSuperProperty(callee)) {
                thisArg = ts.createThis();
                target = callee;
            }
            else if (callee.kind === 97 /* SuperKeyword */) {
                thisArg = ts.createThis();
                target = languageVersion < 2 /* ES2015 */
                    ? ts.setTextRange(ts.createIdentifier("_super"), callee)
                    : callee;
            }
            else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
                thisArg = ts.createVoidZero();
                target = parenthesizeForAccess(callee);
            }
            else {
                switch (callee.kind) {
                    case 187 /* PropertyAccessExpression */: {
                        if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
                            // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
                            thisArg = ts.createTempVariable(recordTempVariable);
                            target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
                            ts.setTextRange(target, callee);
                        }
                        else {
                            thisArg = callee.expression;
                            target = callee;
                        }
                        break;
                    }
                    case 188 /* ElementAccessExpression */: {
                        if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
                            // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
                            thisArg = ts.createTempVariable(recordTempVariable);
                            target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
                            ts.setTextRange(target, callee);
                        }
                        else {
                            thisArg = callee.expression;
                            target = callee;
                        }
                        break;
                    }
                    default: {
                        // for `a()` target is `a` and thisArg is `void 0`
                        thisArg = ts.createVoidZero();
                        target = parenthesizeForAccess(expression);
                        break;
                    }
                }
            }
            return { target: target, thisArg: thisArg };
        }
        ts.createCallBinding = createCallBinding;
        function inlineExpressions(expressions) {
            // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
            // stack size exceeded" errors.
            return expressions.length > 10
                ? ts.createCommaList(expressions)
                : ts.reduceLeft(expressions, ts.createComma);
        }
        ts.inlineExpressions = inlineExpressions;
        function createExpressionFromEntityName(node) {
            if (ts.isQualifiedName(node)) {
                var left = createExpressionFromEntityName(node.left);
                var right = ts.getMutableClone(node.right);
                return ts.setTextRange(ts.createPropertyAccess(left, right), node);
            }
            else {
                return ts.getMutableClone(node);
            }
        }
        ts.createExpressionFromEntityName = createExpressionFromEntityName;
        function createExpressionForPropertyName(memberName) {
            if (ts.isIdentifier(memberName)) {
                return ts.createLiteral(memberName);
            }
            else if (ts.isComputedPropertyName(memberName)) {
                return ts.getMutableClone(memberName.expression);
            }
            else {
                return ts.getMutableClone(memberName);
            }
        }
        ts.createExpressionForPropertyName = createExpressionForPropertyName;
        function createExpressionForObjectLiteralElementLike(node, property, receiver) {
            switch (property.kind) {
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                    return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
                case 273 /* PropertyAssignment */:
                    return createExpressionForPropertyAssignment(property, receiver);
                case 274 /* ShorthandPropertyAssignment */:
                    return createExpressionForShorthandPropertyAssignment(property, receiver);
                case 154 /* MethodDeclaration */:
                    return createExpressionForMethodDeclaration(property, receiver);
            }
        }
        ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
        function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
            var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
            if (property === firstAccessor) {
                var properties_9 = [];
                if (getAccessor) {
                    var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, 
                    /*asteriskToken*/ undefined, 
                    /*name*/ undefined, 
                    /*typeParameters*/ undefined, getAccessor.parameters, 
                    /*type*/ undefined, getAccessor.body // TODO: GH#18217
                    );
                    ts.setTextRange(getterFunction, getAccessor);
                    ts.setOriginalNode(getterFunction, getAccessor);
                    var getter = ts.createPropertyAssignment("get", getterFunction);
                    properties_9.push(getter);
                }
                if (setAccessor) {
                    var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, 
                    /*asteriskToken*/ undefined, 
                    /*name*/ undefined, 
                    /*typeParameters*/ undefined, setAccessor.parameters, 
                    /*type*/ undefined, setAccessor.body // TODO: GH#18217
                    );
                    ts.setTextRange(setterFunction, setAccessor);
                    ts.setOriginalNode(setterFunction, setAccessor);
                    var setter = ts.createPropertyAssignment("set", setterFunction);
                    properties_9.push(setter);
                }
                properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
                properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
                var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
                /*typeArguments*/ undefined, [
                    receiver,
                    createExpressionForPropertyName(property.name),
                    ts.createObjectLiteral(properties_9, multiLine)
                ]), 
                /*location*/ firstAccessor);
                return ts.aggregateTransformFlags(expression);
            }
            return undefined;
        }
        function createExpressionForPropertyAssignment(property, receiver) {
            return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
        }
        function createExpressionForShorthandPropertyAssignment(property, receiver) {
            return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), 
            /*location*/ property), 
            /*original*/ property));
        }
        function createExpressionForMethodDeclaration(method, receiver) {
            return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, 
            /*name*/ undefined, 
            /*typeParameters*/ undefined, method.parameters, 
            /*type*/ undefined, method.body // TODO: GH#18217
            ), 
            /*location*/ method), 
            /*original*/ method)), 
            /*location*/ method), 
            /*original*/ method));
        }
        /**
         * Gets the internal name of a declaration. This is primarily used for declarations that can be
         * referred to by name in the body of an ES5 class function body. An internal name will *never*
         * be prefixed with an module or namespace export modifier like "exports." when emitted as an
         * expression. An internal name will also *never* be renamed due to a collision with a block
         * scoped variable.
         *
         * @param node The declaration.
         * @param allowComments A value indicating whether comments may be emitted for the name.
         * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
         */
        function getInternalName(node, allowComments, allowSourceMaps) {
            return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
        }
        ts.getInternalName = getInternalName;
        /**
         * Gets whether an identifier should only be referred to by its internal name.
         */
        function isInternalName(node) {
            return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
        }
        ts.isInternalName = isInternalName;
        /**
         * Gets the local name of a declaration. This is primarily used for declarations that can be
         * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
         * local name will *never* be prefixed with an module or namespace export modifier like
         * "exports." when emitted as an expression.
         *
         * @param node The declaration.
         * @param allowComments A value indicating whether comments may be emitted for the name.
         * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
         */
        function getLocalName(node, allowComments, allowSourceMaps) {
            return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
        }
        ts.getLocalName = getLocalName;
        /**
         * Gets whether an identifier should only be referred to by its local name.
         */
        function isLocalName(node) {
            return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
        }
        ts.isLocalName = isLocalName;
        /**
         * Gets the export name of a declaration. This is primarily used for declarations that can be
         * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
         * export name will *always* be prefixed with an module or namespace export modifier like
         * `"exports."` when emitted as an expression if the name points to an exported symbol.
         *
         * @param node The declaration.
         * @param allowComments A value indicating whether comments may be emitted for the name.
         * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
         */
        function getExportName(node, allowComments, allowSourceMaps) {
            return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
        }
        ts.getExportName = getExportName;
        /**
         * Gets whether an identifier should only be referred to by its export representation if the
         * name points to an exported symbol.
         */
        function isExportName(node) {
            return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
        }
        ts.isExportName = isExportName;
        /**
         * Gets the name of a declaration for use in declarations.
         *
         * @param node The declaration.
         * @param allowComments A value indicating whether comments may be emitted for the name.
         * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
         */
        function getDeclarationName(node, allowComments, allowSourceMaps) {
            return getName(node, allowComments, allowSourceMaps);
        }
        ts.getDeclarationName = getDeclarationName;
        function getName(node, allowComments, allowSourceMaps, emitFlags) {
            if (emitFlags === void 0) {
                emitFlags = 0;
            }
            var nodeName = ts.getNameOfDeclaration(node);
            if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
                var name = ts.getMutableClone(nodeName);
                emitFlags |= ts.getEmitFlags(nodeName);
                if (!allowSourceMaps)
                    emitFlags |= 48 /* NoSourceMap */;
                if (!allowComments)
                    emitFlags |= 1536 /* NoComments */;
                if (emitFlags)
                    ts.setEmitFlags(name, emitFlags);
                return name;
            }
            return ts.getGeneratedNameForNode(node);
        }
        /**
         * Gets the exported name of a declaration for use in expressions.
         *
         * An exported name will *always* be prefixed with an module or namespace export modifier like
         * "exports." if the name points to an exported symbol.
         *
         * @param ns The namespace identifier.
         * @param node The declaration.
         * @param allowComments A value indicating whether comments may be emitted for the name.
         * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
         */
        function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
            if (ns && ts.hasModifier(node, 1 /* Export */)) {
                return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
            }
            return getExportName(node, allowComments, allowSourceMaps);
        }
        ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
        /**
         * Gets a namespace-qualified name for use in expressions.
         *
         * @param ns The namespace identifier.
         * @param name The name.
         * @param allowComments A value indicating whether comments may be emitted for the name.
         * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
         */
        function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
            var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
            ts.setTextRange(qualifiedName, name);
            var emitFlags = 0;
            if (!allowSourceMaps)
                emitFlags |= 48 /* NoSourceMap */;
            if (!allowComments)
                emitFlags |= 1536 /* NoComments */;
            if (emitFlags)
                ts.setEmitFlags(qualifiedName, emitFlags);
            return qualifiedName;
        }
        ts.getNamespaceMemberName = getNamespaceMemberName;
        function convertToFunctionBody(node, multiLine) {
            return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
        }
        ts.convertToFunctionBody = convertToFunctionBody;
        function convertFunctionDeclarationToExpression(node) {
            if (!node.body)
                return ts.Debug.fail();
            var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
            ts.setOriginalNode(updated, node);
            ts.setTextRange(updated, node);
            if (ts.getStartsOnNewLine(node)) {
                ts.setStartsOnNewLine(updated, /*newLine*/ true);
            }
            ts.aggregateTransformFlags(updated);
            return updated;
        }
        ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
        function isUseStrictPrologue(node) {
            return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
        }
        /**
         * Add any necessary prologue-directives into target statement-array.
         * The function needs to be called during each transformation step.
         * This function needs to be called whenever we transform the statement
         * list of a source file, namespace, or function-like body.
         *
         * @param target: result statements array
         * @param source: origin statements array
         * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
         * @param visitor: Optional callback used to visit any custom prologue directives.
         */
        function addPrologue(target, source, ensureUseStrict, visitor) {
            var offset = addStandardPrologue(target, source, ensureUseStrict);
            return addCustomPrologue(target, source, offset, visitor);
        }
        ts.addPrologue = addPrologue;
        /**
         * Add just the standard (string-expression) prologue-directives into target statement-array.
         * The function needs to be called during each transformation step.
         * This function needs to be called whenever we transform the statement
         * list of a source file, namespace, or function-like body.
         */
        function addStandardPrologue(target, source, ensureUseStrict) {
            ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
            var foundUseStrict = false;
            var statementOffset = 0;
            var numStatements = source.length;
            while (statementOffset < numStatements) {
                var statement = source[statementOffset];
                if (ts.isPrologueDirective(statement)) {
                    if (isUseStrictPrologue(statement)) {
                        foundUseStrict = true;
                    }
                    target.push(statement);
                }
                else {
                    break;
                }
                statementOffset++;
            }
            if (ensureUseStrict && !foundUseStrict) {
                target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
            }
            return statementOffset;
        }
        ts.addStandardPrologue = addStandardPrologue;
        function addCustomPrologue(target, source, statementOffset, visitor) {
            var numStatements = source.length;
            while (statementOffset !== undefined && statementOffset < numStatements) {
                var statement = source[statementOffset];
                if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) {
                    ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
                }
                else {
                    break;
                }
                statementOffset++;
            }
            return statementOffset;
        }
        ts.addCustomPrologue = addCustomPrologue;
        function findUseStrictPrologue(statements) {
            for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
                var statement = statements_3[_i];
                if (ts.isPrologueDirective(statement)) {
                    if (isUseStrictPrologue(statement)) {
                        return statement;
                    }
                }
                else {
                    break;
                }
            }
            return undefined;
        }
        ts.findUseStrictPrologue = findUseStrictPrologue;
        function startsWithUseStrict(statements) {
            var firstStatement = ts.firstOrUndefined(statements);
            return firstStatement !== undefined
                && ts.isPrologueDirective(firstStatement)
                && isUseStrictPrologue(firstStatement);
        }
        ts.startsWithUseStrict = startsWithUseStrict;
        /**
         * Ensures "use strict" directive is added
         *
         * @param statements An array of statements
         */
        function ensureUseStrict(statements) {
            var foundUseStrict = findUseStrictPrologue(statements);
            if (!foundUseStrict) {
                return ts.setTextRange(ts.createNodeArray([
                    startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
                ].concat(statements)), statements);
            }
            return statements;
        }
        ts.ensureUseStrict = ensureUseStrict;
        /**
         * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
         * order of operations.
         *
         * @param binaryOperator The operator for the BinaryExpression.
         * @param operand The operand for the BinaryExpression.
         * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
         *                           BinaryExpression.
         */
        function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
            var skipped = ts.skipPartiallyEmittedExpressions(operand);
            // If the resulting expression is already parenthesized, we do not need to do any further processing.
            if (skipped.kind === 193 /* ParenthesizedExpression */) {
                return operand;
            }
            return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
                ? ts.createParen(operand)
                : operand;
        }
        ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
        /**
         * Determines whether the operand to a BinaryExpression needs to be parenthesized.
         *
         * @param binaryOperator The operator for the BinaryExpression.
         * @param operand The operand for the BinaryExpression.
         * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
         *                           BinaryExpression.
         */
        function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
            // If the operand has lower precedence, then it needs to be parenthesized to preserve the
            // intent of the expression. For example, if the operand is `a + b` and the operator is
            // `*`, then we need to parenthesize the operand to preserve the intended order of
            // operations: `(a + b) * x`.
            //
            // If the operand has higher precedence, then it does not need to be parenthesized. For
            // example, if the operand is `a * b` and the operator is `+`, then we do not need to
            // parenthesize to preserve the intended order of operations: `a * b + x`.
            //
            // If the operand has the same precedence, then we need to check the associativity of
            // the operator based on whether this is the left or right operand of the expression.
            //
            // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
            // to preserve the intended order of operations: `x * (a / d)`
            //
            // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
            // the intended order of operations: `(a ** b) ** c`
            var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator);
            var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator);
            var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
            if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) {
                // We need to parenthesize arrow functions on the right side to avoid it being
                // parsed as parenthesized expression: `a && (() => {})`
                return true;
            }
            var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
            switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
                case -1 /* LessThan */:
                    // If the operand is the right side of a right-associative binary operation
                    // and is a yield expression, then we do not need parentheses.
                    if (!isLeftSideOfBinary
                        && binaryOperatorAssociativity === 1 /* Right */
                        && operand.kind === 205 /* YieldExpression */) {
                        return false;
                    }
                    return true;
                case 1 /* GreaterThan */:
                    return false;
                case 0 /* EqualTo */:
                    if (isLeftSideOfBinary) {
                        // No need to parenthesize the left operand when the binary operator is
                        // left associative:
                        //  (a*b)/x    -> a*b/x
                        //  (a**b)/x   -> a**b/x
                        //
                        // Parentheses are needed for the left operand when the binary operator is
                        // right associative:
                        //  (a/b)**x   -> (a/b)**x
                        //  (a**b)**x  -> (a**b)**x
                        return binaryOperatorAssociativity === 1 /* Right */;
                    }
                    else {
                        if (ts.isBinaryExpression(emittedOperand)
                            && emittedOperand.operatorToken.kind === binaryOperator) {
                            // No need to parenthesize the right operand when the binary operator and
                            // operand are the same and one of the following:
                            //  x*(a*b)     => x*a*b
                            //  x|(a|b)     => x|a|b
                            //  x&(a&b)     => x&a&b
                            //  x^(a^b)     => x^a^b
                            if (operatorHasAssociativeProperty(binaryOperator)) {
                                return false;
                            }
                            // No need to parenthesize the right operand when the binary operator
                            // is plus (+) if both the left and right operands consist solely of either
                            // literals of the same kind or binary plus (+) expressions for literals of
                            // the same kind (recursively).
                            //  "a"+(1+2)       => "a"+(1+2)
                            //  "a"+("b"+"c")   => "a"+"b"+"c"
                            if (binaryOperator === 37 /* PlusToken */) {
                                var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
                                if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
                                    return false;
                                }
                            }
                        }
                        // No need to parenthesize the right operand when the operand is right
                        // associative:
                        //  x/(a**b)    -> x/a**b
                        //  x**(a**b)   -> x**a**b
                        //
                        // Parentheses are needed for the right operand when the operand is left
                        // associative:
                        //  x/(a*b)     -> x/(a*b)
                        //  x**(a/b)    -> x**(a/b)
                        var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
                        return operandAssociativity === 0 /* Left */;
                    }
            }
        }
        /**
         * Determines whether a binary operator is mathematically associative.
         *
         * @param binaryOperator The binary operator.
         */
        function operatorHasAssociativeProperty(binaryOperator) {
            // The following operators are associative in JavaScript:
            //  (a*b)*c     -> a*(b*c)  -> a*b*c
            //  (a|b)|c     -> a|(b|c)  -> a|b|c
            //  (a&b)&c     -> a&(b&c)  -> a&b&c
            //  (a^b)^c     -> a^(b^c)  -> a^b^c
            //
            // While addition is associative in mathematics, JavaScript's `+` is not
            // guaranteed to be associative as it is overloaded with string concatenation.
            return binaryOperator === 39 /* AsteriskToken */
                || binaryOperator === 49 /* BarToken */
                || binaryOperator === 48 /* AmpersandToken */
                || binaryOperator === 50 /* CaretToken */;
        }
        /**
         * This function determines whether an expression consists of a homogeneous set of
         * literal expressions or binary plus expressions that all share the same literal kind.
         * It is used to determine whether the right-hand operand of a binary plus expression can be
         * emitted without parentheses.
         */
        function getLiteralKindOfBinaryPlusOperand(node) {
            node = ts.skipPartiallyEmittedExpressions(node);
            if (ts.isLiteralKind(node.kind)) {
                return node.kind;
            }
            if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) {
                if (node.cachedLiteralKind !== undefined) {
                    return node.cachedLiteralKind;
                }
                var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
                var literalKind = ts.isLiteralKind(leftKind)
                    && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
                    ? leftKind
                    : 0 /* Unknown */;
                node.cachedLiteralKind = literalKind;
                return literalKind;
            }
            return 0 /* Unknown */;
        }
        function parenthesizeForConditionalHead(condition) {
            var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */);
            var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
            var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
            if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) {
                return ts.createParen(condition);
            }
            return condition;
        }
        ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
        function parenthesizeSubexpressionOfConditionalExpression(e) {
            // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
            // so in case when comma expression is introduced as a part of previous transformations
            // if should be wrapped in parens since comma operator has the lowest precedence
            var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
            return isCommaSequence(emittedExpression)
                ? ts.createParen(e)
                : e;
        }
        ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
        /**
         *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
         *  has a lookahead restriction for `function`, `async function`, and `class`.
         *
         * Basically, that means we need to parenthesize in the following cases:
         *
         * - BinaryExpression of CommaToken
         * - CommaList (synthetic list of multiple comma expressions)
         * - FunctionExpression
         * - ClassExpression
         */
        function parenthesizeDefaultExpression(e) {
            var check = ts.skipPartiallyEmittedExpressions(e);
            var needsParens = isCommaSequence(check);
            if (!needsParens) {
                switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
                    case 207 /* ClassExpression */:
                    case 194 /* FunctionExpression */:
                        needsParens = true;
                }
            }
            return needsParens ? ts.createParen(e) : e;
        }
        ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
        /**
         * Wraps an expression in parentheses if it is needed in order to use the expression
         * as the expression of a NewExpression node.
         *
         * @param expression The Expression node.
         */
        function parenthesizeForNew(expression) {
            var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
            switch (leftmostExpr.kind) {
                case 189 /* CallExpression */:
                    return ts.createParen(expression);
                case 190 /* NewExpression */:
                    return !leftmostExpr.arguments
                        ? ts.createParen(expression)
                        : expression;
            }
            return parenthesizeForAccess(expression);
        }
        ts.parenthesizeForNew = parenthesizeForNew;
        /**
         * Wraps an expression in parentheses if it is needed in order to use the expression for
         * property or element access.
         *
         * @param expr The expression node.
         */
        function parenthesizeForAccess(expression) {
            // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
            // to parenthesize the expression before a dot. The known exception is:
            //
            //    NewExpression:
            //       new C.x        -> not the same as (new C).x
            //
            var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
            if (ts.isLeftHandSideExpression(emittedExpression)
                && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) {
                return expression;
            }
            return ts.setTextRange(ts.createParen(expression), expression);
        }
        ts.parenthesizeForAccess = parenthesizeForAccess;
        function parenthesizePostfixOperand(operand) {
            return ts.isLeftHandSideExpression(operand)
                ? operand
                : ts.setTextRange(ts.createParen(operand), operand);
        }
        ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
        function parenthesizePrefixOperand(operand) {
            return ts.isUnaryExpression(operand)
                ? operand
                : ts.setTextRange(ts.createParen(operand), operand);
        }
        ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
        function parenthesizeListElements(elements) {
            var result;
            for (var i = 0; i < elements.length; i++) {
                var element = parenthesizeExpressionForList(elements[i]);
                if (result !== undefined || element !== elements[i]) {
                    if (result === undefined) {
                        result = elements.slice(0, i);
                    }
                    result.push(element);
                }
            }
            if (result !== undefined) {
                return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
            }
            return elements;
        }
        ts.parenthesizeListElements = parenthesizeListElements;
        function parenthesizeExpressionForList(expression) {
            var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
            var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
            var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */);
            return expressionPrecedence > commaPrecedence
                ? expression
                : ts.setTextRange(ts.createParen(expression), expression);
        }
        ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
        function parenthesizeExpressionForExpressionStatement(expression) {
            var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
            if (ts.isCallExpression(emittedExpression)) {
                var callee = emittedExpression.expression;
                var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
                if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) {
                    var mutableCall = ts.getMutableClone(emittedExpression);
                    mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
                    return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */);
                }
            }
            var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
            if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) {
                return ts.setTextRange(ts.createParen(expression), expression);
            }
            return expression;
        }
        ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
        function parenthesizeConditionalTypeMember(member) {
            return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
        }
        ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
        function parenthesizeElementTypeMember(member) {
            switch (member.kind) {
                case 171 /* UnionType */:
                case 172 /* IntersectionType */:
                case 163 /* FunctionType */:
                case 164 /* ConstructorType */:
                    return ts.createParenthesizedType(member);
            }
            return parenthesizeConditionalTypeMember(member);
        }
        ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
        function parenthesizeArrayTypeMember(member) {
            switch (member.kind) {
                case 165 /* TypeQuery */:
                case 177 /* TypeOperator */:
                case 174 /* InferType */:
                    return ts.createParenthesizedType(member);
            }
            return parenthesizeElementTypeMember(member);
        }
        ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
        function parenthesizeElementTypeMembers(members) {
            return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
        }
        ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
        function parenthesizeTypeParameters(typeParameters) {
            if (ts.some(typeParameters)) {
                var params = [];
                for (var i = 0; i < typeParameters.length; ++i) {
                    var entry = typeParameters[i];
                    params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
                        ts.createParenthesizedType(entry) :
                        entry);
                }
                return ts.createNodeArray(params);
            }
        }
        ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
        function getLeftmostExpression(node, stopAtCallExpressions) {
            while (true) {
                switch (node.kind) {
                    case 201 /* PostfixUnaryExpression */:
                        node = node.operand;
                        continue;
                    case 202 /* BinaryExpression */:
                        node = node.left;
                        continue;
                    case 203 /* ConditionalExpression */:
                        node = node.condition;
                        continue;
                    case 191 /* TaggedTemplateExpression */:
                        node = node.tag;
                        continue;
                    case 189 /* CallExpression */:
                        if (stopAtCallExpressions) {
                            return node;
                        }
                    // falls through
                    case 210 /* AsExpression */:
                    case 188 /* ElementAccessExpression */:
                    case 187 /* PropertyAccessExpression */:
                    case 211 /* NonNullExpression */:
                    case 306 /* PartiallyEmittedExpression */:
                        node = node.expression;
                        continue;
                }
                return node;
            }
        }
        function parenthesizeConciseBody(body) {
            if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) {
                return ts.setTextRange(ts.createParen(body), body);
            }
            return body;
        }
        ts.parenthesizeConciseBody = parenthesizeConciseBody;
        function isCommaSequence(node) {
            return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ ||
                node.kind === 307 /* CommaListExpression */;
        }
        ts.isCommaSequence = isCommaSequence;
        var OuterExpressionKinds;
        (function (OuterExpressionKinds) {
            OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
            OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions";
            OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions";
            OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All";
        })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
        function isOuterExpression(node, kinds) {
            if (kinds === void 0) {
                kinds = 7 /* All */;
            }
            switch (node.kind) {
                case 193 /* ParenthesizedExpression */:
                    return (kinds & 1 /* Parentheses */) !== 0;
                case 192 /* TypeAssertionExpression */:
                case 210 /* AsExpression */:
                case 211 /* NonNullExpression */:
                    return (kinds & 2 /* Assertions */) !== 0;
                case 306 /* PartiallyEmittedExpression */:
                    return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
            }
            return false;
        }
        ts.isOuterExpression = isOuterExpression;
        function skipOuterExpressions(node, kinds) {
            if (kinds === void 0) {
                kinds = 7 /* All */;
            }
            var previousNode;
            do {
                previousNode = node;
                if (kinds & 1 /* Parentheses */) {
                    node = ts.skipParentheses(node);
                }
                if (kinds & 2 /* Assertions */) {
                    node = skipAssertions(node);
                }
                if (kinds & 4 /* PartiallyEmittedExpressions */) {
                    node = ts.skipPartiallyEmittedExpressions(node);
                }
            } while (previousNode !== node);
            return node;
        }
        ts.skipOuterExpressions = skipOuterExpressions;
        function skipAssertions(node) {
            while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) {
                node = node.expression;
            }
            return node;
        }
        ts.skipAssertions = skipAssertions;
        function updateOuterExpression(outerExpression, expression) {
            switch (outerExpression.kind) {
                case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
                case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
                case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
                case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
                case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
            }
        }
        /**
         * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
         *
         * A parenthesized expression can be ignored when all of the following are true:
         *
         * - It's `pos` and `end` are not -1
         * - It does not have a custom source map range
         * - It does not have a custom comment range
         * - It does not have synthetic leading or trailing comments
         *
         * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
         * the expression to maintain precedence, a new parenthesized expression should be created automatically when
         * the containing expression is created/updated.
         */
        function isIgnorableParen(node) {
            return node.kind === 193 /* ParenthesizedExpression */
                && ts.nodeIsSynthesized(node)
                && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
                && ts.nodeIsSynthesized(ts.getCommentRange(node))
                && !ts.some(ts.getSyntheticLeadingComments(node))
                && !ts.some(ts.getSyntheticTrailingComments(node));
        }
        function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
            if (kinds === void 0) {
                kinds = 7 /* All */;
            }
            if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
                return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
            }
            return innerExpression;
        }
        ts.recreateOuterExpressions = recreateOuterExpressions;
        function startOnNewLine(node) {
            return ts.setStartsOnNewLine(node, /*newLine*/ true);
        }
        ts.startOnNewLine = startOnNewLine;
        function getExternalHelpersModuleName(node) {
            var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
            var emitNode = parseNode && parseNode.emitNode;
            return emitNode && emitNode.externalHelpersModuleName;
        }
        ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
        function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
            if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
                var externalHelpersModuleName = getExternalHelpersModuleName(node);
                if (externalHelpersModuleName) {
                    return externalHelpersModuleName;
                }
                var moduleKind = ts.getEmitModuleKind(compilerOptions);
                var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
                    && moduleKind !== ts.ModuleKind.System
                    && moduleKind !== ts.ModuleKind.ES2015
                    && moduleKind !== ts.ModuleKind.ESNext;
                if (!create) {
                    var helpers = ts.getEmitHelpers(node);
                    if (helpers) {
                        for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
                            var helper = helpers_2[_i];
                            if (!helper.scoped) {
                                create = true;
                                break;
                            }
                        }
                    }
                }
                if (create) {
                    var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
                    var emitNode = ts.getOrCreateEmitNode(parseNode);
                    return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
                }
            }
        }
        ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
        /**
         * Get the name of that target module from an import or export declaration
         */
        function getLocalNameForExternalImport(node, sourceFile) {
            var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
            if (namespaceDeclaration && !ts.isDefaultImport(node)) {
                var name = namespaceDeclaration.name;
                return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
            }
            if (node.kind === 247 /* ImportDeclaration */ && node.importClause) {
                return ts.getGeneratedNameForNode(node);
            }
            if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) {
                return ts.getGeneratedNameForNode(node);
            }
            return undefined;
        }
        ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
        /**
         * Get the name of a target module from an import/export declaration as should be written in the emitted output.
         * The emitted output name can be different from the input if:
         *  1. The module has a /// <amd-module name="<new name>" />
         *  2. --out or --outFile is used, making the name relative to the rootDir
         *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
         * Otherwise, a new StringLiteral node representing the module name will be returned.
         */
        function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
            var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
            if (moduleName.kind === 9 /* StringLiteral */) {
                return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
                    || tryRenameExternalModule(moduleName, sourceFile)
                    || ts.getSynthesizedClone(moduleName);
            }
            return undefined;
        }
        ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
        /**
         * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
         * Here we check if alternative name was provided for a given moduleName and return it if possible.
         */
        function tryRenameExternalModule(moduleName, sourceFile) {
            var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
            return rename && ts.createLiteral(rename);
        }
        /**
         * Get the name of a module as should be written in the emitted output.
         * The emitted output name can be different from the input if:
         *  1. The module has a /// <amd-module name="<new name>" />
         *  2. --out or --outFile is used, making the name relative to the rootDir
         * Otherwise, a new StringLiteral node representing the module name will be returned.
         */
        function tryGetModuleNameFromFile(file, host, options) {
            if (!file) {
                return undefined;
            }
            if (file.moduleName) {
                return ts.createLiteral(file.moduleName);
            }
            if (!file.isDeclarationFile && (options.out || options.outFile)) {
                return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
            }
            return undefined;
        }
        ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
        function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
            return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
        }
        /**
         * Gets the initializer of an BindingOrAssignmentElement.
         */
        function getInitializerOfBindingOrAssignmentElement(bindingElement) {
            if (ts.isDeclarationBindingElement(bindingElement)) {
                // `1` in `let { a = 1 } = ...`
                // `1` in `let { a: b = 1 } = ...`
                // `1` in `let { a: {b} = 1 } = ...`
                // `1` in `let { a: [b] = 1 } = ...`
                // `1` in `let [a = 1] = ...`
                // `1` in `let [{a} = 1] = ...`
                // `1` in `let [[a] = 1] = ...`
                return bindingElement.initializer;
            }
            if (ts.isPropertyAssignment(bindingElement)) {
                // `1` in `({ a: b = 1 } = ...)`
                // `1` in `({ a: {b} = 1 } = ...)`
                // `1` in `({ a: [b] = 1 } = ...)`
                var initializer = bindingElement.initializer;
                return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
                    ? initializer.right
                    : undefined;
            }
            if (ts.isShorthandPropertyAssignment(bindingElement)) {
                // `1` in `({ a = 1 } = ...)`
                return bindingElement.objectAssignmentInitializer;
            }
            if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
                // `1` in `[a = 1] = ...`
                // `1` in `[{a} = 1] = ...`
                // `1` in `[[a] = 1] = ...`
                return bindingElement.right;
            }
            if (ts.isSpreadElement(bindingElement)) {
                // Recovery consistent with existing emit.
                return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
            }
        }
        ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
        /**
         * Gets the name of an BindingOrAssignmentElement.
         */
        function getTargetOfBindingOrAssignmentElement(bindingElement) {
            if (ts.isDeclarationBindingElement(bindingElement)) {
                // `a` in `let { a } = ...`
                // `a` in `let { a = 1 } = ...`
                // `b` in `let { a: b } = ...`
                // `b` in `let { a: b = 1 } = ...`
                // `a` in `let { ...a } = ...`
                // `{b}` in `let { a: {b} } = ...`
                // `{b}` in `let { a: {b} = 1 } = ...`
                // `[b]` in `let { a: [b] } = ...`
                // `[b]` in `let { a: [b] = 1 } = ...`
                // `a` in `let [a] = ...`
                // `a` in `let [a = 1] = ...`
                // `a` in `let [...a] = ...`
                // `{a}` in `let [{a}] = ...`
                // `{a}` in `let [{a} = 1] = ...`
                // `[a]` in `let [[a]] = ...`
                // `[a]` in `let [[a] = 1] = ...`
                return bindingElement.name;
            }
            if (ts.isObjectLiteralElementLike(bindingElement)) {
                switch (bindingElement.kind) {
                    case 273 /* PropertyAssignment */:
                        // `b` in `({ a: b } = ...)`
                        // `b` in `({ a: b = 1 } = ...)`
                        // `{b}` in `({ a: {b} } = ...)`
                        // `{b}` in `({ a: {b} = 1 } = ...)`
                        // `[b]` in `({ a: [b] } = ...)`
                        // `[b]` in `({ a: [b] = 1 } = ...)`
                        // `b.c` in `({ a: b.c } = ...)`
                        // `b.c` in `({ a: b.c = 1 } = ...)`
                        // `b[0]` in `({ a: b[0] } = ...)`
                        // `b[0]` in `({ a: b[0] = 1 } = ...)`
                        return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
                    case 274 /* ShorthandPropertyAssignment */:
                        // `a` in `({ a } = ...)`
                        // `a` in `({ a = 1 } = ...)`
                        return bindingElement.name;
                    case 275 /* SpreadAssignment */:
                        // `a` in `({ ...a } = ...)`
                        return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
                }
                // no target
                return undefined;
            }
            if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
                // `a` in `[a = 1] = ...`
                // `{a}` in `[{a} = 1] = ...`
                // `[a]` in `[[a] = 1] = ...`
                // `a.b` in `[a.b = 1] = ...`
                // `a[0]` in `[a[0] = 1] = ...`
                return getTargetOfBindingOrAssignmentElement(bindingElement.left);
            }
            if (ts.isSpreadElement(bindingElement)) {
                // `a` in `[...a] = ...`
                return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
            }
            // `a` in `[a] = ...`
            // `{a}` in `[{a}] = ...`
            // `[a]` in `[[a]] = ...`
            // `a.b` in `[a.b] = ...`
            // `a[0]` in `[a[0]] = ...`
            return bindingElement;
        }
        ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
        /**
         * Determines whether an BindingOrAssignmentElement is a rest element.
         */
        function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
            switch (bindingElement.kind) {
                case 149 /* Parameter */:
                case 184 /* BindingElement */:
                    // `...` in `let [...a] = ...`
                    return bindingElement.dotDotDotToken;
                case 206 /* SpreadElement */:
                case 275 /* SpreadAssignment */:
                    // `...` in `[...a] = ...`
                    return bindingElement;
            }
            return undefined;
        }
        ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
        /**
         * Gets the property name of a BindingOrAssignmentElement
         */
        function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
            switch (bindingElement.kind) {
                case 184 /* BindingElement */:
                    // `a` in `let { a: b } = ...`
                    // `[a]` in `let { [a]: b } = ...`
                    // `"a"` in `let { "a": b } = ...`
                    // `1` in `let { 1: b } = ...`
                    if (bindingElement.propertyName) {
                        var propertyName = bindingElement.propertyName;
                        return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
                            ? propertyName.expression
                            : propertyName;
                    }
                    break;
                case 273 /* PropertyAssignment */:
                    // `a` in `({ a: b } = ...)`
                    // `[a]` in `({ [a]: b } = ...)`
                    // `"a"` in `({ "a": b } = ...)`
                    // `1` in `({ 1: b } = ...)`
                    if (bindingElement.name) {
                        var propertyName = bindingElement.name;
                        return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
                            ? propertyName.expression
                            : propertyName;
                    }
                    break;
                case 275 /* SpreadAssignment */:
                    // `a` in `({ ...a } = ...)`
                    return bindingElement.name;
            }
            var target = getTargetOfBindingOrAssignmentElement(bindingElement);
            if (target && ts.isPropertyName(target)) {
                return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression)
                    ? target.expression
                    : target;
            }
            ts.Debug.fail("Invalid property name for binding element.");
        }
        ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
        function isStringOrNumericLiteral(node) {
            var kind = node.kind;
            return kind === 9 /* StringLiteral */
                || kind === 8 /* NumericLiteral */;
        }
        /**
         * Gets the elements of a BindingOrAssignmentPattern
         */
        function getElementsOfBindingOrAssignmentPattern(name) {
            switch (name.kind) {
                case 182 /* ObjectBindingPattern */:
                case 183 /* ArrayBindingPattern */:
                case 185 /* ArrayLiteralExpression */:
                    // `a` in `{a}`
                    // `a` in `[a]`
                    return name.elements;
                case 186 /* ObjectLiteralExpression */:
                    // `a` in `{a}`
                    return name.properties;
            }
        }
        ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
        function convertToArrayAssignmentElement(element) {
            if (ts.isBindingElement(element)) {
                if (element.dotDotDotToken) {
                    ts.Debug.assertNode(element.name, ts.isIdentifier);
                    return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
                }
                var expression = convertToAssignmentElementTarget(element.name);
                return element.initializer
                    ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
                    : expression;
            }
            ts.Debug.assertNode(element, ts.isExpression);
            return element;
        }
        ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
        function convertToObjectAssignmentElement(element) {
            if (ts.isBindingElement(element)) {
                if (element.dotDotDotToken) {
                    ts.Debug.assertNode(element.name, ts.isIdentifier);
                    return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
                }
                if (element.propertyName) {
                    var expression = convertToAssignmentElementTarget(element.name);
                    return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
                }
                ts.Debug.assertNode(element.name, ts.isIdentifier);
                return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
            }
            ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
            return element;
        }
        ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
        function convertToAssignmentPattern(node) {
            switch (node.kind) {
                case 183 /* ArrayBindingPattern */:
                case 185 /* ArrayLiteralExpression */:
                    return convertToArrayAssignmentPattern(node);
                case 182 /* ObjectBindingPattern */:
                case 186 /* ObjectLiteralExpression */:
                    return convertToObjectAssignmentPattern(node);
            }
        }
        ts.convertToAssignmentPattern = convertToAssignmentPattern;
        function convertToObjectAssignmentPattern(node) {
            if (ts.isObjectBindingPattern(node)) {
                return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
            }
            ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
            return node;
        }
        ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
        function convertToArrayAssignmentPattern(node) {
            if (ts.isArrayBindingPattern(node)) {
                return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
            }
            ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
            return node;
        }
        ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
        function convertToAssignmentElementTarget(node) {
            if (ts.isBindingPattern(node)) {
                return convertToAssignmentPattern(node);
            }
            ts.Debug.assertNode(node, ts.isExpression);
            return node;
        }
        ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
        function visitNode(node, visitor, test, lift) {
            if (node === undefined || visitor === undefined) {
                return node;
            }
            ts.aggregateTransformFlags(node);
            var visited = visitor(node);
            if (visited === node) {
                return node;
            }
            var visitedNode;
            if (visited === undefined) {
                return undefined;
            }
            else if (ts.isArray(visited)) {
                visitedNode = (lift || extractSingleNode)(visited);
            }
            else {
                visitedNode = visited;
            }
            ts.Debug.assertNode(visitedNode, test);
            ts.aggregateTransformFlags(visitedNode);
            return visitedNode;
        }
        ts.visitNode = visitNode;
        /**
         * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
         *
         * @param nodes The NodeArray to visit.
         * @param visitor The callback used to visit a Node.
         * @param test A node test to execute for each node.
         * @param start An optional value indicating the starting offset at which to start visiting.
         * @param count An optional value indicating the maximum number of nodes to visit.
         */
        function visitNodes(nodes, visitor, test, start, count) {
            if (nodes === undefined || visitor === undefined) {
                return nodes;
            }
            var updated;
            // Ensure start and count have valid values
            var length = nodes.length;
            if (start === undefined || start < 0) {
                start = 0;
            }
            if (count === undefined || count > length - start) {
                count = length - start;
            }
            if (start > 0 || count < length) {
                // If we are not visiting all of the original nodes, we must always create a new array.
                // Since this is a fragment of a node array, we do not copy over the previous location
                // and will only copy over `hasTrailingComma` if we are including the last element.
                updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
            }
            // Visit each original node.
            for (var i = 0; i < count; i++) {
                var node = nodes[i + start];
                ts.aggregateTransformFlags(node);
                var visited = node !== undefined ? visitor(node) : undefined;
                if (updated !== undefined || visited === undefined || visited !== node) {
                    if (updated === undefined) {
                        // Ensure we have a copy of `nodes`, up to the current index.
                        updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
                        ts.setTextRange(updated, nodes);
                    }
                    if (visited) {
                        if (ts.isArray(visited)) {
                            for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
                                var visitedNode = visited_1[_i];
                                ts.Debug.assertNode(visitedNode, test);
                                ts.aggregateTransformFlags(visitedNode);
                                updated.push(visitedNode);
                            }
                        }
                        else {
                            ts.Debug.assertNode(visited, test);
                            ts.aggregateTransformFlags(visited);
                            updated.push(visited);
                        }
                    }
                }
            }
            return updated || nodes;
        }
        ts.visitNodes = visitNodes;
        /**
         * Starts a new lexical environment and visits a statement list, ending the lexical environment
         * and merging hoisted declarations upon completion.
         */
        function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
            context.startLexicalEnvironment();
            statements = visitNodes(statements, visitor, ts.isStatement, start);
            if (ensureUseStrict && !ts.startsWithUseStrict(statements)) {
                statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements);
            }
            var declarations = context.endLexicalEnvironment();
            return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements);
        }
        ts.visitLexicalEnvironment = visitLexicalEnvironment;
        /**
         * Starts a new lexical environment and visits a parameter list, suspending the lexical
         * environment upon completion.
         */
        function visitParameterList(nodes, visitor, context, nodesVisitor) {
            if (nodesVisitor === void 0) {
                nodesVisitor = visitNodes;
            }
            context.startLexicalEnvironment();
            var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
            context.suspendLexicalEnvironment();
            return updated;
        }
        ts.visitParameterList = visitParameterList;
        function visitFunctionBody(node, visitor, context) {
            context.resumeLexicalEnvironment();
            var updated = visitNode(node, visitor, ts.isConciseBody);
            var declarations = context.endLexicalEnvironment();
            if (ts.some(declarations)) {
                var block = ts.convertToFunctionBody(updated);
                var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
                return ts.updateBlock(block, statements);
            }
            return updated;
        }
        ts.visitFunctionBody = visitFunctionBody;
        function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
            if (nodesVisitor === void 0) {
                nodesVisitor = visitNodes;
            }
            if (node === undefined) {
                return undefined;
            }
            var kind = node.kind;
            // No need to visit nodes with no children.
            if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) {
                return node;
            }
            switch (kind) {
                // Names
                case 71 /* Identifier */:
                    return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
                case 146 /* QualifiedName */:
                    return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
                case 147 /* ComputedPropertyName */:
                    return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
                // Signature elements
                case 148 /* TypeParameter */:
                    return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
                case 149 /* Parameter */:
                    return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
                case 150 /* Decorator */:
                    return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
                // Type elements
                case 151 /* PropertySignature */:
                    return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
                case 152 /* PropertyDeclaration */:
                    return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
                case 153 /* MethodSignature */:
                    return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken));
                case 154 /* MethodDeclaration */:
                    return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
                case 155 /* Constructor */:
                    return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
                case 156 /* GetAccessor */:
                    return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
                case 157 /* SetAccessor */:
                    return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
                case 158 /* CallSignature */:
                    return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
                case 159 /* ConstructSignature */:
                    return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
                case 160 /* IndexSignature */:
                    return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
                // Types
                case 161 /* TypePredicate */:
                    return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
                case 162 /* TypeReference */:
                    return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
                case 163 /* FunctionType */:
                    return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
                case 164 /* ConstructorType */:
                    return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
                case 165 /* TypeQuery */:
                    return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
                case 166 /* TypeLiteral */:
                    return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
                case 167 /* ArrayType */:
                    return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
                case 168 /* TupleType */:
                    return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
                case 169 /* OptionalType */:
                    return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
                case 170 /* RestType */:
                    return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
                case 171 /* UnionType */:
                    return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
                case 172 /* IntersectionType */:
                    return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
                case 173 /* ConditionalType */:
                    return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode));
                case 174 /* InferType */:
                    return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
                case 181 /* ImportType */:
                    return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
                case 175 /* ParenthesizedType */:
                    return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
                case 177 /* TypeOperator */:
                    return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
                case 178 /* IndexedAccessType */:
                    return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
                case 179 /* MappedType */:
                    return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
                case 180 /* LiteralType */:
                    return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
                // Binding patterns
                case 182 /* ObjectBindingPattern */:
                    return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
                case 183 /* ArrayBindingPattern */:
                    return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
                case 184 /* BindingElement */:
                    return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression));
                // Expression
                case 185 /* ArrayLiteralExpression */:
                    return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
                case 186 /* ObjectLiteralExpression */:
                    return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
                case 187 /* PropertyAccessExpression */:
                    return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier));
                case 188 /* ElementAccessExpression */:
                    return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
                case 189 /* CallExpression */:
                    return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
                case 190 /* NewExpression */:
                    return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
                case 191 /* TaggedTemplateExpression */:
                    return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
                case 192 /* TypeAssertionExpression */:
                    return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
                case 193 /* ParenthesizedExpression */:
                    return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
                case 194 /* FunctionExpression */:
                    return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
                case 195 /* ArrowFunction */:
                    return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context));
                case 196 /* DeleteExpression */:
                    return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
                case 197 /* TypeOfExpression */:
                    return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
                case 198 /* VoidExpression */:
                    return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
                case 199 /* AwaitExpression */:
                    return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
                case 200 /* PrefixUnaryExpression */:
                    return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
                case 201 /* PostfixUnaryExpression */:
                    return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
                case 202 /* BinaryExpression */:
                    return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken));
                case 203 /* ConditionalExpression */:
                    return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression));
                case 204 /* TemplateExpression */:
                    return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
                case 205 /* YieldExpression */:
                    return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
                case 206 /* SpreadElement */:
                    return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
                case 207 /* ClassExpression */:
                    return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
                case 209 /* ExpressionWithTypeArguments */:
                    return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
                case 210 /* AsExpression */:
                    return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
                case 211 /* NonNullExpression */:
                    return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
                case 212 /* MetaProperty */:
                    return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
                // Misc
                case 214 /* TemplateSpan */:
                    return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
                // Element
                case 216 /* Block */:
                    return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
                case 217 /* VariableStatement */:
                    return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
                case 219 /* ExpressionStatement */:
                    return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
                case 220 /* IfStatement */:
                    return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock));
                case 221 /* DoStatement */:
                    return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
                case 222 /* WhileStatement */:
                    return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                case 223 /* ForStatement */:
                    return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                case 224 /* ForInStatement */:
                    return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                case 225 /* ForOfStatement */:
                    return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                case 226 /* ContinueStatement */:
                    return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
                case 227 /* BreakStatement */:
                    return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
                case 228 /* ReturnStatement */:
                    return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
                case 229 /* WithStatement */:
                    return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                case 230 /* SwitchStatement */:
                    return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
                case 231 /* LabeledStatement */:
                    return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                case 232 /* ThrowStatement */:
                    return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
                case 233 /* TryStatement */:
                    return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
                case 235 /* VariableDeclaration */:
                    return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
                case 236 /* VariableDeclarationList */:
                    return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
                case 237 /* FunctionDeclaration */:
                    return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
                case 238 /* ClassDeclaration */:
                    return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
                case 239 /* InterfaceDeclaration */:
                    return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement));
                case 240 /* TypeAliasDeclaration */:
                    return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
                case 241 /* EnumDeclaration */:
                    return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
                case 242 /* ModuleDeclaration */:
                    return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody));
                case 243 /* ModuleBlock */:
                    return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
                case 244 /* CaseBlock */:
                    return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
                case 245 /* NamespaceExportDeclaration */:
                    return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
                case 246 /* ImportEqualsDeclaration */:
                    return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference));
                case 247 /* ImportDeclaration */:
                    return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
                case 248 /* ImportClause */:
                    return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings));
                case 249 /* NamespaceImport */:
                    return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
                case 250 /* NamedImports */:
                    return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
                case 251 /* ImportSpecifier */:
                    return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
                case 252 /* ExportAssignment */:
                    return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
                case 253 /* ExportDeclaration */:
                    return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
                case 254 /* NamedExports */:
                    return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
                case 255 /* ExportSpecifier */:
                    return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
                // Module references
                case 257 /* ExternalModuleReference */:
                    return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
                // JSX
                case 258 /* JsxElement */:
                    return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
                case 259 /* JsxSelfClosingElement */:
                    return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
                case 260 /* JsxOpeningElement */:
                    return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
                case 261 /* JsxClosingElement */:
                    return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
                case 262 /* JsxFragment */:
                    return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
                case 265 /* JsxAttribute */:
                    return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
                case 266 /* JsxAttributes */:
                    return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
                case 267 /* JsxSpreadAttribute */:
                    return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
                case 268 /* JsxExpression */:
                    return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
                // Clauses
                case 269 /* CaseClause */:
                    return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
                case 270 /* DefaultClause */:
                    return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
                case 271 /* HeritageClause */:
                    return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
                case 272 /* CatchClause */:
                    return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
                // Property assignments
                case 273 /* PropertyAssignment */:
                    return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
                case 274 /* ShorthandPropertyAssignment */:
                    return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
                case 275 /* SpreadAssignment */:
                    return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
                // Enum
                case 276 /* EnumMember */:
                    return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
                // Top-level nodes
                case 277 /* SourceFile */:
                    return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
                // Transformation nodes
                case 306 /* PartiallyEmittedExpression */:
                    return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
                case 307 /* CommaListExpression */:
                    return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
                default:
                    // No need to visit nodes with no children.
                    return node;
            }
        }
        ts.visitEachChild = visitEachChild;
        /**
         * Extracts the single node from a NodeArray.
         *
         * @param nodes The NodeArray.
         */
        function extractSingleNode(nodes) {
            ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
            return ts.singleOrUndefined(nodes);
        }
    })(ts || (ts = {}));
    /* @internal */
    (function (ts) {
        function reduceNode(node, f, initial) {
            return node ? f(initial, node) : initial;
        }
        function reduceNodeArray(nodes, f, initial) {
            return nodes ? f(initial, nodes) : initial;
        }
        /**
         * Similar to `reduceLeft`, performs a reduction against each child of a node.
         * NOTE: Unlike `forEachChild`, this does *not* visit every node.
         *
         * @param node The node containing the children to reduce.
         * @param initial The initial value to supply to the reduction.
         * @param f The callback function
         */
        function reduceEachChild(node, initial, cbNode, cbNodeArray) {
            if (node === undefined) {
                return initial;
            }
            var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
            var cbNodes = cbNodeArray || cbNode;
            var kind = node.kind;
            // No need to visit nodes with no children.
            if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) {
                return initial;
            }
            // We do not yet support types.
            if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) {
                return initial;
            }
            var result = initial;
            switch (node.kind) {
                // Leaf nodes
                case 215 /* SemicolonClassElement */:
                case 218 /* EmptyStatement */:
                case 208 /* OmittedExpression */:
                case 234 /* DebuggerStatement */:
                case 305 /* NotEmittedStatement */:
                    // No need to visit nodes with no children.
                    break;
                // Names
                case 146 /* QualifiedName */:
                    result = reduceNode(node.left, cbNode, result);
                    result = reduceNode(node.right, cbNode, result);
                    break;
                case 147 /* ComputedPropertyName */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                // Signature elements
                case 149 /* Parameter */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                case 150 /* Decorator */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                // Type member
                case 151 /* PropertySignature */:
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.questionToken, cbNode, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                case 152 /* PropertyDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                case 154 /* MethodDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.typeParameters, cbNodes, result);
                    result = reduceNodes(node.parameters, cbNodes, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                case 155 /* Constructor */:
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNodes(node.parameters, cbNodes, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                case 156 /* GetAccessor */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.parameters, cbNodes, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                case 157 /* SetAccessor */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.parameters, cbNodes, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                // Binding patterns
                case 182 /* ObjectBindingPattern */:
                case 183 /* ArrayBindingPattern */:
                    result = reduceNodes(node.elements, cbNodes, result);
                    break;
                case 184 /* BindingElement */:
                    result = reduceNode(node.propertyName, cbNode, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                // Expression
                case 185 /* ArrayLiteralExpression */:
                    result = reduceNodes(node.elements, cbNodes, result);
                    break;
                case 186 /* ObjectLiteralExpression */:
                    result = reduceNodes(node.properties, cbNodes, result);
                    break;
                case 187 /* PropertyAccessExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.name, cbNode, result);
                    break;
                case 188 /* ElementAccessExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.argumentExpression, cbNode, result);
                    break;
                case 189 /* CallExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNodes(node.typeArguments, cbNodes, result);
                    result = reduceNodes(node.arguments, cbNodes, result);
                    break;
                case 190 /* NewExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNodes(node.typeArguments, cbNodes, result);
                    result = reduceNodes(node.arguments, cbNodes, result);
                    break;
                case 191 /* TaggedTemplateExpression */:
                    result = reduceNode(node.tag, cbNode, result);
                    result = reduceNode(node.template, cbNode, result);
                    break;
                case 192 /* TypeAssertionExpression */:
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 194 /* FunctionExpression */:
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.typeParameters, cbNodes, result);
                    result = reduceNodes(node.parameters, cbNodes, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                case 195 /* ArrowFunction */:
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNodes(node.typeParameters, cbNodes, result);
                    result = reduceNodes(node.parameters, cbNodes, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                case 193 /* ParenthesizedExpression */:
                case 196 /* DeleteExpression */:
                case 197 /* TypeOfExpression */:
                case 198 /* VoidExpression */:
                case 199 /* AwaitExpression */:
                case 205 /* YieldExpression */:
                case 206 /* SpreadElement */:
                case 211 /* NonNullExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 200 /* PrefixUnaryExpression */:
                case 201 /* PostfixUnaryExpression */:
                    result = reduceNode(node.operand, cbNode, result);
                    break;
                case 202 /* BinaryExpression */:
                    result = reduceNode(node.left, cbNode, result);
                    result = reduceNode(node.right, cbNode, result);
                    break;
                case 203 /* ConditionalExpression */:
                    result = reduceNode(node.condition, cbNode, result);
                    result = reduceNode(node.whenTrue, cbNode, result);
                    result = reduceNode(node.whenFalse, cbNode, result);
                    break;
                case 204 /* TemplateExpression */:
                    result = reduceNode(node.head, cbNode, result);
                    result = reduceNodes(node.templateSpans, cbNodes, result);
                    break;
                case 207 /* ClassExpression */:
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.typeParameters, cbNodes, result);
                    result = reduceNodes(node.heritageClauses, cbNodes, result);
                    result = reduceNodes(node.members, cbNodes, result);
                    break;
                case 209 /* ExpressionWithTypeArguments */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNodes(node.typeArguments, cbNodes, result);
                    break;
                case 210 /* AsExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.type, cbNode, result);
                    break;
                // Misc
                case 214 /* TemplateSpan */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.literal, cbNode, result);
                    break;
                // Element
                case 216 /* Block */:
                    result = reduceNodes(node.statements, cbNodes, result);
                    break;
                case 217 /* VariableStatement */:
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.declarationList, cbNode, result);
                    break;
                case 219 /* ExpressionStatement */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 220 /* IfStatement */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.thenStatement, cbNode, result);
                    result = reduceNode(node.elseStatement, cbNode, result);
                    break;
                case 221 /* DoStatement */:
                    result = reduceNode(node.statement, cbNode, result);
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 222 /* WhileStatement */:
                case 229 /* WithStatement */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.statement, cbNode, result);
                    break;
                case 223 /* ForStatement */:
                    result = reduceNode(node.initializer, cbNode, result);
                    result = reduceNode(node.condition, cbNode, result);
                    result = reduceNode(node.incrementor, cbNode, result);
                    result = reduceNode(node.statement, cbNode, result);
                    break;
                case 224 /* ForInStatement */:
                case 225 /* ForOfStatement */:
                    result = reduceNode(node.initializer, cbNode, result);
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.statement, cbNode, result);
                    break;
                case 228 /* ReturnStatement */:
                case 232 /* ThrowStatement */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 230 /* SwitchStatement */:
                    result = reduceNode(node.expression, cbNode, result);
                    result = reduceNode(node.caseBlock, cbNode, result);
                    break;
                case 231 /* LabeledStatement */:
                    result = reduceNode(node.label, cbNode, result);
                    result = reduceNode(node.statement, cbNode, result);
                    break;
                case 233 /* TryStatement */:
                    result = reduceNode(node.tryBlock, cbNode, result);
                    result = reduceNode(node.catchClause, cbNode, result);
                    result = reduceNode(node.finallyBlock, cbNode, result);
                    break;
                case 235 /* VariableDeclaration */:
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                case 236 /* VariableDeclarationList */:
                    result = reduceNodes(node.declarations, cbNodes, result);
                    break;
                case 237 /* FunctionDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.typeParameters, cbNodes, result);
                    result = reduceNodes(node.parameters, cbNodes, result);
                    result = reduceNode(node.type, cbNode, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                case 238 /* ClassDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.typeParameters, cbNodes, result);
                    result = reduceNodes(node.heritageClauses, cbNodes, result);
                    result = reduceNodes(node.members, cbNodes, result);
                    break;
                case 241 /* EnumDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNodes(node.members, cbNodes, result);
                    break;
                case 242 /* ModuleDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.body, cbNode, result);
                    break;
                case 243 /* ModuleBlock */:
                    result = reduceNodes(node.statements, cbNodes, result);
                    break;
                case 244 /* CaseBlock */:
                    result = reduceNodes(node.clauses, cbNodes, result);
                    break;
                case 246 /* ImportEqualsDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.moduleReference, cbNode, result);
                    break;
                case 247 /* ImportDeclaration */:
                    result = reduceNodes(node.decorators, cbNodes, result);
                    result = reduceNodes(node.modifiers, cbNodes, result);
                    result = reduceNode(node.importClause, cbNode, result);
                    result = reduceNode(node.moduleSpecifier, cbNode, result);
                    break;
                case 248 /* ImportClause */:
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.namedBindings, cbNode, result);
                    break;
                case 249 /* NamespaceImport */:
                    result = reduceNode(node.name, cbNode, result);
                    break;
                case 250 /* NamedImports */:
                case 254 /* NamedExports */:
                    result = reduceNodes(node.elements, cbNodes, result);
                    break;
                case 251 /* ImportSpecifier */:
                case 255 /* ExportSpecifier */:
                    result = reduceNode(node.propertyName, cbNode, result);
                    result = reduceNode(node.name, cbNode, result);
                    break;
                case 252 /* ExportAssignment */:
                    result = ts.reduceLeft(node.decorators, cbNode, result);
                    result = ts.reduceLeft(node.modifiers, cbNode, result);
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 253 /* ExportDeclaration */:
                    result = ts.reduceLeft(node.decorators, cbNode, result);
                    result = ts.reduceLeft(node.modifiers, cbNode, result);
                    result = reduceNode(node.exportClause, cbNode, result);
                    result = reduceNode(node.moduleSpecifier, cbNode, result);
                    break;
                // Module references
                case 257 /* ExternalModuleReference */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                // JSX
                case 258 /* JsxElement */:
                    result = reduceNode(node.openingElement, cbNode, result);
                    result = ts.reduceLeft(node.children, cbNode, result);
                    result = reduceNode(node.closingElement, cbNode, result);
                    break;
                case 262 /* JsxFragment */:
                    result = reduceNode(node.openingFragment, cbNode, result);
                    result = ts.reduceLeft(node.children, cbNode, result);
                    result = reduceNode(node.closingFragment, cbNode, result);
                    break;
                case 259 /* JsxSelfClosingElement */:
                case 260 /* JsxOpeningElement */:
                    result = reduceNode(node.tagName, cbNode, result);
                    result = reduceNode(node.attributes, cbNode, result);
                    break;
                case 266 /* JsxAttributes */:
                    result = reduceNodes(node.properties, cbNodes, result);
                    break;
                case 261 /* JsxClosingElement */:
                    result = reduceNode(node.tagName, cbNode, result);
                    break;
                case 265 /* JsxAttribute */:
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                case 267 /* JsxSpreadAttribute */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 268 /* JsxExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                // Clauses
                case 269 /* CaseClause */:
                    result = reduceNode(node.expression, cbNode, result);
                // falls through
                case 270 /* DefaultClause */:
                    result = reduceNodes(node.statements, cbNodes, result);
                    break;
                case 271 /* HeritageClause */:
                    result = reduceNodes(node.types, cbNodes, result);
                    break;
                case 272 /* CatchClause */:
                    result = reduceNode(node.variableDeclaration, cbNode, result);
                    result = reduceNode(node.block, cbNode, result);
                    break;
                // Property assignments
                case 273 /* PropertyAssignment */:
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                case 274 /* ShorthandPropertyAssignment */:
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
                    break;
                case 275 /* SpreadAssignment */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                // Enum
                case 276 /* EnumMember */:
                    result = reduceNode(node.name, cbNode, result);
                    result = reduceNode(node.initializer, cbNode, result);
                    break;
                // Top-level nodes
                case 277 /* SourceFile */:
                    result = reduceNodes(node.statements, cbNodes, result);
                    break;
                // Transformation nodes
                case 306 /* PartiallyEmittedExpression */:
                    result = reduceNode(node.expression, cbNode, result);
                    break;
                case 307 /* CommaListExpression */:
                    result = reduceNodes(node.elements, cbNodes, result);
                    break;
                default:
                    break;
            }
            return result;
        }
        ts.reduceEachChild = reduceEachChild;
        function mergeLexicalEnvironment(statements, declarations) {
            if (!ts.some(declarations)) {
                return statements;
            }
            return ts.isNodeArray(statements)
                ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
                : ts.addStatementsAfterPrologue(statements, declarations);
        }
        ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
        /**
         * Lifts a NodeArray containing only Statement nodes to a block.
         *
         * @param nodes The NodeArray.
         */
        function liftToBlock(nodes) {
            Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
            return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
        }
        ts.liftToBlock = liftToBlock;
        /**
         * Aggregates the TransformFlags for a Node and its subtree.
         */
        function aggregateTransformFlags(node) {
            aggregateTransformFlagsForNode(node);
            return node;
        }
        ts.aggregateTransformFlags = aggregateTransformFlags;
        /**
         * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
         * computed first, then the transform flags for the current node are computed from the subtree
         * flags and the state of the current node. Finally, the transform flags of the node are
         * returned, excluding any flags that should not be included in its parent node's subtree
         * flags.
         */
        function aggregateTransformFlagsForNode(node) {
            if (node === undefined) {
                return 0 /* None */;
            }
            if (node.transformFlags & 536870912 /* HasComputedFlags */) {
                return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
            }
            var subtreeFlags = aggregateTransformFlagsForSubtree(node);
            return ts.computeTransformFlagsForNode(node, subtreeFlags);
        }
        function aggregateTransformFlagsForNodeArray(nodes) {
            if (nodes === undefined) {
                return 0 /* None */;
            }
            var subtreeFlags = 0 /* None */;
            var nodeArrayFlags = 0 /* None */;
            for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
                var node = nodes_3[_i];
                subtreeFlags |= aggregateTransformFlagsForNode(node);
                nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
            }
            nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
            return subtreeFlags;
        }
        /**
         * Aggregates the transform flags for the subtree of a node.
         */
        function aggregateTransformFlagsForSubtree(node) {
            // We do not transform ambient declarations or types, so there is no need to
            // recursively aggregate transform flags.
            if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) {
                return 0 /* None */;
            }
            // Aggregate the transform flags of each child.
            return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
        }
        /**
         * Aggregates the TransformFlags of a child node with the TransformFlags of its
         * siblings.
         */
        function aggregateTransformFlagsForChildNode(transformFlags, node) {
            return transformFlags | aggregateTransformFlagsForNode(node);
        }
        function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
            return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
        }
        var Debug;
        (function (Debug) {
            var isDebugInfoEnabled = false;
            function failBadSyntaxKind(node, message) {
                return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind);
            }
            Debug.failBadSyntaxKind = failBadSyntaxKind;
            Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */)
                ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); }
                : ts.noop;
            Debug.assertNode = Debug.shouldAssert(1 /* Normal */)
                ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); }
                : ts.noop;
            Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */)
                ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); }
                : ts.noop;
            Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */)
                ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); }
                : ts.noop;
            Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */)
                ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); }
                : ts.noop;
            /**
             * Injects debug information into frequently used types.
             */
            function enableDebugInfo() {
                if (isDebugInfoEnabled)
                    return;
                // Add additional properties in debug mode to assist with debugging.
                Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
                    __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } }
                });
                Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
                    __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } },
                    __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } },
                    __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
                });
                var nodeConstructors = [
                    ts.objectAllocator.getNodeConstructor(),
                    ts.objectAllocator.getIdentifierConstructor(),
                    ts.objectAllocator.getTokenConstructor(),
                    ts.objectAllocator.getSourceFileConstructor()
                ];
                for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
                    var ctor = nodeConstructors_1[_i];
                    if (!ctor.prototype.hasOwnProperty("__debugKind")) {
                        Object.defineProperties(ctor.prototype, {
                            __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } },
                            __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
                            __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } },
                            __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } },
                            __debugGetText: {
                                value: function (includeTrivia) {
                                    if (ts.nodeIsSynthesized(this))
                                        return "";
                                    var parseNode = ts.getParseTreeNode(this);
                                    var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
                                    return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
                                }
                            }
                        });
                    }
                }
                isDebugInfoEnabled = true;
            }
            Debug.enableDebugInfo = enableDebugInfo;
        })(Debug = ts.Debug || (ts.Debug = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function createSourceFileLikeCache(host) {
            var cached = ts.createMap();
            return {
                get: function (path) {
                    if (cached.has(path)) {
                        return cached.get(path);
                    }
                    if (!host.fileExists || !host.readFile || !host.fileExists(path))
                        return;
                    // And failing that, check the disk
                    var text = host.readFile(path); // TODO: GH#18217
                    var file = {
                        text: text,
                        lineMap: undefined,
                        getLineAndCharacterOfPosition: function (pos) {
                            return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos);
                        }
                    };
                    cached.set(path, file);
                    return file;
                }
            };
        }
        ts.createSourceFileLikeCache = createSourceFileLikeCache;
    })(ts || (ts = {}));
    /* @internal */
    (function (ts) {
        var sourcemaps;
        (function (sourcemaps) {
            sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity };
            function decode(host, mapPath, map, program, fallbackCache) {
                if (fallbackCache === void 0) {
                    fallbackCache = ts.createSourceFileLikeCache(host);
                }
                var currentDirectory = ts.getDirectoryPath(mapPath);
                var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory;
                var decodedMappings;
                var generatedOrderedMappings;
                var sourceOrderedMappings;
                return {
                    getOriginalPosition: getOriginalPosition,
                    getGeneratedPosition: getGeneratedPosition
                };
                function getGeneratedPosition(loc) {
                    var maps = getSourceOrderedMappings();
                    if (!ts.length(maps))
                        return loc;
                    var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions);
                    if (targetIndex < 0 && maps.length > 0) {
                        // if no exact match, closest is 2's compliment of result
                        targetIndex = ~targetIndex;
                    }
                    if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) {
                        return loc;
                    }
                    return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos
                }
                function getOriginalPosition(loc) {
                    var maps = getGeneratedOrderedMappings();
                    if (!ts.length(maps))
                        return loc;
                    var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions);
                    if (targetIndex < 0 && maps.length > 0) {
                        // if no exact match, closest is 2's compliment of result
                        targetIndex = ~targetIndex;
                    }
                    return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos
                }
                function getSourceFileLike(fileName, location) {
                    // Lookup file in program, if provided
                    var path = ts.toPath(fileName, location, host.getCanonicalFileName);
                    var file = program && program.getSourceFile(path);
                    // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file
                    if (!file || file.resolvedPath !== path) {
                        // Otherwise check the cache (which may hit disk)
                        return fallbackCache.get(path);
                    }
                    return file;
                }
                function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) {
                    var file = getSourceFileLike(fileName, directory);
                    if (!file) {
                        return -1;
                    }
                    return ts.getPositionOfLineAndCharacter(file, line, character);
                }
                function getDecodedMappings() {
                    return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host));
                }
                function getSourceOrderedMappings() {
                    return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions));
                }
                function getGeneratedOrderedMappings() {
                    return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions));
                }
                function compareProcessedPositionSourcePositions(a, b) {
                    return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) ||
                        ts.compareValues(a.sourcePosition, b.sourcePosition);
                }
                function compareProcessedPositionEmittedPositions(a, b) {
                    return ts.compareValues(a.emittedPosition, b.emittedPosition);
                }
                function processPosition(position) {
                    var sourcePath = map.sources[position.sourceIndex];
                    return {
                        emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn),
                        sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn),
                        sourcePath: sourcePath,
                    };
                }
            }
            sourcemaps.decode = decode;
            /*@internal*/
            function decodeMappings(map) {
                var state = {
                    encodedText: map.mappings,
                    currentNameIndex: undefined,
                    sourceMapNamesLength: map.names ? map.names.length : undefined,
                    currentEmittedColumn: 0,
                    currentEmittedLine: 0,
                    currentSourceColumn: 0,
                    currentSourceLine: 0,
                    currentSourceIndex: 0,
                    decodingIndex: 0
                };
                function captureSpan() {
                    return {
                        emittedColumn: state.currentEmittedColumn,
                        emittedLine: state.currentEmittedLine,
                        sourceColumn: state.currentSourceColumn,
                        sourceIndex: state.currentSourceIndex,
                        sourceLine: state.currentSourceLine,
                        nameIndex: state.currentNameIndex
                    };
                }
                return {
                    get decodingIndex() { return state.decodingIndex; },
                    get error() { return state.error; },
                    get lastSpan() { return captureSpan(); },
                    next: function () {
                        if (hasCompletedDecoding(state) || state.error)
                            return { done: true, value: undefined };
                        if (!decodeSinglePosition(state))
                            return { done: true, value: undefined };
                        return { done: false, value: captureSpan() };
                    }
                };
            }
            sourcemaps.decodeMappings = decodeMappings;
            function calculateDecodedMappings(map, processPosition, host) {
                var decoder = decodeMappings(map);
                var positions = ts.arrayFrom(decoder, processPosition);
                if (decoder.error) {
                    if (host && host.log) {
                        host.log("Encountered error while decoding sourcemap: " + decoder.error);
                    }
                    return [];
                }
                return positions;
            }
            function hasCompletedDecoding(state) {
                return state.decodingIndex === state.encodedText.length;
            }
            function decodeSinglePosition(state) {
                while (state.decodingIndex < state.encodedText.length) {
                    var char = state.encodedText.charCodeAt(state.decodingIndex);
                    if (char === 59 /* semicolon */) {
                        // New line
                        state.currentEmittedLine++;
                        state.currentEmittedColumn = 0;
                        state.decodingIndex++;
                        continue;
                    }
                    if (char === 44 /* comma */) {
                        // Next entry is on same line - no action needed
                        state.decodingIndex++;
                        continue;
                    }
                    // Read the current position
                    // 1. Column offset from prev read jsColumn
                    state.currentEmittedColumn += base64VLQFormatDecode();
                    // Incorrect emittedColumn dont support this map
                    if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) {
                        return false;
                    }
                    // Dont support reading mappings that dont have information about original source and its line numbers
                    if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) {
                        return false;
                    }
                    // 2. Relative sourceIndex
                    state.currentSourceIndex += base64VLQFormatDecode();
                    // Incorrect sourceIndex dont support this map
                    if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) {
                        return false;
                    }
                    // Dont support reading mappings that dont have information about original source position
                    if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) {
                        return false;
                    }
                    // 3. Relative sourceLine 0 based
                    state.currentSourceLine += base64VLQFormatDecode();
                    // Incorrect sourceLine dont support this map
                    if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) {
                        return false;
                    }
                    // Dont support reading mappings that dont have information about original source and its line numbers
                    if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) {
                        return false;
                    }
                    // 4. Relative sourceColumn 0 based
                    state.currentSourceColumn += base64VLQFormatDecode();
                    // Incorrect sourceColumn dont support this map
                    if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) {
                        return false;
                    }
                    // 5. Check if there is name:
                    if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) {
                        if (state.currentNameIndex === undefined) {
                            state.currentNameIndex = 0;
                        }
                        state.currentNameIndex += base64VLQFormatDecode();
                        // Incorrect nameIndex dont support this map
                        // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap
                        // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) {
                        //    return;
                        // }
                    }
                    // Dont support reading mappings that dont have information about original source and its line numbers
                    if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) {
                        return false;
                    }
                    // Entry should be complete
                    return true;
                }
                createErrorIfCondition(/*condition*/ true, "No encoded entry found");
                return false;
                function createErrorIfCondition(condition, errormsg) {
                    if (state.error) {
                        // An error was already reported
                        return true;
                    }
                    if (condition) {
                        state.error = errormsg;
                    }
                    return condition;
                }
                function base64VLQFormatDecode() {
                    var moreDigits = true;
                    var shiftCount = 0;
                    var value = 0;
                    for (; moreDigits; state.decodingIndex++) {
                        if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) {
                            return undefined; // TODO: GH#18217
                        }
                        // 6 digit number
                        var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex));
                        // If msb is set, we still have more bits to continue
                        moreDigits = (currentByte & 32) !== 0;
                        // least significant 5 bits are the next msbs in the final value.
                        value = value | ((currentByte & 31) << shiftCount);
                        shiftCount += 5;
                    }
                    // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
                    if ((value & 1) === 0) {
                        // + number
                        value = value >> 1;
                    }
                    else {
                        // - number
                        value = value >> 1;
                        value = -value;
                    }
                    return value;
                }
            }
            function base64FormatDecode(char) {
                return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char);
            }
            function isSourceMappingSegmentEnd(encodedText, pos) {
                return (pos === encodedText.length ||
                    encodedText.charCodeAt(pos) === 44 /* comma */ ||
                    encodedText.charCodeAt(pos) === 59 /* semicolon */);
            }
        })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function getOriginalNodeId(node) {
            node = ts.getOriginalNode(node);
            return node ? ts.getNodeId(node) : 0;
        }
        ts.getOriginalNodeId = getOriginalNodeId;
        function containsDefaultReference(node) {
            if (!node)
                return false;
            if (!ts.isNamedImports(node))
                return false;
            return ts.some(node.elements, isNamedDefaultReference);
        }
        function isNamedDefaultReference(e) {
            return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
        }
        function chainBundle(transformSourceFile) {
            return transformSourceFileOrBundle;
            function transformSourceFileOrBundle(node) {
                return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
            }
            function transformBundle(node) {
                return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
            }
        }
        ts.chainBundle = chainBundle;
        function getImportNeedsImportStarHelper(node) {
            if (!!ts.getNamespaceDeclarationNode(node)) {
                return true;
            }
            var bindings = node.importClause && node.importClause.namedBindings;
            if (!bindings) {
                return false;
            }
            if (!ts.isNamedImports(bindings))
                return false;
            var defaultRefCount = 0;
            for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
                var binding = _a[_i];
                if (isNamedDefaultReference(binding)) {
                    defaultRefCount++;
                }
            }
            // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
            return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
        }
        ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
        function getImportNeedsImportDefaultHelper(node) {
            // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
            return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
        }
        ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
        function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
            var externalImports = [];
            var exportSpecifiers = ts.createMultiMap();
            var exportedBindings = [];
            var uniqueExports = ts.createMap();
            var exportedNames;
            var hasExportDefault = false;
            var exportEquals;
            var hasExportStarsToExportValues = false;
            var hasImportStarOrImportDefault = false;
            for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
                var node = _a[_i];
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                        // import "mod"
                        // import x from "mod"
                        // import * as x from "mod"
                        // import { x, y } from "mod"
                        externalImports.push(node);
                        hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node);
                        break;
                    case 246 /* ImportEqualsDeclaration */:
                        if (node.moduleReference.kind === 257 /* ExternalModuleReference */) {
                            // import x = require("mod")
                            externalImports.push(node);
                        }
                        break;
                    case 253 /* ExportDeclaration */:
                        if (node.moduleSpecifier) {
                            if (!node.exportClause) {
                                // export * from "mod"
                                externalImports.push(node);
                                hasExportStarsToExportValues = true;
                            }
                            else {
                                // export { x, y } from "mod"
                                externalImports.push(node);
                            }
                        }
                        else {
                            // export { x, y }
                            for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) {
                                var specifier = _c[_b];
                                if (!uniqueExports.get(ts.idText(specifier.name))) {
                                    var name = specifier.propertyName || specifier.name;
                                    exportSpecifiers.add(ts.idText(name), specifier);
                                    var decl = resolver.getReferencedImportDeclaration(name)
                                        || resolver.getReferencedValueDeclaration(name);
                                    if (decl) {
                                        multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
                                    }
                                    uniqueExports.set(ts.idText(specifier.name), true);
                                    exportedNames = ts.append(exportedNames, specifier.name);
                                }
                            }
                        }
                        break;
                    case 252 /* ExportAssignment */:
                        if (node.isExportEquals && !exportEquals) {
                            // export = x
                            exportEquals = node;
                        }
                        break;
                    case 217 /* VariableStatement */:
                        if (ts.hasModifier(node, 1 /* Export */)) {
                            for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
                                var decl = _e[_d];
                                exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
                            }
                        }
                        break;
                    case 237 /* FunctionDeclaration */:
                        if (ts.hasModifier(node, 1 /* Export */)) {
                            if (ts.hasModifier(node, 512 /* Default */)) {
                                // export default function() { }
                                if (!hasExportDefault) {
                                    multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
                                    hasExportDefault = true;
                                }
                            }
                            else {
                                // export function x() { }
                                var name = node.name;
                                if (!uniqueExports.get(ts.idText(name))) {
                                    multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
                                    uniqueExports.set(ts.idText(name), true);
                                    exportedNames = ts.append(exportedNames, name);
                                }
                            }
                        }
                        break;
                    case 238 /* ClassDeclaration */:
                        if (ts.hasModifier(node, 1 /* Export */)) {
                            if (ts.hasModifier(node, 512 /* Default */)) {
                                // export default class { }
                                if (!hasExportDefault) {
                                    multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
                                    hasExportDefault = true;
                                }
                            }
                            else {
                                // export class x { }
                                var name = node.name;
                                if (name && !uniqueExports.get(ts.idText(name))) {
                                    multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
                                    uniqueExports.set(ts.idText(name), true);
                                    exportedNames = ts.append(exportedNames, name);
                                }
                            }
                        }
                        break;
                }
            }
            var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault);
            var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(
            /*decorators*/ undefined, 
            /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText));
            if (externalHelpersImportDeclaration) {
                ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
                externalImports.unshift(externalHelpersImportDeclaration);
            }
            return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
        }
        ts.collectExternalModuleInfo = collectExternalModuleInfo;
        function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
            if (ts.isBindingPattern(decl.name)) {
                for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
                    var element = _a[_i];
                    if (!ts.isOmittedExpression(element)) {
                        exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
                    }
                }
            }
            else if (!ts.isGeneratedIdentifier(decl.name)) {
                var text = ts.idText(decl.name);
                if (!uniqueExports.get(text)) {
                    uniqueExports.set(text, true);
                    exportedNames = ts.append(exportedNames, decl.name);
                }
            }
            return exportedNames;
        }
        /** Use a sparse array as a multi-map. */
        function multiMapSparseArrayAdd(map, key, value) {
            var values = map[key];
            if (values) {
                values.push(value);
            }
            else {
                map[key] = values = [value];
            }
            return values;
        }
        /**
         * Used in the module transformer to check if an expression is reasonably without sideeffect,
         *  and thus better to copy into multiple places rather than to cache in a temporary variable
         *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
         */
        function isSimpleCopiableExpression(expression) {
            return ts.isStringLiteralLike(expression) ||
                expression.kind === 8 /* NumericLiteral */ ||
                ts.isKeyword(expression.kind) ||
                ts.isIdentifier(expression);
        }
        ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
        /**
         * @param input Template string input strings
         * @param args Names which need to be made file-level unique
         */
        function helperString(input) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            return function (uniqueName) {
                var result = "";
                for (var i = 0; i < args.length; i++) {
                    result += input[i];
                    result += uniqueName(args[i]);
                }
                result += input[input.length - 1];
                return result;
            };
        }
        ts.helperString = helperString;
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        var FlattenLevel;
        (function (FlattenLevel) {
            FlattenLevel[FlattenLevel["All"] = 0] = "All";
            FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
        })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
        /**
         * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
         *
         * @param node The node to flatten.
         * @param visitor An optional visitor used to visit initializers.
         * @param context The transformation context.
         * @param level Indicates the extent to which flattening should occur.
         * @param needsValue An optional value indicating whether the value from the right-hand-side of
         * the destructuring assignment is needed as part of a larger expression.
         * @param createAssignmentCallback An optional callback used to create the assignment expression.
         */
        function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
            var location = node;
            var value;
            if (ts.isDestructuringAssignment(node)) {
                value = node.right;
                while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
                    if (ts.isDestructuringAssignment(value)) {
                        location = node = value;
                        value = node.right;
                    }
                    else {
                        return ts.visitNode(value, visitor, ts.isExpression);
                    }
                }
            }
            var expressions;
            var flattenContext = {
                context: context,
                level: level,
                downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
                hoistTempVariables: true,
                emitExpression: emitExpression,
                emitBindingOrAssignment: emitBindingOrAssignment,
                createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
                createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
                createArrayBindingOrAssignmentElement: makeAssignmentElement,
                visitor: visitor
            };
            if (value) {
                value = ts.visitNode(value, visitor, ts.isExpression);
                if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) {
                    // If the right-hand value of the assignment is also an assignment target then
                    // we need to cache the right-hand value.
                    value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
                }
                else if (needsValue) {
                    // If the right-hand value of the destructuring assignment needs to be preserved (as
                    // is the case when the destructuring assignment is part of a larger expression),
                    // then we need to cache the right-hand value.
                    //
                    // The source map location for the assignment should point to the entire binary
                    // expression.
                    value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
                }
                else if (ts.nodeIsSynthesized(node)) {
                    // Generally, the source map location for a destructuring assignment is the root
                    // expression.
                    //
                    // However, if the root expression is synthesized (as in the case
                    // of the initializer when transforming a ForOfStatement), then the source map
                    // location should point to the right-hand value of the expression.
                    location = value;
                }
            }
            flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
            if (value && needsValue) {
                if (!ts.some(expressions)) {
                    return value;
                }
                expressions.push(value);
            }
            return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
            function emitExpression(expression) {
                // NOTE: this completely disables source maps, but aligns with the behavior of
                //       `emitAssignment` in the old emitter.
                ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */);
                ts.aggregateTransformFlags(expression);
                expressions = ts.append(expressions, expression);
            }
            function emitBindingOrAssignment(target, value, location, original) {
                ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
                var expression = createAssignmentCallback
                    ? createAssignmentCallback(target, value, location)
                    : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
                expression.original = original;
                emitExpression(expression);
            }
        }
        ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
        function bindingOrAssignmentElementAssignsToName(element, escapedName) {
            var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
            if (ts.isBindingOrAssignmentPattern(target)) {
                return bindingOrAssignmentPatternAssignsToName(target, escapedName);
            }
            else if (ts.isIdentifier(target)) {
                return target.escapedText === escapedName;
            }
            return false;
        }
        function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
            var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
            for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
                var element = elements_3[_i];
                if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
                    return true;
                }
            }
            return false;
        }
        /**
         * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
         *
         * @param node The node to flatten.
         * @param visitor An optional visitor used to visit initializers.
         * @param context The transformation context.
         * @param boundValue The value bound to the declaration.
         * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
         * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
         * @param level Indicates the extent to which flattening should occur.
         */
        function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
            if (hoistTempVariables === void 0) {
                hoistTempVariables = false;
            }
            var pendingExpressions;
            var pendingDeclarations = [];
            var declarations = [];
            var flattenContext = {
                context: context,
                level: level,
                downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
                hoistTempVariables: hoistTempVariables,
                emitExpression: emitExpression,
                emitBindingOrAssignment: emitBindingOrAssignment,
                createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
                createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
                createArrayBindingOrAssignmentElement: makeBindingElement,
                visitor: visitor
            };
            if (ts.isVariableDeclaration(node)) {
                var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
                if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) {
                    // If the right-hand value of the assignment is also an assignment target then
                    // we need to cache the right-hand value.
                    initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
                    node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
                }
            }
            flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
            if (pendingExpressions) {
                var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
                if (hoistTempVariables) {
                    var value = ts.inlineExpressions(pendingExpressions);
                    pendingExpressions = undefined;
                    emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
                }
                else {
                    context.hoistVariableDeclaration(temp);
                    var pendingDeclaration = ts.last(pendingDeclarations);
                    pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
                    ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
                    pendingDeclaration.value = temp;
                }
            }
            for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
                var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
                var variable = ts.createVariableDeclaration(name, 
                /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
                variable.original = original;
                ts.setTextRange(variable, location);
                if (ts.isIdentifier(name)) {
                    ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */);
                }
                ts.aggregateTransformFlags(variable);
                declarations.push(variable);
            }
            return declarations;
            function emitExpression(value) {
                pendingExpressions = ts.append(pendingExpressions, value);
            }
            function emitBindingOrAssignment(target, value, location, original) {
                ts.Debug.assertNode(target, ts.isBindingName);
                if (pendingExpressions) {
                    value = ts.inlineExpressions(ts.append(pendingExpressions, value));
                    pendingExpressions = undefined;
                }
                pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
            }
        }
        ts.flattenDestructuringBinding = flattenDestructuringBinding;
        /**
         * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
         *
         * @param flattenContext Options used to control flattening.
         * @param element The element to flatten.
         * @param value The current RHS value to assign to the element.
         * @param location The location to use for source maps and comments.
         * @param skipInitializer An optional value indicating whether to include the initializer
         * for the element.
         */
        function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
            if (!skipInitializer) {
                var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
                if (initializer) {
                    // Combine value and initializer
                    value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
                }
                else if (!value) {
                    // Use 'void 0' in absence of value and initializer
                    value = ts.createVoidZero();
                }
            }
            var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
            if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
                flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
            }
            else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
                flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
            }
            else {
                flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
            }
        }
        /**
         * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
         *
         * @param flattenContext Options used to control flattening.
         * @param parent The parent element of the pattern.
         * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
         * @param value The current RHS value to assign to the element.
         * @param location The location to use for source maps and comments.
         */
        function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
            var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
            var numElements = elements.length;
            if (numElements !== 1) {
                // For anything other than a single-element destructuring we need to generate a temporary
                // to ensure value is evaluated exactly once. Additionally, if we have zero elements
                // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
                // so in that case, we'll intentionally create that temporary.
                var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
                value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
            }
            var bindingElements;
            var computedTempVariables;
            for (var i = 0; i < numElements; i++) {
                var element = elements[i];
                if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
                    var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
                    if (flattenContext.level >= 1 /* ObjectRest */
                        && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */))
                        && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */))
                        && !ts.isComputedPropertyName(propertyName)) {
                        bindingElements = ts.append(bindingElements, element);
                    }
                    else {
                        if (bindingElements) {
                            flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
                            bindingElements = undefined;
                        }
                        var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
                        if (ts.isComputedPropertyName(propertyName)) {
                            computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
                        }
                        flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
                    }
                }
                else if (i === numElements - 1) {
                    if (bindingElements) {
                        flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
                        bindingElements = undefined;
                    }
                    var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
                    flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
                }
            }
            if (bindingElements) {
                flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
            }
        }
        /**
         * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
         *
         * @param flattenContext Options used to control flattening.
         * @param parent The parent element of the pattern.
         * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
         * @param value The current RHS value to assign to the element.
         * @param location The location to use for source maps and comments.
         */
        function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
            var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
            var numElements = elements.length;
            if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
                // Read the elements of the iterable into an array
                value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
                    ? undefined
                    : numElements, location), 
                /*reuseIdentifierExpressions*/ false, location);
            }
            else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
                || ts.every(elements, ts.isOmittedExpression)) {
                // For anything other than a single-element destructuring we need to generate a temporary
                // to ensure value is evaluated exactly once. Additionally, if we have zero elements
                // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
                // so in that case, we'll intentionally create that temporary.
                // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
                // then we will create temporary variable.
                var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
                value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
            }
            var bindingElements;
            var restContainingElements;
            for (var i = 0; i < numElements; i++) {
                var element = elements[i];
                if (flattenContext.level >= 1 /* ObjectRest */) {
                    // If an array pattern contains an ObjectRest, we must cache the result so that we
                    // can perform the ObjectRest destructuring in a different declaration
                    if (element.transformFlags & 1048576 /* ContainsObjectRest */) {
                        var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
                        if (flattenContext.hoistTempVariables) {
                            flattenContext.context.hoistVariableDeclaration(temp);
                        }
                        restContainingElements = ts.append(restContainingElements, [temp, element]);
                        bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
                    }
                    else {
                        bindingElements = ts.append(bindingElements, element);
                    }
                }
                else if (ts.isOmittedExpression(element)) {
                    continue;
                }
                else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
                    var rhsValue = ts.createElementAccess(value, i);
                    flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
                }
                else if (i === numElements - 1) {
                    var rhsValue = ts.createArraySlice(value, i);
                    flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
                }
            }
            if (bindingElements) {
                flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
            }
            if (restContainingElements) {
                for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
                    var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
                    flattenBindingOrAssignmentElement(flattenContext, element, id, element);
                }
            }
        }
        /**
         * Creates an expression used to provide a default value if a value is `undefined` at runtime.
         *
         * @param flattenContext Options used to control flattening.
         * @param value The RHS value to test.
         * @param defaultValue The default value to use if `value` is `undefined` at runtime.
         * @param location The location to use for source maps and comments.
         */
        function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
            value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
            return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
        }
        /**
         * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
         * right-hand side of a transformed destructuring assignment.
         *
         * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
         *
         * @param flattenContext Options used to control flattening.
         * @param value The RHS value that is the source of the property.
         * @param propertyName The destructuring property name.
         */
        function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
            if (ts.isComputedPropertyName(propertyName)) {
                var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
                return ts.createElementAccess(value, argumentExpression);
            }
            else if (ts.isStringOrNumericLiteralLike(propertyName)) {
                var argumentExpression = ts.getSynthesizedClone(propertyName);
                argumentExpression.text = argumentExpression.text;
                return ts.createElementAccess(value, argumentExpression);
            }
            else {
                var name = ts.createIdentifier(ts.idText(propertyName));
                return ts.createPropertyAccess(value, name);
            }
        }
        /**
         * Ensures that there exists a declared identifier whose value holds the given expression.
         * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
         * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
         *
         * @param flattenContext Options used to control flattening.
         * @param value the expression whose value needs to be bound.
         * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
         * false if it is necessary to always emit an identifier.
         * @param location The location to use for source maps and comments.
         */
        function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
            if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
                return value;
            }
            else {
                var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
                if (flattenContext.hoistTempVariables) {
                    flattenContext.context.hoistVariableDeclaration(temp);
                    flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
                }
                else {
                    flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
                }
                return temp;
            }
        }
        function makeArrayBindingPattern(elements) {
            ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
            return ts.createArrayBindingPattern(elements);
        }
        function makeArrayAssignmentPattern(elements) {
            return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
        }
        function makeObjectBindingPattern(elements) {
            ts.Debug.assertEachNode(elements, ts.isBindingElement);
            return ts.createObjectBindingPattern(elements);
        }
        function makeObjectAssignmentPattern(elements) {
            return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
        }
        function makeBindingElement(name) {
            return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
        }
        function makeAssignmentElement(name) {
            return name;
        }
        var restHelper = {
            name: "typescript:rest",
            scoped: false,
            text: "\n            var __rest = (this && this.__rest) || function (s, e) {\n                var t = {};\n                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n                    t[p] = s[p];\n                if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n                    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n                        t[p[i]] = s[p[i]];\n                return t;\n            };"
        };
        /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
         * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
         */
        function createRestCall(context, value, elements, computedTempVariables, location) {
            context.requestEmitHelper(restHelper);
            var propertyNames = [];
            var computedTempVariableOffset = 0;
            for (var i = 0; i < elements.length - 1; i++) {
                var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
                if (propertyName) {
                    if (ts.isComputedPropertyName(propertyName)) {
                        var temp = computedTempVariables[computedTempVariableOffset];
                        computedTempVariableOffset++;
                        // typeof _tmp === "symbol" ? _tmp : _tmp + ""
                        propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
                    }
                    else {
                        propertyNames.push(ts.createLiteral(propertyName));
                    }
                }
            }
            return ts.createCall(ts.getHelperName("__rest"), 
            /*typeArguments*/ undefined, [
                value,
                ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
            ]);
        }
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        /**
         * Indicates whether to emit type metadata in the new format.
         */
        var USE_NEW_TYPE_METADATA_FORMAT = false;
        var TypeScriptSubstitutionFlags;
        (function (TypeScriptSubstitutionFlags) {
            /** Enables substitutions for decorated classes. */
            TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
            /** Enables substitutions for namespace exports. */
            TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
            /* Enables substitutions for unqualified enum members */
            TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
        })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
        var ClassFacts;
        (function (ClassFacts) {
            ClassFacts[ClassFacts["None"] = 0] = "None";
            ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
            ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
            ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
            ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
            ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
            ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
            ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
            ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
            ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
            ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
            ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
            ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
        })(ClassFacts || (ClassFacts = {}));
        function transformTypeScript(context) {
            var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
            var resolver = context.getEmitResolver();
            var compilerOptions = context.getCompilerOptions();
            var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
            var languageVersion = ts.getEmitScriptTarget(compilerOptions);
            var moduleKind = ts.getEmitModuleKind(compilerOptions);
            // Save the previous transformation hooks.
            var previousOnEmitNode = context.onEmitNode;
            var previousOnSubstituteNode = context.onSubstituteNode;
            // Set new transformation hooks.
            context.onEmitNode = onEmitNode;
            context.onSubstituteNode = onSubstituteNode;
            // Enable substitution for property/element access to emit const enum values.
            context.enableSubstitution(187 /* PropertyAccessExpression */);
            context.enableSubstitution(188 /* ElementAccessExpression */);
            // These variables contain state that changes as we descend into the tree.
            var currentSourceFile;
            var currentNamespace;
            var currentNamespaceContainerName;
            var currentLexicalScope;
            var currentNameScope;
            var currentScopeFirstDeclarationsOfName;
            /**
             * Keeps track of whether expression substitution has been enabled for specific edge cases.
             * They are persisted between each SourceFile transformation and should not be reset.
             */
            var enabledSubstitutions;
            /**
             * A map that keeps track of aliases created for classes with decorators to avoid issues
             * with the double-binding behavior of classes.
             */
            var classAliases;
            /**
             * Keeps track of whether we are within any containing namespaces when performing
             * just-in-time substitution while printing an expression identifier.
             */
            var applicableSubstitutions;
            /**
             * Tracks what computed name expressions originating from elided names must be inlined
             * at the next execution site, in document order
             */
            var pendingExpressions;
            return transformSourceFileOrBundle;
            function transformSourceFileOrBundle(node) {
                if (node.kind === 278 /* Bundle */) {
                    return transformBundle(node);
                }
                return transformSourceFile(node);
            }
            function transformBundle(node) {
                return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
                    if (prepend.kind === 280 /* InputFiles */) {
                        return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText);
                    }
                    return prepend;
                }));
            }
            /**
             * Transform TypeScript-specific syntax in a SourceFile.
             *
             * @param node A SourceFile node.
             */
            function transformSourceFile(node) {
                if (node.isDeclarationFile) {
                    return node;
                }
                currentSourceFile = node;
                var visited = saveStateAndInvoke(node, visitSourceFile);
                ts.addEmitHelpers(visited, context.readEmitHelpers());
                currentSourceFile = undefined;
                return visited;
            }
            /**
             * Visits a node, saving and restoring state variables on the stack.
             *
             * @param node The node to visit.
             */
            function saveStateAndInvoke(node, f) {
                // Save state
                var savedCurrentScope = currentLexicalScope;
                var savedCurrentNameScope = currentNameScope;
                var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
                // Handle state changes before visiting a node.
                onBeforeVisitNode(node);
                var visited = f(node);
                // Restore state
                if (currentLexicalScope !== savedCurrentScope) {
                    currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
                }
                currentLexicalScope = savedCurrentScope;
                currentNameScope = savedCurrentNameScope;
                return visited;
            }
            /**
             * Performs actions that should always occur immediately before visiting a node.
             *
             * @param node The node to visit.
             */
            function onBeforeVisitNode(node) {
                switch (node.kind) {
                    case 277 /* SourceFile */:
                    case 244 /* CaseBlock */:
                    case 243 /* ModuleBlock */:
                    case 216 /* Block */:
                        currentLexicalScope = node;
                        currentNameScope = undefined;
                        currentScopeFirstDeclarationsOfName = undefined;
                        break;
                    case 238 /* ClassDeclaration */:
                    case 237 /* FunctionDeclaration */:
                        if (ts.hasModifier(node, 2 /* Ambient */)) {
                            break;
                        }
                        // Record these declarations provided that they have a name.
                        if (node.name) {
                            recordEmittedDeclarationInScope(node);
                        }
                        else {
                            // These nodes should always have names unless they are default-exports;
                            // however, class declaration parsing allows for undefined names, so syntactically invalid
                            // programs may also have an undefined name.
                            ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
                        }
                        if (ts.isClassDeclaration(node)) {
                            // XXX: should probably also cover interfaces and type aliases that can have type variables?
                            currentNameScope = node;
                        }
                        break;
                }
            }
            /**
             * General-purpose node visitor.
             *
             * @param node The node to visit.
             */
            function visitor(node) {
                return saveStateAndInvoke(node, visitorWorker);
            }
            /**
             * Visits and possibly transforms any node.
             *
             * @param node The node to visit.
             */
            function visitorWorker(node) {
                if (node.transformFlags & 1 /* TypeScript */) {
                    // This node is explicitly marked as TypeScript, so we should transform the node.
                    return visitTypeScript(node);
                }
                else if (node.transformFlags & 2 /* ContainsTypeScript */) {
                    // This node contains TypeScript, so we should visit its children.
                    return ts.visitEachChild(node, visitor, context);
                }
                return node;
            }
            /**
             * Specialized visitor that visits the immediate children of a SourceFile.
             *
             * @param node The node to visit.
             */
            function sourceElementVisitor(node) {
                return saveStateAndInvoke(node, sourceElementVisitorWorker);
            }
            /**
             * Specialized visitor that visits the immediate children of a SourceFile.
             *
             * @param node The node to visit.
             */
            function sourceElementVisitorWorker(node) {
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                    case 246 /* ImportEqualsDeclaration */:
                    case 252 /* ExportAssignment */:
                    case 253 /* ExportDeclaration */:
                        return visitEllidableStatement(node);
                    default:
                        return visitorWorker(node);
                }
            }
            function visitEllidableStatement(node) {
                var parsed = ts.getParseTreeNode(node);
                if (parsed !== node) {
                    // If the node has been transformed by a `before` transformer, perform no ellision on it
                    // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
                    // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
                    // and will trigger debug failures when debug verbosity is turned up
                    if (node.transformFlags & 2 /* ContainsTypeScript */) {
                        // This node contains TypeScript, so we should visit its children.
                        return ts.visitEachChild(node, visitor, context);
                    }
                    // Otherwise, we can just return the node
                    return node;
                }
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                        return visitImportDeclaration(node);
                    case 246 /* ImportEqualsDeclaration */:
                        return visitImportEqualsDeclaration(node);
                    case 252 /* ExportAssignment */:
                        return visitExportAssignment(node);
                    case 253 /* ExportDeclaration */:
                        return visitExportDeclaration(node);
                    default:
                        ts.Debug.fail("Unhandled ellided statement");
                }
            }
            /**
             * Specialized visitor that visits the immediate children of a namespace.
             *
             * @param node The node to visit.
             */
            function namespaceElementVisitor(node) {
                return saveStateAndInvoke(node, namespaceElementVisitorWorker);
            }
            /**
             * Specialized visitor that visits the immediate children of a namespace.
             *
             * @param node The node to visit.
             */
            function namespaceElementVisitorWorker(node) {
                if (node.kind === 253 /* ExportDeclaration */ ||
                    node.kind === 247 /* ImportDeclaration */ ||
                    node.kind === 248 /* ImportClause */ ||
                    (node.kind === 246 /* ImportEqualsDeclaration */ &&
                        node.moduleReference.kind === 257 /* ExternalModuleReference */)) {
                    // do not emit ES6 imports and exports since they are illegal inside a namespace
                    return undefined;
                }
                else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
                    // This node is explicitly marked as TypeScript, or is exported at the namespace
                    // level, so we should transform the node.
                    return visitTypeScript(node);
                }
                else if (node.transformFlags & 2 /* ContainsTypeScript */) {
                    // This node contains TypeScript, so we should visit its children.
                    return ts.visitEachChild(node, visitor, context);
                }
                return node;
            }
            /**
             * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
             *
             * @param node The node to visit.
             */
            function classElementVisitor(node) {
                return saveStateAndInvoke(node, classElementVisitorWorker);
            }
            /**
             * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
             *
             * @param node The node to visit.
             */
            function classElementVisitorWorker(node) {
                switch (node.kind) {
                    case 155 /* Constructor */:
                        // TypeScript constructors are transformed in `visitClassDeclaration`.
                        // We elide them here as `visitorWorker` checks transform flags, which could
                        // erronously include an ES6 constructor without TypeScript syntax.
                        return undefined;
                    case 152 /* PropertyDeclaration */:
                    case 160 /* IndexSignature */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 154 /* MethodDeclaration */:
                        // Fallback to the default visit behavior.
                        return visitorWorker(node);
                    case 215 /* SemicolonClassElement */:
                        return node;
                    default:
                        return ts.Debug.failBadSyntaxKind(node);
                }
            }
            function modifierVisitor(node) {
                if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
                    return undefined;
                }
                else if (currentNamespace && node.kind === 84 /* ExportKeyword */) {
                    return undefined;
                }
                return node;
            }
            /**
             * Branching visitor, visits a TypeScript syntax node.
             *
             * @param node The node to visit.
             */
            function visitTypeScript(node) {
                if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) {
                    // TypeScript ambient declarations are elided, but some comments may be preserved.
                    // See the implementation of `getLeadingComments` in comments.ts for more details.
                    return ts.createNotEmittedStatement(node);
                }
                switch (node.kind) {
                    case 84 /* ExportKeyword */:
                    case 79 /* DefaultKeyword */:
                        // ES6 export and default modifiers are elided when inside a namespace.
                        return currentNamespace ? undefined : node;
                    case 114 /* PublicKeyword */:
                    case 112 /* PrivateKeyword */:
                    case 113 /* ProtectedKeyword */:
                    case 117 /* AbstractKeyword */:
                    case 76 /* ConstKeyword */:
                    case 124 /* DeclareKeyword */:
                    case 132 /* ReadonlyKeyword */:
                    // TypeScript accessibility and readonly modifiers are elided.
                    case 167 /* ArrayType */:
                    case 168 /* TupleType */:
                    case 169 /* OptionalType */:
                    case 170 /* RestType */:
                    case 166 /* TypeLiteral */:
                    case 161 /* TypePredicate */:
                    case 148 /* TypeParameter */:
                    case 119 /* AnyKeyword */:
                    case 142 /* UnknownKeyword */:
                    case 122 /* BooleanKeyword */:
                    case 137 /* StringKeyword */:
                    case 134 /* NumberKeyword */:
                    case 131 /* NeverKeyword */:
                    case 105 /* VoidKeyword */:
                    case 138 /* SymbolKeyword */:
                    case 164 /* ConstructorType */:
                    case 163 /* FunctionType */:
                    case 165 /* TypeQuery */:
                    case 162 /* TypeReference */:
                    case 171 /* UnionType */:
                    case 172 /* IntersectionType */:
                    case 173 /* ConditionalType */:
                    case 175 /* ParenthesizedType */:
                    case 176 /* ThisType */:
                    case 177 /* TypeOperator */:
                    case 178 /* IndexedAccessType */:
                    case 179 /* MappedType */:
                    case 180 /* LiteralType */:
                    // TypeScript type nodes are elided.
                    case 160 /* IndexSignature */:
                    // TypeScript index signatures are elided.
                    case 150 /* Decorator */:
                    // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
                    case 240 /* TypeAliasDeclaration */:
                        // TypeScript type-only declarations are elided.
                        return undefined;
                    case 152 /* PropertyDeclaration */:
                        // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
                        return visitPropertyDeclaration(node);
                    case 245 /* NamespaceExportDeclaration */:
                        // TypeScript namespace export declarations are elided.
                        return undefined;
                    case 155 /* Constructor */:
                        return visitConstructor(node);
                    case 239 /* InterfaceDeclaration */:
                        // TypeScript interfaces are elided, but some comments may be preserved.
                        // See the implementation of `getLeadingComments` in comments.ts for more details.
                        return ts.createNotEmittedStatement(node);
                    case 238 /* ClassDeclaration */:
                        // This is a class declaration with TypeScript syntax extensions.
                        //
                        // TypeScript class syntax extensions include:
                        // - decorators
                        // - optional `implements` heritage clause
                        // - parameter property assignments in the constructor
                        // - property declarations
                        // - index signatures
                        // - method overload signatures
                        return visitClassDeclaration(node);
                    case 207 /* ClassExpression */:
                        // This is a class expression with TypeScript syntax extensions.
                        //
                        // TypeScript class syntax extensions include:
                        // - decorators
                        // - optional `implements` heritage clause
                        // - parameter property assignments in the constructor
                        // - property declarations
                        // - index signatures
                        // - method overload signatures
                        return visitClassExpression(node);
                    case 271 /* HeritageClause */:
                        // This is a heritage clause with TypeScript syntax extensions.
                        //
                        // TypeScript heritage clause extensions include:
                        // - `implements` clause
                        return visitHeritageClause(node);
                    case 209 /* ExpressionWithTypeArguments */:
                        // TypeScript supports type arguments on an expression in an `extends` heritage clause.
                        return visitExpressionWithTypeArguments(node);
                    case 154 /* MethodDeclaration */:
                        // TypeScript method declarations may have decorators, modifiers
                        // or type annotations.
                        return visitMethodDeclaration(node);
                    case 156 /* GetAccessor */:
                        // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
                        return visitGetAccessor(node);
                    case 157 /* SetAccessor */:
                        // Set Accessors can have TypeScript modifiers and type annotations.
                        return visitSetAccessor(node);
                    case 237 /* FunctionDeclaration */:
                        // Typescript function declarations can have modifiers, decorators, and type annotations.
                        return visitFunctionDeclaration(node);
                    case 194 /* FunctionExpression */:
                        // TypeScript function expressions can have modifiers and type annotations.
                        return visitFunctionExpression(node);
                    case 195 /* ArrowFunction */:
                        // TypeScript arrow functions can have modifiers and type annotations.
                        return visitArrowFunction(node);
                    case 149 /* Parameter */:
                        // This is a parameter declaration with TypeScript syntax extensions.
                        //
                        // TypeScript parameter declaration syntax extensions include:
                        // - decorators
                        // - accessibility modifiers
                        // - the question mark (?) token for optional parameters
                        // - type annotations
                        // - this parameters
                        return visitParameter(node);
                    case 193 /* ParenthesizedExpression */:
                        // ParenthesizedExpressions are TypeScript if their expression is a
                        // TypeAssertion or AsExpression
                        return visitParenthesizedExpression(node);
                    case 192 /* TypeAssertionExpression */:
                    case 210 /* AsExpression */:
                        // TypeScript type assertions are removed, but their subtrees are preserved.
                        return visitAssertionExpression(node);
                    case 189 /* CallExpression */:
                        return visitCallExpression(node);
                    case 190 /* NewExpression */:
                        return visitNewExpression(node);
                    case 191 /* TaggedTemplateExpression */:
                        return visitTaggedTemplateExpression(node);
                    case 211 /* NonNullExpression */:
                        // TypeScript non-null expressions are removed, but their subtrees are preserved.
                        return visitNonNullExpression(node);
                    case 241 /* EnumDeclaration */:
                        // TypeScript enum declarations do not exist in ES6 and must be rewritten.
                        return visitEnumDeclaration(node);
                    case 217 /* VariableStatement */:
                        // TypeScript namespace exports for variable statements must be transformed.
                        return visitVariableStatement(node);
                    case 235 /* VariableDeclaration */:
                        return visitVariableDeclaration(node);
                    case 242 /* ModuleDeclaration */:
                        // TypeScript namespace declarations must be transformed.
                        return visitModuleDeclaration(node);
                    case 246 /* ImportEqualsDeclaration */:
                        // TypeScript namespace or external module import.
                        return visitImportEqualsDeclaration(node);
                    default:
                        return ts.Debug.failBadSyntaxKind(node);
                }
            }
            function visitSourceFile(node) {
                var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
                    !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
                    !ts.isJsonSourceFile(node);
                return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
            }
            /**
             * Tests whether we should emit a __decorate call for a class declaration.
             */
            function shouldEmitDecorateCallForClass(node) {
                if (node.decorators && node.decorators.length > 0) {
                    return true;
                }
                var constructor = ts.getFirstConstructorWithBody(node);
                if (constructor) {
                    return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
                }
                return false;
            }
            /**
             * Tests whether we should emit a __decorate call for a parameter declaration.
             */
            function shouldEmitDecorateCallForParameter(parameter) {
                return parameter.decorators !== undefined && parameter.decorators.length > 0;
            }
            function getClassFacts(node, staticProperties) {
                var facts = 0 /* None */;
                if (ts.some(staticProperties))
                    facts |= 1 /* HasStaticInitializedProperties */;
                var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
                if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */)
                    facts |= 64 /* IsDerivedClass */;
                if (shouldEmitDecorateCallForClass(node))
                    facts |= 2 /* HasConstructorDecorators */;
                if (ts.childIsDecorated(node))
                    facts |= 4 /* HasMemberDecorators */;
                if (isExportOfNamespace(node))
                    facts |= 8 /* IsExportOfNamespace */;
                else if (isDefaultExternalModuleExport(node))
                    facts |= 32 /* IsDefaultExternalExport */;
                else if (isNamedExternalModuleExport(node))
                    facts |= 16 /* IsNamedExternalExport */;
                if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
                    facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
                return facts;
            }
            /**
             * Transforms a class declaration with TypeScript syntax into compatible ES6.
             *
             * This function will only be called when one of the following conditions are met:
             * - The class has decorators.
             * - The class has property declarations with initializers.
             * - The class contains a constructor that contains parameters with accessibility modifiers.
             * - The class is an export in a TypeScript namespace.
             *
             * @param node The node to transform.
             */
            function visitClassDeclaration(node) {
                var savedPendingExpressions = pendingExpressions;
                pendingExpressions = undefined;
                var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
                var facts = getClassFacts(node, staticProperties);
                if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
                    context.startLexicalEnvironment();
                }
                var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
                var classStatement = facts & 2 /* HasConstructorDecorators */
                    ? createClassDeclarationHeadWithDecorators(node, name, facts)
                    : createClassDeclarationHeadWithoutDecorators(node, name, facts);
                var statements = [classStatement];
                // Write any pending expressions from elided or moved computed property names
                if (ts.some(pendingExpressions)) {
                    statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
                }
                pendingExpressions = savedPendingExpressions;
                // Emit static property assignment. Because classDeclaration is lexically evaluated,
                // it is safe to emit static property assignment after classDeclaration
                // From ES6 specification:
                //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
                //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
                if (facts & 1 /* HasStaticInitializedProperties */) {
                    addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node));
                }
                // Write any decorators of the node.
                addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
                addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
                addConstructorDecorationStatement(statements, node);
                if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
                    // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
                    // 'es2015' transformer can properly nest static initializers and decorators. The result
                    // looks something like:
                    //
                    //  var C = function () {
                    //      class C {
                    //      }
                    //      C.static_prop = 1;
                    //      return C;
                    //  }();
                    //
                    var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */);
                    var localName = ts.getInternalName(node);
                    // The following partially-emitted expression exists purely to align our sourcemap
                    // emit with the original emitter.
                    var outer = ts.createPartiallyEmittedExpression(localName);
                    outer.end = closingBraceLocation.end;
                    ts.setEmitFlags(outer, 1536 /* NoComments */);
                    var statement = ts.createReturn(outer);
                    statement.pos = closingBraceLocation.pos;
                    ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
                    statements.push(statement);
                    ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
                    var iife = ts.createImmediatelyInvokedArrowFunction(statements);
                    ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
                    var varStatement = ts.createVariableStatement(
                    /*modifiers*/ undefined, ts.createVariableDeclarationList([
                        ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
                        /*type*/ undefined, iife)
                    ]));
                    ts.setOriginalNode(varStatement, node);
                    ts.setCommentRange(varStatement, node);
                    ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
                    ts.startOnNewLine(varStatement);
                    statements = [varStatement];
                }
                // If the class is exported as part of a TypeScript namespace, emit the namespace export.
                // Otherwise, if the class was exported at the top level and was decorated, emit an export
                // declaration or export default for the class.
                if (facts & 8 /* IsExportOfNamespace */) {
                    addExportMemberAssignment(statements, node);
                }
                else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
                    if (facts & 32 /* IsDefaultExternalExport */) {
                        statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
                    }
                    else if (facts & 16 /* IsNamedExternalExport */) {
                        statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
                    }
                }
                if (statements.length > 1) {
                    // Add a DeclarationMarker as a marker for the end of the declaration
                    statements.push(ts.createEndOfDeclarationMarker(node));
                    ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Transforms a non-decorated class declaration and appends the resulting statements.
             *
             * @param node A ClassDeclaration node.
             * @param name The name of the class.
             * @param facts Precomputed facts about the class.
             */
            function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
                //  ${modifiers} class ${name} ${heritageClauses} {
                //      ${members}
                //  }
                // we do not emit modifiers on the declaration if we are emitting an IIFE
                var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
                    ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
                    : undefined;
                var classDeclaration = ts.createClassDeclaration(
                /*decorators*/ undefined, modifiers, name, 
                /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0));
                // To better align with the old emitter, we should not emit a trailing source map
                // entry if the class has static properties.
                var emitFlags = ts.getEmitFlags(node);
                if (facts & 1 /* HasStaticInitializedProperties */) {
                    emitFlags |= 32 /* NoTrailingSourceMap */;
                }
                ts.setTextRange(classDeclaration, node);
                ts.setOriginalNode(classDeclaration, node);
                ts.setEmitFlags(classDeclaration, emitFlags);
                return classDeclaration;
            }
            /**
             * Transforms a decorated class declaration and appends the resulting statements. If
             * the class requires an alias to avoid issues with double-binding, the alias is returned.
             */
            function createClassDeclarationHeadWithDecorators(node, name, facts) {
                // When we emit an ES6 class that has a class decorator, we must tailor the
                // emit to certain specific cases.
                //
                // In the simplest case, we emit the class declaration as a let declaration, and
                // evaluate decorators after the close of the class body:
                //
                //  [Example 1]
                //  ---------------------------------------------------------------------
                //  TypeScript                      | Javascript
                //  ---------------------------------------------------------------------
                //  @dec                            | let C = class C {
                //  class C {                       | }
                //  }                               | C = __decorate([dec], C);
                //  ---------------------------------------------------------------------
                //  @dec                            | let C = class C {
                //  export class C {                | }
                //  }                               | C = __decorate([dec], C);
                //                                  | export { C };
                //  ---------------------------------------------------------------------
                //
                // If a class declaration contains a reference to itself *inside* of the class body,
                // this introduces two bindings to the class: One outside of the class body, and one
                // inside of the class body. If we apply decorators as in [Example 1] above, there
                // is the possibility that the decorator `dec` will return a new value for the
                // constructor, which would result in the binding inside of the class no longer
                // pointing to the same reference as the binding outside of the class.
                //
                // As a result, we must instead rewrite all references to the class *inside* of the
                // class body to instead point to a local temporary alias for the class:
                //
                //  [Example 2]
                //  ---------------------------------------------------------------------
                //  TypeScript                      | Javascript
                //  ---------------------------------------------------------------------
                //  @dec                            | let C = C_1 = class C {
                //  class C {                       |   static x() { return C_1.y; }
                //    static x() { return C.y; }    | }
                //    static y = 1;                 | C.y = 1;
                //  }                               | C = C_1 = __decorate([dec], C);
                //                                  | var C_1;
                //  ---------------------------------------------------------------------
                //  @dec                            | let C = class C {
                //  export class C {                |   static x() { return C_1.y; }
                //    static x() { return C.y; }    | }
                //    static y = 1;                 | C.y = 1;
                //  }                               | C = C_1 = __decorate([dec], C);
                //                                  | export { C };
                //                                  | var C_1;
                //  ---------------------------------------------------------------------
                //
                // If a class declaration is the default export of a module, we instead emit
                // the export after the decorated declaration:
                //
                //  [Example 3]
                //  ---------------------------------------------------------------------
                //  TypeScript                      | Javascript
                //  ---------------------------------------------------------------------
                //  @dec                            | let default_1 = class {
                //  export default class {          | }
                //  }                               | default_1 = __decorate([dec], default_1);
                //                                  | export default default_1;
                //  ---------------------------------------------------------------------
                //  @dec                            | let C = class C {
                //  export default class C {        | }
                //  }                               | C = __decorate([dec], C);
                //                                  | export default C;
                //  ---------------------------------------------------------------------
                //
                // If the class declaration is the default export and a reference to itself
                // inside of the class body, we must emit both an alias for the class *and*
                // move the export after the declaration:
                //
                //  [Example 4]
                //  ---------------------------------------------------------------------
                //  TypeScript                      | Javascript
                //  ---------------------------------------------------------------------
                //  @dec                            | let C = class C {
                //  export default class C {        |   static x() { return C_1.y; }
                //    static x() { return C.y; }    | }
                //    static y = 1;                 | C.y = 1;
                //  }                               | C = C_1 = __decorate([dec], C);
                //                                  | export default C;
                //                                  | var C_1;
                //  ---------------------------------------------------------------------
                //
                var location = ts.moveRangePastDecorators(node);
                var classAlias = getClassAliasIfNeeded(node);
                var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
                //  ... = class ${name} ${heritageClauses} {
                //      ${members}
                //  }
                var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
                var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0);
                var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
                ts.setOriginalNode(classExpression, node);
                ts.setTextRange(classExpression, location);
                //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
                //                                         or decoratedClassAlias if the class contain self-reference.
                var statement = ts.createVariableStatement(
                /*modifiers*/ undefined, ts.createVariableDeclarationList([
                    ts.createVariableDeclaration(declName, 
                    /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
                ], 1 /* Let */));
                ts.setOriginalNode(statement, node);
                ts.setTextRange(statement, location);
                ts.setCommentRange(statement, node);
                return statement;
            }
            /**
             * Transforms a class expression with TypeScript syntax into compatible ES6.
             *
             * This function will only be called when one of the following conditions are met:
             * - The class has property declarations with initializers.
             * - The class contains a constructor that contains parameters with accessibility modifiers.
             *
             * @param node The node to transform.
             */
            function visitClassExpression(node) {
                var savedPendingExpressions = pendingExpressions;
                pendingExpressions = undefined;
                var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
                var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
                var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; }));
                var classExpression = ts.createClassExpression(
                /*modifiers*/ undefined, node.name, 
                /*typeParameters*/ undefined, heritageClauses, members);
                ts.setOriginalNode(classExpression, node);
                ts.setTextRange(classExpression, node);
                if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
                    var expressions = [];
                    var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */;
                    var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
                    if (isClassWithConstructorReference) {
                        // record an alias as the class name is not in scope for statics.
                        enableSubstitutionForClassAliases();
                        var alias = ts.getSynthesizedClone(temp);
                        alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
                        classAliases[ts.getOriginalNodeId(node)] = alias;
                    }
                    // To preserve the behavior of the old emitter, we explicitly indent
                    // the body of a class with static initializers.
                    ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
                    expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
                    // Add any pending expressions leftover from elided or relocated computed property names
                    ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
                    pendingExpressions = savedPendingExpressions;
                    ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
                    expressions.push(ts.startOnNewLine(temp));
                    return ts.inlineExpressions(expressions);
                }
                pendingExpressions = savedPendingExpressions;
                return classExpression;
            }
            /**
             * Transforms the members of a class.
             *
             * @param node The current class.
             * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'.
             */
            function transformClassMembers(node, isDerivedClass) {
                var members = [];
                var constructor = transformConstructor(node, isDerivedClass);
                if (constructor) {
                    members.push(constructor);
                }
                ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
                return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
            }
            /**
             * Transforms (or creates) a constructor for a class.
             *
             * @param node The current class.
             * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'.
             */
            function transformConstructor(node, isDerivedClass) {
                // Check if we have property assignment inside class declaration.
                // If there is a property assignment, we need to emit constructor whether users define it or not
                // If there is no property assignment, we can omit constructor if users do not define it
                var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
                var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */;
                var constructor = ts.getFirstConstructorWithBody(node);
                // If the class does not contain nodes that require a synthesized constructor,
                // accept the current constructor if it exists.
                if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) {
                    return ts.visitEachChild(constructor, visitor, context);
                }
                var parameters = transformConstructorParameters(constructor);
                var body = transformConstructorBody(node, constructor, isDerivedClass);
                //  constructor(${parameters}) {
                //      ${body}
                //  }
                return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, parameters, body), constructor || node), constructor));
            }
            /**
             * Transforms (or creates) the parameters for the constructor of a class with
             * parameter property assignments or instance property initializers.
             *
             * @param constructor The constructor declaration.
             */
            function transformConstructorParameters(constructor) {
                // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation:
                // If constructor is empty, then
                //     If ClassHeritag_eopt is present and protoParent is not null, then
                //          Let constructor be the result of parsing the source text
                //              constructor(...args) { super (...args);}
                //          using the syntactic grammar with the goal symbol MethodDefinition[~Yield].
                //      Else,
                //           Let constructor be the result of parsing the source text
                //               constructor( ){ }
                //           using the syntactic grammar with the goal symbol MethodDefinition[~Yield].
                //
                // While we could emit the '...args' rest parameter, certain later tools in the pipeline might
                // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array.
                // Instead, we'll avoid using a rest parameter and spread into the super call as
                // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody".
                return ts.visitParameterList(constructor && constructor.parameters, visitor, context)
                    || [];
            }
            /**
             * Transforms (or creates) a constructor body for a class with parameter property
             * assignments or instance property initializers.
             *
             * @param node The current class.
             * @param constructor The current class constructor.
             * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'.
             */
            function transformConstructorBody(node, constructor, isDerivedClass) {
                var statements = [];
                var indexOfFirstStatement = 0;
                resumeLexicalEnvironment();
                if (constructor) {
                    indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements);
                    // Add parameters with property assignments. Transforms this:
                    //
                    //  constructor (public x, public y) {
                    //  }
                    //
                    // Into this:
                    //
                    //  constructor (x, y) {
                    //      this.x = x;
                    //      this.y = y;
                    //  }
                    //
                    var propertyAssignments = getParametersWithPropertyAssignments(constructor);
                    ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment));
                }
                else if (isDerivedClass) {
                    // Add a synthetic `super` call:
                    //
                    //  super(...arguments);
                    //
                    statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), 
                    /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
                }
                // Add the property initializers. Transforms this:
                //
                //  public x = 1;
                //
                // Into this:
                //
                //  constructor() {
                //      this.x = 1;
                //  }
                //
                var properties = getInitializedProperties(node, /*isStatic*/ false);
                addInitializedPropertyStatements(statements, properties, ts.createThis());
                if (constructor) {
                    // The class already had a constructor, so we should add the existing statements, skipping the initial super call.
                    ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
                }
                // End the lexical environment.
                statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
                return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
                /*location*/ constructor ? constructor.body.statements : node.members), 
                /*multiLine*/ true), 
                /*location*/ constructor ? constructor.body : undefined);
            }
            /**
             * Adds super call and preceding prologue directives into the list of statements.
             *
             * @param ctor The constructor node.
             * @returns index of the statement that follows super call
             */
            function addPrologueDirectivesAndInitialSuperCall(ctor, result) {
                if (ctor.body) {
                    var statements = ctor.body.statements;
                    // add prologue directives to the list (if any)
                    var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
                    if (index === statements.length) {
                        // list contains nothing but prologue directives (or empty) - exit
                        return index;
                    }
                    var statement = statements[index];
                    if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
                        result.push(ts.visitNode(statement, visitor, ts.isStatement));
                        return index + 1;
                    }
                    return index;
                }
                return 0;
            }
            /**
             * Gets all parameters of a constructor that should be transformed into property assignments.
             *
             * @param node The constructor node.
             */
            function getParametersWithPropertyAssignments(node) {
                return ts.filter(node.parameters, isParameterWithPropertyAssignment);
            }
            /**
             * Determines whether a parameter should be transformed into a property assignment.
             *
             * @param parameter The parameter node.
             */
            function isParameterWithPropertyAssignment(parameter) {
                return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */)
                    && ts.isIdentifier(parameter.name);
            }
            /**
             * Transforms a parameter into a property assignment statement.
             *
             * @param node The parameter declaration.
             */
            function transformParameterWithPropertyAssignment(node) {
                ts.Debug.assert(ts.isIdentifier(node.name));
                var name = node.name;
                var propertyName = ts.getMutableClone(name);
                ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
                var localName = ts.getMutableClone(name);
                ts.setEmitFlags(localName, 1536 /* NoComments */);
                return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */));
            }
            /**
             * Gets all property declarations with initializers on either the static or instance side of a class.
             *
             * @param node The class node.
             * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
             */
            function getInitializedProperties(node, isStatic) {
                return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty);
            }
            /**
             * Gets a value indicating whether a class element is a static property declaration with an initializer.
             *
             * @param member The class element node.
             */
            function isStaticInitializedProperty(member) {
                return isInitializedProperty(member, /*isStatic*/ true);
            }
            /**
             * Gets a value indicating whether a class element is an instance property declaration with an initializer.
             *
             * @param member The class element node.
             */
            function isInstanceInitializedProperty(member) {
                return isInitializedProperty(member, /*isStatic*/ false);
            }
            /**
             * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
             *
             * @param member The class element node.
             * @param isStatic A value indicating whether the member should be a static or instance member.
             */
            function isInitializedProperty(member, isStatic) {
                return member.kind === 152 /* PropertyDeclaration */
                    && isStatic === ts.hasModifier(member, 32 /* Static */)
                    && member.initializer !== undefined;
            }
            /**
             * Generates assignment statements for property initializers.
             *
             * @param properties An array of property declarations to transform.
             * @param receiver The receiver on which each property should be assigned.
             */
            function addInitializedPropertyStatements(statements, properties, receiver) {
                for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
                    var property = properties_10[_i];
                    var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
                    ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
                    ts.setCommentRange(statement, property);
                    ts.setOriginalNode(statement, property);
                    statements.push(statement);
                }
            }
            /**
             * Generates assignment expressions for property initializers.
             *
             * @param properties An array of property declarations to transform.
             * @param receiver The receiver on which each property should be assigned.
             */
            function generateInitializedPropertyExpressions(properties, receiver) {
                var expressions = [];
                for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) {
                    var property = properties_11[_i];
                    var expression = transformInitializedProperty(property, receiver);
                    ts.startOnNewLine(expression);
                    ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
                    ts.setCommentRange(expression, property);
                    ts.setOriginalNode(expression, property);
                    expressions.push(expression);
                }
                return expressions;
            }
            /**
             * Transforms a property initializer into an assignment statement.
             *
             * @param property The property declaration.
             * @param receiver The object receiving the property assignment.
             */
            function transformInitializedProperty(property, receiver) {
                // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
                var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
                    ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
                    : property.name;
                var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression);
                var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
                return ts.createAssignment(memberAccess, initializer);
            }
            /**
             * Gets either the static or instance members of a class that are decorated, or have
             * parameters that are decorated.
             *
             * @param node The class containing the member.
             * @param isStatic A value indicating whether to retrieve static or instance members of
             *                 the class.
             */
            function getDecoratedClassElements(node, isStatic) {
                return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
            }
            /**
             * Determines whether a class member is a static member of a class that is decorated, or
             * has parameters that are decorated.
             *
             * @param member The class member.
             */
            function isStaticDecoratedClassElement(member, parent) {
                return isDecoratedClassElement(member, /*isStatic*/ true, parent);
            }
            /**
             * Determines whether a class member is an instance member of a class that is decorated,
             * or has parameters that are decorated.
             *
             * @param member The class member.
             */
            function isInstanceDecoratedClassElement(member, parent) {
                return isDecoratedClassElement(member, /*isStatic*/ false, parent);
            }
            /**
             * Determines whether a class member is either a static or an instance member of a class
             * that is decorated, or has parameters that are decorated.
             *
             * @param member The class member.
             */
            function isDecoratedClassElement(member, isStatic, parent) {
                return ts.nodeOrChildIsDecorated(member, parent)
                    && isStatic === ts.hasModifier(member, 32 /* Static */);
            }
            /**
             * Gets an array of arrays of decorators for the parameters of a function-like node.
             * The offset into the result array should correspond to the offset of the parameter.
             *
             * @param node The function-like node.
             */
            function getDecoratorsOfParameters(node) {
                var decorators;
                if (node) {
                    var parameters = node.parameters;
                    for (var i = 0; i < parameters.length; i++) {
                        var parameter = parameters[i];
                        if (decorators || parameter.decorators) {
                            if (!decorators) {
                                decorators = new Array(parameters.length);
                            }
                            decorators[i] = parameter.decorators;
                        }
                    }
                }
                return decorators;
            }
            /**
             * Gets an AllDecorators object containing the decorators for the class and the decorators for the
             * parameters of the constructor of the class.
             *
             * @param node The class node.
             */
            function getAllDecoratorsOfConstructor(node) {
                var decorators = node.decorators;
                var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
                if (!decorators && !parameters) {
                    return undefined;
                }
                return {
                    decorators: decorators,
                    parameters: parameters
                };
            }
            /**
             * Gets an AllDecorators object containing the decorators for the member and its parameters.
             *
             * @param node The class node that contains the member.
             * @param member The class member.
             */
            function getAllDecoratorsOfClassElement(node, member) {
                switch (member.kind) {
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return getAllDecoratorsOfAccessors(node, member);
                    case 154 /* MethodDeclaration */:
                        return getAllDecoratorsOfMethod(member);
                    case 152 /* PropertyDeclaration */:
                        return getAllDecoratorsOfProperty(member);
                    default:
                        return undefined;
                }
            }
            /**
             * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
             *
             * @param node The class node that contains the accessor.
             * @param accessor The class accessor member.
             */
            function getAllDecoratorsOfAccessors(node, accessor) {
                if (!accessor.body) {
                    return undefined;
                }
                var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
                var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
                if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
                    return undefined;
                }
                var decorators = firstAccessorWithDecorators.decorators;
                var parameters = getDecoratorsOfParameters(setAccessor);
                if (!decorators && !parameters) {
                    return undefined;
                }
                return { decorators: decorators, parameters: parameters };
            }
            /**
             * Gets an AllDecorators object containing the decorators for the method and its parameters.
             *
             * @param method The class method member.
             */
            function getAllDecoratorsOfMethod(method) {
                if (!method.body) {
                    return undefined;
                }
                var decorators = method.decorators;
                var parameters = getDecoratorsOfParameters(method);
                if (!decorators && !parameters) {
                    return undefined;
                }
                return { decorators: decorators, parameters: parameters };
            }
            /**
             * Gets an AllDecorators object containing the decorators for the property.
             *
             * @param property The class property member.
             */
            function getAllDecoratorsOfProperty(property) {
                var decorators = property.decorators;
                if (!decorators) {
                    return undefined;
                }
                return { decorators: decorators };
            }
            /**
             * Transforms all of the decorators for a declaration into an array of expressions.
             *
             * @param node The declaration node.
             * @param allDecorators An object containing all of the decorators for the declaration.
             */
            function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
                if (!allDecorators) {
                    return undefined;
                }
                var decoratorExpressions = [];
                ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
                ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
                addTypeMetadata(node, container, decoratorExpressions);
                return decoratorExpressions;
            }
            /**
             * Generates statements used to apply decorators to either the static or instance members
             * of a class.
             *
             * @param node The class node.
             * @param isStatic A value indicating whether to generate statements for static or
             *                 instance members.
             */
            function addClassElementDecorationStatements(statements, node, isStatic) {
                ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
            }
            /**
             * Generates expressions used to apply decorators to either the static or instance members
             * of a class.
             *
             * @param node The class node.
             * @param isStatic A value indicating whether to generate expressions for static or
             *                 instance members.
             */
            function generateClassElementDecorationExpressions(node, isStatic) {
                var members = getDecoratedClassElements(node, isStatic);
                var expressions;
                for (var _i = 0, members_5 = members; _i < members_5.length; _i++) {
                    var member = members_5[_i];
                    var expression = generateClassElementDecorationExpression(node, member);
                    if (expression) {
                        if (!expressions) {
                            expressions = [expression];
                        }
                        else {
                            expressions.push(expression);
                        }
                    }
                }
                return expressions;
            }
            /**
             * Generates an expression used to evaluate class element decorators at runtime.
             *
             * @param node The class node that contains the member.
             * @param member The class member.
             */
            function generateClassElementDecorationExpression(node, member) {
                var allDecorators = getAllDecoratorsOfClassElement(node, member);
                var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
                if (!decoratorExpressions) {
                    return undefined;
                }
                // Emit the call to __decorate. Given the following:
                //
                //   class C {
                //     @dec method(@dec2 x) {}
                //     @dec get accessor() {}
                //     @dec prop;
                //   }
                //
                // The emit for a method is:
                //
                //   __decorate([
                //       dec,
                //       __param(0, dec2),
                //       __metadata("design:type", Function),
                //       __metadata("design:paramtypes", [Object]),
                //       __metadata("design:returntype", void 0)
                //   ], C.prototype, "method", null);
                //
                // The emit for an accessor is:
                //
                //   __decorate([
                //       dec
                //   ], C.prototype, "accessor", null);
                //
                // The emit for a property is:
                //
                //   __decorate([
                //       dec
                //   ], C.prototype, "prop");
                //
                var prefix = getClassMemberPrefix(node, member);
                var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
                var descriptor = languageVersion > 0 /* ES3 */
                    ? member.kind === 152 /* PropertyDeclaration */
                        // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
                        // should not invoke `Object.getOwnPropertyDescriptor`.
                        ? ts.createVoidZero()
                        // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
                        // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
                        : ts.createNull()
                    : undefined;
                var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
                ts.setEmitFlags(helper, 1536 /* NoComments */);
                return helper;
            }
            /**
             * Generates a __decorate helper call for a class constructor.
             *
             * @param node The class node.
             */
            function addConstructorDecorationStatement(statements, node) {
                var expression = generateConstructorDecorationExpression(node);
                if (expression) {
                    statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
                }
            }
            /**
             * Generates a __decorate helper call for a class constructor.
             *
             * @param node The class node.
             */
            function generateConstructorDecorationExpression(node) {
                var allDecorators = getAllDecoratorsOfConstructor(node);
                var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
                if (!decoratorExpressions) {
                    return undefined;
                }
                var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
                var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
                var decorate = createDecorateHelper(context, decoratorExpressions, localName);
                var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
                ts.setEmitFlags(expression, 1536 /* NoComments */);
                ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
                return expression;
            }
            /**
             * Transforms a decorator into an expression.
             *
             * @param decorator The decorator node.
             */
            function transformDecorator(decorator) {
                return ts.visitNode(decorator.expression, visitor, ts.isExpression);
            }
            /**
             * Transforms the decorators of a parameter.
             *
             * @param decorators The decorators for the parameter at the provided offset.
             * @param parameterOffset The offset of the parameter.
             */
            function transformDecoratorsOfParameter(decorators, parameterOffset) {
                var expressions;
                if (decorators) {
                    expressions = [];
                    for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
                        var decorator = decorators_1[_i];
                        var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, 
                        /*location*/ decorator.expression);
                        ts.setEmitFlags(helper, 1536 /* NoComments */);
                        expressions.push(helper);
                    }
                }
                return expressions;
            }
            /**
             * Adds optional type metadata for a declaration.
             *
             * @param node The declaration node.
             * @param decoratorExpressions The destination array to which to add new decorator expressions.
             */
            function addTypeMetadata(node, container, decoratorExpressions) {
                if (USE_NEW_TYPE_METADATA_FORMAT) {
                    addNewTypeMetadata(node, container, decoratorExpressions);
                }
                else {
                    addOldTypeMetadata(node, container, decoratorExpressions);
                }
            }
            function addOldTypeMetadata(node, container, decoratorExpressions) {
                if (compilerOptions.emitDecoratorMetadata) {
                    if (shouldAddTypeMetadata(node)) {
                        decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
                    }
                    if (shouldAddParamTypesMetadata(node)) {
                        decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
                    }
                    if (shouldAddReturnTypeMetadata(node)) {
                        decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
                    }
                }
            }
            function addNewTypeMetadata(node, container, decoratorExpressions) {
                if (compilerOptions.emitDecoratorMetadata) {
                    var properties = void 0;
                    if (shouldAddTypeMetadata(node)) {
                        (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
                    }
                    if (shouldAddParamTypesMetadata(node)) {
                        (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
                    }
                    if (shouldAddReturnTypeMetadata(node)) {
                        (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
                    }
                    if (properties) {
                        decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
                    }
                }
            }
            /**
             * Determines whether to emit the "design:type" metadata based on the node's kind.
             * The caller should have already tested whether the node has decorators and whether the
             * emitDecoratorMetadata compiler option is set.
             *
             * @param node The node to test.
             */
            function shouldAddTypeMetadata(node) {
                var kind = node.kind;
                return kind === 154 /* MethodDeclaration */
                    || kind === 156 /* GetAccessor */
                    || kind === 157 /* SetAccessor */
                    || kind === 152 /* PropertyDeclaration */;
            }
            /**
             * Determines whether to emit the "design:returntype" metadata based on the node's kind.
             * The caller should have already tested whether the node has decorators and whether the
             * emitDecoratorMetadata compiler option is set.
             *
             * @param node The node to test.
             */
            function shouldAddReturnTypeMetadata(node) {
                return node.kind === 154 /* MethodDeclaration */;
            }
            /**
             * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
             * The caller should have already tested whether the node has decorators and whether the
             * emitDecoratorMetadata compiler option is set.
             *
             * @param node The node to test.
             */
            function shouldAddParamTypesMetadata(node) {
                switch (node.kind) {
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                        return ts.getFirstConstructorWithBody(node) !== undefined;
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return true;
                }
                return false;
            }
            function getAccessorTypeNode(node) {
                var accessors = resolver.getAllAccessorDeclarations(node);
                return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
                    || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
            }
            /**
             * Serializes the type of a node for use with decorator type metadata.
             *
             * @param node The node that should have its type serialized.
             */
            function serializeTypeOfNode(node) {
                switch (node.kind) {
                    case 152 /* PropertyDeclaration */:
                    case 149 /* Parameter */:
                        return serializeTypeNode(node.type);
                    case 157 /* SetAccessor */:
                    case 156 /* GetAccessor */:
                        return serializeTypeNode(getAccessorTypeNode(node));
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                    case 154 /* MethodDeclaration */:
                        return ts.createIdentifier("Function");
                    default:
                        return ts.createVoidZero();
                }
            }
            /**
             * Serializes the types of the parameters of a node for use with decorator type metadata.
             *
             * @param node The node that should have its parameter types serialized.
             */
            function serializeParameterTypesOfNode(node, container) {
                var valueDeclaration = ts.isClassLike(node)
                    ? ts.getFirstConstructorWithBody(node)
                    : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
                        ? node
                        : undefined;
                var expressions = [];
                if (valueDeclaration) {
                    var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
                    var numParameters = parameters.length;
                    for (var i = 0; i < numParameters; i++) {
                        var parameter = parameters[i];
                        if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
                            continue;
                        }
                        if (parameter.dotDotDotToken) {
                            expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
                        }
                        else {
                            expressions.push(serializeTypeOfNode(parameter));
                        }
                    }
                }
                return ts.createArrayLiteral(expressions);
            }
            function getParametersOfDecoratedDeclaration(node, container) {
                if (container && node.kind === 156 /* GetAccessor */) {
                    var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
                    if (setAccessor) {
                        return setAccessor.parameters;
                    }
                }
                return node.parameters;
            }
            /**
             * Serializes the return type of a node for use with decorator type metadata.
             *
             * @param node The node that should have its return type serialized.
             */
            function serializeReturnTypeOfNode(node) {
                if (ts.isFunctionLike(node) && node.type) {
                    return serializeTypeNode(node.type);
                }
                else if (ts.isAsyncFunction(node)) {
                    return ts.createIdentifier("Promise");
                }
                return ts.createVoidZero();
            }
            /**
             * Serializes a type node for use with decorator type metadata.
             *
             * Types are serialized in the following fashion:
             * - Void types point to "undefined" (e.g. "void 0")
             * - Function and Constructor types point to the global "Function" constructor.
             * - Interface types with a call or construct signature types point to the global
             *   "Function" constructor.
             * - Array and Tuple types point to the global "Array" constructor.
             * - Type predicates and booleans point to the global "Boolean" constructor.
             * - String literal types and strings point to the global "String" constructor.
             * - Enum and number types point to the global "Number" constructor.
             * - Symbol types point to the global "Symbol" constructor.
             * - Type references to classes (or class-like variables) point to the constructor for the class.
             * - Anything else points to the global "Object" constructor.
             *
             * @param node The type node to serialize.
             */
            function serializeTypeNode(node) {
                if (node === undefined) {
                    return ts.createIdentifier("Object");
                }
                switch (node.kind) {
                    case 105 /* VoidKeyword */:
                    case 140 /* UndefinedKeyword */:
                    case 95 /* NullKeyword */:
                    case 131 /* NeverKeyword */:
                        return ts.createVoidZero();
                    case 175 /* ParenthesizedType */:
                        return serializeTypeNode(node.type);
                    case 163 /* FunctionType */:
                    case 164 /* ConstructorType */:
                        return ts.createIdentifier("Function");
                    case 167 /* ArrayType */:
                    case 168 /* TupleType */:
                        return ts.createIdentifier("Array");
                    case 161 /* TypePredicate */:
                    case 122 /* BooleanKeyword */:
                        return ts.createIdentifier("Boolean");
                    case 137 /* StringKeyword */:
                        return ts.createIdentifier("String");
                    case 135 /* ObjectKeyword */:
                        return ts.createIdentifier("Object");
                    case 180 /* LiteralType */:
                        switch (node.literal.kind) {
                            case 9 /* StringLiteral */:
                                return ts.createIdentifier("String");
                            case 8 /* NumericLiteral */:
                                return ts.createIdentifier("Number");
                            case 101 /* TrueKeyword */:
                            case 86 /* FalseKeyword */:
                                return ts.createIdentifier("Boolean");
                            default:
                                return ts.Debug.failBadSyntaxKind(node.literal);
                        }
                    case 134 /* NumberKeyword */:
                        return ts.createIdentifier("Number");
                    case 138 /* SymbolKeyword */:
                        return languageVersion < 2 /* ES2015 */
                            ? getGlobalSymbolNameWithFallback()
                            : ts.createIdentifier("Symbol");
                    case 162 /* TypeReference */:
                        return serializeTypeReferenceNode(node);
                    case 172 /* IntersectionType */:
                    case 171 /* UnionType */:
                        return serializeUnionOrIntersectionType(node);
                    case 165 /* TypeQuery */:
                    case 177 /* TypeOperator */:
                    case 178 /* IndexedAccessType */:
                    case 179 /* MappedType */:
                    case 166 /* TypeLiteral */:
                    case 119 /* AnyKeyword */:
                    case 142 /* UnknownKeyword */:
                    case 176 /* ThisType */:
                    case 181 /* ImportType */:
                        break;
                    default:
                        return ts.Debug.failBadSyntaxKind(node);
                }
                return ts.createIdentifier("Object");
            }
            function serializeUnionOrIntersectionType(node) {
                // Note when updating logic here also update getEntityNameForDecoratorMetadata
                // so that aliases can be marked as referenced
                var serializedUnion;
                for (var _i = 0, _a = node.types; _i < _a.length; _i++) {
                    var typeNode = _a[_i];
                    while (typeNode.kind === 175 /* ParenthesizedType */) {
                        typeNode = typeNode.type; // Skip parens if need be
                    }
                    if (typeNode.kind === 131 /* NeverKeyword */) {
                        continue; // Always elide `never` from the union/intersection if possible
                    }
                    if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 140 /* UndefinedKeyword */)) {
                        continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
                    }
                    var serializedIndividual = serializeTypeNode(typeNode);
                    if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
                        // One of the individual is global object, return immediately
                        return serializedIndividual;
                    }
                    // If there exists union that is not void 0 expression, check if the the common type is identifier.
                    // anything more complex and we will just default to Object
                    else if (serializedUnion) {
                        // Different types
                        if (!ts.isIdentifier(serializedUnion) ||
                            !ts.isIdentifier(serializedIndividual) ||
                            serializedUnion.escapedText !== serializedIndividual.escapedText) {
                            return ts.createIdentifier("Object");
                        }
                    }
                    else {
                        // Initialize the union type
                        serializedUnion = serializedIndividual;
                    }
                }
                // If we were able to find common type, use it
                return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
            }
            /**
             * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
             * decorator type metadata.
             *
             * @param node The type reference node.
             */
            function serializeTypeReferenceNode(node) {
                var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
                switch (kind) {
                    case ts.TypeReferenceSerializationKind.Unknown:
                        var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
                        var temp = ts.createTempVariable(hoistVariableDeclaration);
                        return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
                    case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
                        return serializeEntityNameAsExpression(node.typeName);
                    case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
                        return ts.createVoidZero();
                    case ts.TypeReferenceSerializationKind.BooleanType:
                        return ts.createIdentifier("Boolean");
                    case ts.TypeReferenceSerializationKind.NumberLikeType:
                        return ts.createIdentifier("Number");
                    case ts.TypeReferenceSerializationKind.StringLikeType:
                        return ts.createIdentifier("String");
                    case ts.TypeReferenceSerializationKind.ArrayLikeType:
                        return ts.createIdentifier("Array");
                    case ts.TypeReferenceSerializationKind.ESSymbolType:
                        return languageVersion < 2 /* ES2015 */
                            ? getGlobalSymbolNameWithFallback()
                            : ts.createIdentifier("Symbol");
                    case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
                        return ts.createIdentifier("Function");
                    case ts.TypeReferenceSerializationKind.Promise:
                        return ts.createIdentifier("Promise");
                    case ts.TypeReferenceSerializationKind.ObjectType:
                        return ts.createIdentifier("Object");
                    default:
                        return ts.Debug.assertNever(kind);
                }
            }
            function createCheckedValue(left, right) {
                return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
            }
            /**
             * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
             *
             * @param node The entity name to serialize.
             */
            function serializeEntityNameAsExpressionFallback(node) {
                if (node.kind === 71 /* Identifier */) {
                    // A -> typeof A !== undefined && A
                    var copied = serializeEntityNameAsExpression(node);
                    return createCheckedValue(copied, copied);
                }
                if (node.left.kind === 71 /* Identifier */) {
                    // A.B -> typeof A !== undefined && A.B
                    return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
                }
                // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
                var left = serializeEntityNameAsExpressionFallback(node.left);
                var temp = ts.createTempVariable(hoistVariableDeclaration);
                return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
            }
            /**
             * Serializes an entity name as an expression for decorator type metadata.
             *
             * @param node The entity name to serialize.
             */
            function serializeEntityNameAsExpression(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        // Create a clone of the name with a new parent, and treat it as if it were
                        // a source tree node for the purposes of the checker.
                        var name = ts.getMutableClone(node);
                        name.flags &= ~8 /* Synthesized */;
                        name.original = undefined;
                        name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
                        return name;
                    case 146 /* QualifiedName */:
                        return serializeQualifiedNameAsExpression(node);
                }
            }
            /**
             * Serializes an qualified name as an expression for decorator type metadata.
             *
             * @param node The qualified name to serialize.
             * @param useFallback A value indicating whether to use logical operators to test for the
             *                    qualified name at runtime.
             */
            function serializeQualifiedNameAsExpression(node) {
                return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
            }
            /**
             * Gets an expression that points to the global "Symbol" constructor at runtime if it is
             * available.
             */
            function getGlobalSymbolNameWithFallback() {
                return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
            }
            /**
             * A simple inlinable expression is an expression which can be copied into multiple locations
             * without risk of repeating any sideeffects and whose value could not possibly change between
             * any such locations
             */
            function isSimpleInlineableExpression(expression) {
                return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) ||
                    ts.isWellKnownSymbolSyntactically(expression);
            }
            /**
             * Gets an expression that represents a property name. For a computed property, a
             * name is generated for the node.
             *
             * @param member The member whose name should be converted into an expression.
             */
            function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
                var name = member.name;
                if (ts.isComputedPropertyName(name)) {
                    return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression)
                        ? ts.getGeneratedNameForNode(name)
                        : name.expression;
                }
                else if (ts.isIdentifier(name)) {
                    return ts.createLiteral(ts.idText(name));
                }
                else {
                    return ts.getSynthesizedClone(name);
                }
            }
            /**
             * If the name is a computed property, this function transforms it, then either returns an expression which caches the
             * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
             * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
             * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal)
             */
            function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) {
                if (ts.isComputedPropertyName(name)) {
                    var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
                    var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
                    var inlinable = isSimpleInlineableExpression(innerExpression);
                    if (!inlinable && shouldHoist) {
                        var generatedName = ts.getGeneratedNameForNode(name);
                        hoistVariableDeclaration(generatedName);
                        return ts.createAssignment(generatedName, expression);
                    }
                    return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression;
                }
            }
            /**
             * Visits the property name of a class element, for use when emitting property
             * initializers. For a computed property on a node with decorators, a temporary
             * value is stored for later use.
             *
             * @param member The member whose name should be visited.
             */
            function visitPropertyNameOfClassElement(member) {
                var name = member.name;
                var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false);
                if (expr) { // expr only exists if `name` is a computed property name
                    // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order
                    if (ts.some(pendingExpressions)) {
                        expr = ts.inlineExpressions(pendingExpressions.concat([expr]));
                        pendingExpressions.length = 0;
                    }
                    return ts.updateComputedPropertyName(name, expr);
                }
                else {
                    return name;
                }
            }
            /**
             * Transforms a HeritageClause with TypeScript syntax.
             *
             * This function will only be called when one of the following conditions are met:
             * - The node is a non-`extends` heritage clause that should be elided.
             * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
             *
             * @param node The HeritageClause to transform.
             */
            function visitHeritageClause(node) {
                if (node.token === 85 /* ExtendsKeyword */) {
                    var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
                    return ts.setTextRange(ts.createHeritageClause(85 /* ExtendsKeyword */, types), node);
                }
                return undefined;
            }
            /**
             * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
             *
             * This function will only be called when one of the following conditions are met:
             * - The node contains type arguments that should be elided.
             *
             * @param node The ExpressionWithTypeArguments to transform.
             */
            function visitExpressionWithTypeArguments(node) {
                return ts.updateExpressionWithTypeArguments(node, 
                /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
            }
            /**
             * Determines whether to emit a function-like declaration. We should not emit the
             * declaration if it does not have a body.
             *
             * @param node The declaration node.
             */
            function shouldEmitFunctionLikeDeclaration(node) {
                return !ts.nodeIsMissing(node.body);
            }
            function visitPropertyDeclaration(node) {
                var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true);
                if (expr && !isSimpleInlineableExpression(expr)) {
                    (pendingExpressions || (pendingExpressions = [])).push(expr);
                }
                return undefined;
            }
            function visitConstructor(node) {
                if (!shouldEmitFunctionLikeDeclaration(node)) {
                    return undefined;
                }
                return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
            }
            /**
             * Visits a method declaration of a class.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is an overload
             * - The node is marked as abstract, public, private, protected, or readonly
             * - The node has a computed property name
             *
             * @param node The method node.
             */
            function visitMethodDeclaration(node) {
                if (!shouldEmitFunctionLikeDeclaration(node)) {
                    return undefined;
                }
                var updated = ts.updateMethod(node, 
                /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
                /*questionToken*/ undefined, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
                if (updated !== node) {
                    // While we emit the source map for the node after skipping decorators and modifiers,
                    // we need to emit the comments for the original range.
                    ts.setCommentRange(updated, node);
                    ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
                }
                return updated;
            }
            /**
             * Determines whether to emit an accessor declaration. We should not emit the
             * declaration if it does not have a body and is abstract.
             *
             * @param node The declaration node.
             */
            function shouldEmitAccessorDeclaration(node) {
                return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
            }
            /**
             * Visits a get accessor declaration of a class.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is marked as abstract, public, private, or protected
             * - The node has a computed property name
             *
             * @param node The get accessor node.
             */
            function visitGetAccessor(node) {
                if (!shouldEmitAccessorDeclaration(node)) {
                    return undefined;
                }
                var updated = ts.updateGetAccessor(node, 
                /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
                if (updated !== node) {
                    // While we emit the source map for the node after skipping decorators and modifiers,
                    // we need to emit the comments for the original range.
                    ts.setCommentRange(updated, node);
                    ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
                }
                return updated;
            }
            /**
             * Visits a set accessor declaration of a class.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is marked as abstract, public, private, or protected
             * - The node has a computed property name
             *
             * @param node The set accessor node.
             */
            function visitSetAccessor(node) {
                if (!shouldEmitAccessorDeclaration(node)) {
                    return undefined;
                }
                var updated = ts.updateSetAccessor(node, 
                /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
                if (updated !== node) {
                    // While we emit the source map for the node after skipping decorators and modifiers,
                    // we need to emit the comments for the original range.
                    ts.setCommentRange(updated, node);
                    ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
                }
                return updated;
            }
            /**
             * Visits a function declaration.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is an overload
             * - The node is exported from a TypeScript namespace
             * - The node has decorators
             *
             * @param node The function node.
             */
            function visitFunctionDeclaration(node) {
                if (!shouldEmitFunctionLikeDeclaration(node)) {
                    return ts.createNotEmittedStatement(node);
                }
                var updated = ts.updateFunctionDeclaration(node, 
                /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
                if (isExportOfNamespace(node)) {
                    var statements = [updated];
                    addExportMemberAssignment(statements, node);
                    return statements;
                }
                return updated;
            }
            /**
             * Visits a function expression node.
             *
             * This function will be called when one of the following conditions are met:
             * - The node has type annotations
             *
             * @param node The function expression node.
             */
            function visitFunctionExpression(node) {
                if (!shouldEmitFunctionLikeDeclaration(node)) {
                    return ts.createOmittedExpression();
                }
                var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
                return updated;
            }
            /**
             * @remarks
             * This function will be called when one of the following conditions are met:
             * - The node has type annotations
             */
            function visitArrowFunction(node) {
                var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
                return updated;
            }
            /**
             * Visits a parameter declaration node.
             *
             * This function will be called when one of the following conditions are met:
             * - The node has an accessibility modifier.
             * - The node has a questionToken.
             * - The node's kind is ThisKeyword.
             *
             * @param node The parameter declaration node.
             */
            function visitParameter(node) {
                if (ts.parameterIsThisKeyword(node)) {
                    return undefined;
                }
                var parameter = ts.createParameter(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
                /*questionToken*/ undefined, 
                /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
                // While we emit the source map for the node after skipping decorators and modifiers,
                // we need to emit the comments for the original range.
                ts.setOriginalNode(parameter, node);
                ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
                ts.setCommentRange(parameter, node);
                ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
                ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
                return parameter;
            }
            /**
             * Visits a variable statement in a namespace.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is exported from a TypeScript namespace.
             */
            function visitVariableStatement(node) {
                if (isExportOfNamespace(node)) {
                    var variables = ts.getInitializedVariables(node.declarationList);
                    if (variables.length === 0) {
                        // elide statement if there are no initialized variables.
                        return undefined;
                    }
                    return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
                }
                else {
                    return ts.visitEachChild(node, visitor, context);
                }
            }
            function transformInitializedVariable(node) {
                var name = node.name;
                if (ts.isBindingPattern(name)) {
                    return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
                    /*needsValue*/ false, createNamespaceExportExpression);
                }
                else {
                    return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
                    /*location*/ node);
                }
            }
            function visitVariableDeclaration(node) {
                return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
                /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
            }
            /**
             * Visits a parenthesized expression that contains either a type assertion or an `as`
             * expression.
             *
             * @param node The parenthesized expression node.
             */
            function visitParenthesizedExpression(node) {
                var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
                if (ts.isAssertionExpression(innerExpression)) {
                    // Make sure we consider all nested cast expressions, e.g.:
                    // (<any><number><any>-A).x;
                    var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
                    // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
                    // is really not desirable. We would like to emit the subexpression as-is. Omitting
                    // the parentheses, however, could cause change in the semantics of the generated
                    // code if the casted expression has a lower precedence than the rest of the
                    // expression.
                    //
                    // To preserve comments, we return a "PartiallyEmittedExpression" here which will
                    // preserve the position information of the original expression.
                    //
                    // Due to the auto-parenthesization rules used by the visitor and factory functions
                    // we can safely elide the parentheses here, as a new synthetic
                    // ParenthesizedExpression will be inserted if we remove parentheses too
                    // aggressively.
                    // HOWEVER - if there are leading comments on the expression itself, to handle ASI
                    // correctly for return and throw, we must keep the parenthesis
                    if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
                        return ts.updateParen(node, expression);
                    }
                    return ts.createPartiallyEmittedExpression(expression, node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitAssertionExpression(node) {
                var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
                return ts.createPartiallyEmittedExpression(expression, node);
            }
            function visitNonNullExpression(node) {
                var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
                return ts.createPartiallyEmittedExpression(expression, node);
            }
            function visitCallExpression(node) {
                return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
                /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
            }
            function visitNewExpression(node) {
                return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
                /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
            }
            function visitTaggedTemplateExpression(node) {
                return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
                /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
            }
            /**
             * Determines whether to emit an enum declaration.
             *
             * @param node The enum declaration node.
             */
            function shouldEmitEnumDeclaration(node) {
                return !ts.isEnumConst(node)
                    || compilerOptions.preserveConstEnums
                    || compilerOptions.isolatedModules;
            }
            /**
             * Visits an enum declaration.
             *
             * This function will be called any time a TypeScript enum is encountered.
             *
             * @param node The enum declaration node.
             */
            function visitEnumDeclaration(node) {
                if (!shouldEmitEnumDeclaration(node)) {
                    return undefined;
                }
                var statements = [];
                // We request to be advised when the printer is about to print this node. This allows
                // us to set up the correct state for later substitutions.
                var emitFlags = 2 /* AdviseOnEmitNode */;
                // If needed, we should emit a variable declaration for the enum. If we emit
                // a leading variable declaration, we should not emit leading comments for the
                // enum body.
                var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
                if (varAdded) {
                    // We should still emit the comments if we are emitting a system module.
                    if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
                        emitFlags |= 512 /* NoLeadingComments */;
                    }
                }
                // `parameterName` is the declaration name used inside of the enum.
                var parameterName = getNamespaceParameterName(node);
                // `containerName` is the expression used inside of the enum for assignments.
                var containerName = getNamespaceContainerName(node);
                // `exportName` is the expression used within this node's container for any exported references.
                var exportName = ts.hasModifier(node, 1 /* Export */)
                    ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
                    : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
                //  x || (x = {})
                //  exports.x || (exports.x = {})
                var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
                if (hasNamespaceQualifiedExportName(node)) {
                    // `localName` is the expression used within this node's containing scope for any local references.
                    var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
                    //  x = (exports.x || (exports.x = {}))
                    moduleArg = ts.createAssignment(localName, moduleArg);
                }
                //  (function (x) {
                //      x[x["y"] = 0] = "y";
                //      ...
                //  })(x || (x = {}));
                var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
                /*type*/ undefined, transformEnumBody(node, containerName)), 
                /*typeArguments*/ undefined, [moduleArg]));
                ts.setOriginalNode(enumStatement, node);
                if (varAdded) {
                    // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
                    ts.setSyntheticLeadingComments(enumStatement, undefined);
                    ts.setSyntheticTrailingComments(enumStatement, undefined);
                }
                ts.setTextRange(enumStatement, node);
                ts.addEmitFlags(enumStatement, emitFlags);
                statements.push(enumStatement);
                // Add a DeclarationMarker for the enum to preserve trailing comments and mark
                // the end of the declaration.
                statements.push(ts.createEndOfDeclarationMarker(node));
                return statements;
            }
            /**
             * Transforms the body of an enum declaration.
             *
             * @param node The enum declaration node.
             */
            function transformEnumBody(node, localName) {
                var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
                currentNamespaceContainerName = localName;
                var statements = [];
                startLexicalEnvironment();
                var members = ts.map(node.members, transformEnumMember);
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                ts.addRange(statements, members);
                currentNamespaceContainerName = savedCurrentNamespaceLocalName;
                return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), 
                /*multiLine*/ true);
            }
            /**
             * Transforms an enum member into a statement.
             *
             * @param member The enum member node.
             */
            function transformEnumMember(member) {
                // enums don't support computed properties
                // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
                // old emitter always generate 'expression' part of the name as-is.
                var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
                var valueExpression = transformEnumMemberDeclarationValue(member);
                var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
                var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ?
                    innerAssignment :
                    ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
                return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
            }
            /**
             * Transforms the value of an enum member.
             *
             * @param member The enum member node.
             */
            function transformEnumMemberDeclarationValue(member) {
                var value = resolver.getConstantValue(member);
                if (value !== undefined) {
                    return ts.createLiteral(value);
                }
                else {
                    enableSubstitutionForNonQualifiedEnumMembers();
                    if (member.initializer) {
                        return ts.visitNode(member.initializer, visitor, ts.isExpression);
                    }
                    else {
                        return ts.createVoidZero();
                    }
                }
            }
            /**
             * Determines whether to elide a module declaration.
             *
             * @param node The module declaration node.
             */
            function shouldEmitModuleDeclaration(node) {
                return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
            }
            /**
             * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
             * or `exports.x`).
             */
            function hasNamespaceQualifiedExportName(node) {
                return isExportOfNamespace(node)
                    || (isExternalModuleExport(node)
                        && moduleKind !== ts.ModuleKind.ES2015
                        && moduleKind !== ts.ModuleKind.ESNext
                        && moduleKind !== ts.ModuleKind.System);
            }
            /**
             * Records that a declaration was emitted in the current scope, if it was the first
             * declaration for the provided symbol.
             */
            function recordEmittedDeclarationInScope(node) {
                if (!currentScopeFirstDeclarationsOfName) {
                    currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
                }
                var name = declaredNameInScope(node);
                if (!currentScopeFirstDeclarationsOfName.has(name)) {
                    currentScopeFirstDeclarationsOfName.set(name, node);
                }
            }
            /**
             * Determines whether a declaration is the first declaration with
             * the same name emitted in the current scope.
             */
            function isFirstEmittedDeclarationInScope(node) {
                if (currentScopeFirstDeclarationsOfName) {
                    var name = declaredNameInScope(node);
                    return currentScopeFirstDeclarationsOfName.get(name) === node;
                }
                return true;
            }
            function declaredNameInScope(node) {
                ts.Debug.assertNode(node.name, ts.isIdentifier);
                return node.name.escapedText;
            }
            /**
             * Adds a leading VariableStatement for a enum or module declaration.
             */
            function addVarForEnumOrModuleDeclaration(statements, node) {
                // Emit a variable statement for the module. We emit top-level enums as a `var`
                // declaration to avoid static errors in global scripts scripts due to redeclaration.
                // enums in any other scope are emitted as a `let` declaration.
                var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
                    ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
                ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
                ts.setOriginalNode(statement, node);
                recordEmittedDeclarationInScope(node);
                if (isFirstEmittedDeclarationInScope(node)) {
                    // Adjust the source map emit to match the old emitter.
                    if (node.kind === 241 /* EnumDeclaration */) {
                        ts.setSourceMapRange(statement.declarationList, node);
                    }
                    else {
                        ts.setSourceMapRange(statement, node);
                    }
                    // Trailing comments for module declaration should be emitted after the function closure
                    // instead of the variable statement:
                    //
                    //     /** Module comment*/
                    //     module m1 {
                    //         function foo4Export() {
                    //         }
                    //     } // trailing comment module
                    //
                    // Should emit:
                    //
                    //     /** Module comment*/
                    //     var m1;
                    //     (function (m1) {
                    //         function foo4Export() {
                    //         }
                    //     })(m1 || (m1 = {})); // trailing comment module
                    //
                    ts.setCommentRange(statement, node);
                    ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
                    statements.push(statement);
                    return true;
                }
                else {
                    // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
                    // declaration we do not emit a leading variable declaration. To preserve the
                    // begin/end semantics of the declararation and to properly handle exports
                    // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
                    var mergeMarker = ts.createMergeDeclarationMarker(statement);
                    ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
                    statements.push(mergeMarker);
                    return false;
                }
            }
            /**
             * Visits a module declaration node.
             *
             * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
             *
             * @param node The module declaration node.
             */
            function visitModuleDeclaration(node) {
                if (!shouldEmitModuleDeclaration(node)) {
                    return ts.createNotEmittedStatement(node);
                }
                ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
                enableSubstitutionForNamespaceExports();
                var statements = [];
                // We request to be advised when the printer is about to print this node. This allows
                // us to set up the correct state for later substitutions.
                var emitFlags = 2 /* AdviseOnEmitNode */;
                // If needed, we should emit a variable declaration for the module. If we emit
                // a leading variable declaration, we should not emit leading comments for the
                // module body.
                var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
                if (varAdded) {
                    // We should still emit the comments if we are emitting a system module.
                    if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
                        emitFlags |= 512 /* NoLeadingComments */;
                    }
                }
                // `parameterName` is the declaration name used inside of the namespace.
                var parameterName = getNamespaceParameterName(node);
                // `containerName` is the expression used inside of the namespace for exports.
                var containerName = getNamespaceContainerName(node);
                // `exportName` is the expression used within this node's container for any exported references.
                var exportName = ts.hasModifier(node, 1 /* Export */)
                    ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
                    : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
                //  x || (x = {})
                //  exports.x || (exports.x = {})
                var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
                if (hasNamespaceQualifiedExportName(node)) {
                    // `localName` is the expression used within this node's containing scope for any local references.
                    var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
                    //  x = (exports.x || (exports.x = {}))
                    moduleArg = ts.createAssignment(localName, moduleArg);
                }
                //  (function (x_1) {
                //      x_1.y = ...;
                //  })(x || (x = {}));
                var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
                /*type*/ undefined, transformModuleBody(node, containerName)), 
                /*typeArguments*/ undefined, [moduleArg]));
                ts.setOriginalNode(moduleStatement, node);
                if (varAdded) {
                    // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
                    ts.setSyntheticLeadingComments(moduleStatement, undefined);
                    ts.setSyntheticTrailingComments(moduleStatement, undefined);
                }
                ts.setTextRange(moduleStatement, node);
                ts.addEmitFlags(moduleStatement, emitFlags);
                statements.push(moduleStatement);
                // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
                // the end of the declaration.
                statements.push(ts.createEndOfDeclarationMarker(node));
                return statements;
            }
            /**
             * Transforms the body of a module declaration.
             *
             * @param node The module declaration node.
             */
            function transformModuleBody(node, namespaceLocalName) {
                var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
                var savedCurrentNamespace = currentNamespace;
                var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
                currentNamespaceContainerName = namespaceLocalName;
                currentNamespace = node;
                currentScopeFirstDeclarationsOfName = undefined;
                var statements = [];
                startLexicalEnvironment();
                var statementsLocation;
                var blockLocation;
                var body = node.body;
                if (body.kind === 243 /* ModuleBlock */) {
                    saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
                    statementsLocation = body.statements;
                    blockLocation = body;
                }
                else {
                    var result = visitModuleDeclaration(body);
                    if (result) {
                        if (ts.isArray(result)) {
                            ts.addRange(statements, result);
                        }
                        else {
                            statements.push(result);
                        }
                    }
                    var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
                    statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
                }
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                currentNamespaceContainerName = savedCurrentNamespaceContainerName;
                currentNamespace = savedCurrentNamespace;
                currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
                var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
                /*location*/ statementsLocation), 
                /*multiLine*/ true);
                ts.setTextRange(block, blockLocation);
                // namespace hello.hi.world {
                //      function foo() {}
                //
                //      // TODO, blah
                // }
                //
                // should be emitted as
                //
                // var hello;
                // (function (hello) {
                //     var hi;
                //     (function (hi) {
                //         var world;
                //         (function (world) {
                //             function foo() { }
                //             // TODO, blah
                //         })(world = hi.world || (hi.world = {}));
                //     })(hi = hello.hi || (hello.hi = {}));
                // })(hello || (hello = {}));
                // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
                if (body.kind !== 243 /* ModuleBlock */) {
                    ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
                }
                return block;
            }
            function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
                if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) {
                    var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
                    return recursiveInnerModule || moduleDeclaration.body;
                }
            }
            /**
             * Visits an import declaration, eliding it if it is not referenced.
             *
             * @param node The import declaration node.
             */
            function visitImportDeclaration(node) {
                if (!node.importClause) {
                    // Do not elide a side-effect only import declaration.
                    //  import "foo";
                    return node;
                }
                // Elide the declaration if the import clause was elided.
                var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
                return importClause
                    ? ts.updateImportDeclaration(node, 
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, importClause, node.moduleSpecifier)
                    : undefined;
            }
            /**
             * Visits an import clause, eliding it if it is not referenced.
             *
             * @param node The import clause node.
             */
            function visitImportClause(node) {
                // Elide the import clause if we elide both its name and its named bindings.
                var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
                var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
                return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined;
            }
            /**
             * Visits named import bindings, eliding it if it is not referenced.
             *
             * @param node The named import bindings node.
             */
            function visitNamedImportBindings(node) {
                if (node.kind === 249 /* NamespaceImport */) {
                    // Elide a namespace import if it is not referenced.
                    return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
                }
                else {
                    // Elide named imports if all of its import specifiers are elided.
                    var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
                    return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
                }
            }
            /**
             * Visits an import specifier, eliding it if it is not referenced.
             *
             * @param node The import specifier node.
             */
            function visitImportSpecifier(node) {
                // Elide an import specifier if it is not referenced.
                return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
            }
            /**
             * Visits an export assignment, eliding it if it does not contain a clause that resolves
             * to a value.
             *
             * @param node The export assignment node.
             */
            function visitExportAssignment(node) {
                // Elide the export assignment if it does not reference a value.
                return resolver.isValueAliasDeclaration(node)
                    ? ts.visitEachChild(node, visitor, context)
                    : undefined;
            }
            /**
             * Visits an export declaration, eliding it if it does not contain a clause that resolves
             * to a value.
             *
             * @param node The export declaration node.
             */
            function visitExportDeclaration(node) {
                if (!node.exportClause) {
                    // Elide a star export if the module it references does not export a value.
                    return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
                }
                if (!resolver.isValueAliasDeclaration(node)) {
                    // Elide the export declaration if it does not export a value.
                    return undefined;
                }
                // Elide the export declaration if all of its named exports are elided.
                var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports);
                return exportClause
                    ? ts.updateExportDeclaration(node, 
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, exportClause, node.moduleSpecifier)
                    : undefined;
            }
            /**
             * Visits named exports, eliding it if it does not contain an export specifier that
             * resolves to a value.
             *
             * @param node The named exports node.
             */
            function visitNamedExports(node) {
                // Elide the named exports if all of its export specifiers were elided.
                var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
                return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
            }
            /**
             * Visits an export specifier, eliding it if it does not resolve to a value.
             *
             * @param node The export specifier node.
             */
            function visitExportSpecifier(node) {
                // Elide an export specifier if it does not reference a value.
                return resolver.isValueAliasDeclaration(node) ? node : undefined;
            }
            /**
             * Determines whether to emit an import equals declaration.
             *
             * @param node The import equals declaration node.
             */
            function shouldEmitImportEqualsDeclaration(node) {
                // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
                // - current file is not external module
                // - import declaration is top level and target is value imported by entity name
                return resolver.isReferencedAliasDeclaration(node)
                    || (!ts.isExternalModule(currentSourceFile)
                        && resolver.isTopLevelValueImportEqualsWithEntityName(node));
            }
            /**
             * Visits an import equals declaration.
             *
             * @param node The import equals declaration node.
             */
            function visitImportEqualsDeclaration(node) {
                if (ts.isExternalModuleImportEqualsDeclaration(node)) {
                    // Elide external module `import=` if it is not referenced.
                    return resolver.isReferencedAliasDeclaration(node)
                        ? ts.visitEachChild(node, visitor, context)
                        : undefined;
                }
                if (!shouldEmitImportEqualsDeclaration(node)) {
                    return undefined;
                }
                var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
                ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
                if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
                    //  export var ${name} = ${moduleReference};
                    //  var ${name} = ${moduleReference};
                    return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
                        ts.setOriginalNode(ts.createVariableDeclaration(node.name, 
                        /*type*/ undefined, moduleReference), node)
                    ])), node), node);
                }
                else {
                    // exports.${name} = ${moduleReference};
                    return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
                }
            }
            /**
             * Gets a value indicating whether the node is exported from a namespace.
             *
             * @param node The node to test.
             */
            function isExportOfNamespace(node) {
                return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
            }
            /**
             * Gets a value indicating whether the node is exported from an external module.
             *
             * @param node The node to test.
             */
            function isExternalModuleExport(node) {
                return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
            }
            /**
             * Gets a value indicating whether the node is a named export from an external module.
             *
             * @param node The node to test.
             */
            function isNamedExternalModuleExport(node) {
                return isExternalModuleExport(node)
                    && !ts.hasModifier(node, 512 /* Default */);
            }
            /**
             * Gets a value indicating whether the node is the default export of an external module.
             *
             * @param node The node to test.
             */
            function isDefaultExternalModuleExport(node) {
                return isExternalModuleExport(node)
                    && ts.hasModifier(node, 512 /* Default */);
            }
            /**
             * Creates a statement for the provided expression. This is used in calls to `map`.
             */
            function expressionToStatement(expression) {
                return ts.createExpressionStatement(expression);
            }
            function addExportMemberAssignment(statements, node) {
                var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
                ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
                var statement = ts.createExpressionStatement(expression);
                ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
                statements.push(statement);
            }
            function createNamespaceExport(exportName, exportValue, location) {
                return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
            }
            function createNamespaceExportExpression(exportName, exportValue, location) {
                return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
            }
            function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
                return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
            }
            /**
             * Gets the declaration name used inside of a namespace or enum.
             */
            function getNamespaceParameterName(node) {
                var name = ts.getGeneratedNameForNode(node);
                ts.setSourceMapRange(name, node.name);
                return name;
            }
            /**
             * Gets the expression used to refer to a namespace or enum within the body
             * of its declaration.
             */
            function getNamespaceContainerName(node) {
                return ts.getGeneratedNameForNode(node);
            }
            /**
             * Gets a local alias for a class declaration if it is a decorated class with an internal
             * reference to the static side of the class. This is necessary to avoid issues with
             * double-binding semantics for the class name.
             */
            function getClassAliasIfNeeded(node) {
                if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) {
                    enableSubstitutionForClassAliases();
                    var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
                    classAliases[ts.getOriginalNodeId(node)] = classAlias;
                    hoistVariableDeclaration(classAlias);
                    return classAlias;
                }
            }
            function getClassPrototype(node) {
                return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
            }
            function getClassMemberPrefix(node, member) {
                return ts.hasModifier(member, 32 /* Static */)
                    ? ts.getDeclarationName(node)
                    : getClassPrototype(node);
            }
            function enableSubstitutionForNonQualifiedEnumMembers() {
                if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
                    enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
                    context.enableSubstitution(71 /* Identifier */);
                }
            }
            function enableSubstitutionForClassAliases() {
                if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
                    enabledSubstitutions |= 1 /* ClassAliases */;
                    // We need to enable substitutions for identifiers. This allows us to
                    // substitute class names inside of a class declaration.
                    context.enableSubstitution(71 /* Identifier */);
                    // Keep track of class aliases.
                    classAliases = [];
                }
            }
            function enableSubstitutionForNamespaceExports() {
                if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
                    enabledSubstitutions |= 2 /* NamespaceExports */;
                    // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
                    // substitute the names of exported members of a namespace.
                    context.enableSubstitution(71 /* Identifier */);
                    context.enableSubstitution(274 /* ShorthandPropertyAssignment */);
                    // We need to be notified when entering and exiting namespaces.
                    context.enableEmitNotification(242 /* ModuleDeclaration */);
                }
            }
            function isTransformedModuleDeclaration(node) {
                return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */;
            }
            function isTransformedEnumDeclaration(node) {
                return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */;
            }
            /**
             * Hook for node emit.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emit A callback used to emit the node in the printer.
             */
            function onEmitNode(hint, node, emitCallback) {
                var savedApplicableSubstitutions = applicableSubstitutions;
                var savedCurrentSourceFile = currentSourceFile;
                if (ts.isSourceFile(node)) {
                    currentSourceFile = node;
                }
                if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
                    applicableSubstitutions |= 2 /* NamespaceExports */;
                }
                if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
                    applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
                }
                previousOnEmitNode(hint, node, emitCallback);
                applicableSubstitutions = savedApplicableSubstitutions;
                currentSourceFile = savedCurrentSourceFile;
            }
            /**
             * Hooks node substitutions.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (hint === 1 /* Expression */) {
                    return substituteExpression(node);
                }
                else if (ts.isShorthandPropertyAssignment(node)) {
                    return substituteShorthandPropertyAssignment(node);
                }
                return node;
            }
            function substituteShorthandPropertyAssignment(node) {
                if (enabledSubstitutions & 2 /* NamespaceExports */) {
                    var name = node.name;
                    var exportedName = trySubstituteNamespaceExportedName(name);
                    if (exportedName) {
                        // A shorthand property with an assignment initializer is probably part of a
                        // destructuring assignment
                        if (node.objectAssignmentInitializer) {
                            var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
                            return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
                        }
                        return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
                    }
                }
                return node;
            }
            function substituteExpression(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return substituteExpressionIdentifier(node);
                    case 187 /* PropertyAccessExpression */:
                        return substitutePropertyAccessExpression(node);
                    case 188 /* ElementAccessExpression */:
                        return substituteElementAccessExpression(node);
                }
                return node;
            }
            function substituteExpressionIdentifier(node) {
                return trySubstituteClassAlias(node)
                    || trySubstituteNamespaceExportedName(node)
                    || node;
            }
            function trySubstituteClassAlias(node) {
                if (enabledSubstitutions & 1 /* ClassAliases */) {
                    if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) {
                        // Due to the emit for class decorators, any reference to the class from inside of the class body
                        // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
                        // behavior of class names in ES6.
                        // Also, when emitting statics for class expressions, we must substitute a class alias for
                        // constructor references in static property initializers.
                        var declaration = resolver.getReferencedValueDeclaration(node);
                        if (declaration) {
                            var classAlias = classAliases[declaration.id]; // TODO: GH#18217
                            if (classAlias) {
                                var clone_1 = ts.getSynthesizedClone(classAlias);
                                ts.setSourceMapRange(clone_1, node);
                                ts.setCommentRange(clone_1, node);
                                return clone_1;
                            }
                        }
                    }
                }
                return undefined;
            }
            function trySubstituteNamespaceExportedName(node) {
                // If this is explicitly a local name, do not substitute.
                if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
                    // If we are nested within a namespace declaration, we may need to qualifiy
                    // an identifier that is exported from a merged namespace.
                    var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
                    if (container && container.kind !== 277 /* SourceFile */) {
                        var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) ||
                            (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */);
                        if (substitute) {
                            return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), 
                            /*location*/ node);
                        }
                    }
                }
                return undefined;
            }
            function substitutePropertyAccessExpression(node) {
                return substituteConstantValue(node);
            }
            function substituteElementAccessExpression(node) {
                return substituteConstantValue(node);
            }
            function substituteConstantValue(node) {
                var constantValue = tryGetConstEnumValue(node);
                if (constantValue !== undefined) {
                    // track the constant value on the node for the printer in needsDotDotForPropertyAccess
                    ts.setConstantValue(node, constantValue);
                    var substitute = ts.createLiteral(constantValue);
                    if (!compilerOptions.removeComments) {
                        var propertyName = ts.isPropertyAccessExpression(node)
                            ? ts.declarationNameToString(node.name)
                            : ts.getTextOfNode(node.argumentExpression);
                        ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
                    }
                    return substitute;
                }
                return node;
            }
            function tryGetConstEnumValue(node) {
                if (compilerOptions.isolatedModules) {
                    return undefined;
                }
                return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
            }
        }
        ts.transformTypeScript = transformTypeScript;
        function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
            var argumentsArray = [];
            argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
            argumentsArray.push(target);
            if (memberName) {
                argumentsArray.push(memberName);
                if (descriptor) {
                    argumentsArray.push(descriptor);
                }
            }
            context.requestEmitHelper(decorateHelper);
            return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), 
            /*typeArguments*/ undefined, argumentsArray), location);
        }
        var decorateHelper = {
            name: "typescript:decorate",
            scoped: false,
            priority: 2,
            text: "\n            var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n                var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n                if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n                else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n                return c > 3 && r && Object.defineProperty(target, key, r), r;\n            };"
        };
        function createMetadataHelper(context, metadataKey, metadataValue) {
            context.requestEmitHelper(metadataHelper);
            return ts.createCall(ts.getHelperName("__metadata"), 
            /*typeArguments*/ undefined, [
                ts.createLiteral(metadataKey),
                metadataValue
            ]);
        }
        var metadataHelper = {
            name: "typescript:metadata",
            scoped: false,
            priority: 3,
            text: "\n            var __metadata = (this && this.__metadata) || function (k, v) {\n                if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n            };"
        };
        function createParamHelper(context, expression, parameterOffset, location) {
            context.requestEmitHelper(paramHelper);
            return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), 
            /*typeArguments*/ undefined, [
                ts.createLiteral(parameterOffset),
                expression
            ]), location);
        }
        var paramHelper = {
            name: "typescript:param",
            scoped: false,
            priority: 4,
            text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
        };
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        var ES2017SubstitutionFlags;
        (function (ES2017SubstitutionFlags) {
            /** Enables substitutions for async methods with `super` calls. */
            ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
        })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
        function transformES2017(context) {
            var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
            var resolver = context.getEmitResolver();
            var compilerOptions = context.getCompilerOptions();
            var languageVersion = ts.getEmitScriptTarget(compilerOptions);
            /**
             * Keeps track of whether expression substitution has been enabled for specific edge cases.
             * They are persisted between each SourceFile transformation and should not be reset.
             */
            var enabledSubstitutions;
            /**
             * This keeps track of containers where `super` is valid, for use with
             * just-in-time substitution for `super` expressions inside of async methods.
             */
            var enclosingSuperContainerFlags = 0;
            var enclosingFunctionParameterNames;
            // Save the previous transformation hooks.
            var previousOnEmitNode = context.onEmitNode;
            var previousOnSubstituteNode = context.onSubstituteNode;
            // Set new transformation hooks.
            context.onEmitNode = onEmitNode;
            context.onSubstituteNode = onSubstituteNode;
            return ts.chainBundle(transformSourceFile);
            function transformSourceFile(node) {
                if (node.isDeclarationFile) {
                    return node;
                }
                var visited = ts.visitEachChild(node, visitor, context);
                ts.addEmitHelpers(visited, context.readEmitHelpers());
                return visited;
            }
            function visitor(node) {
                if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
                    return node;
                }
                switch (node.kind) {
                    case 120 /* AsyncKeyword */:
                        // ES2017 async modifier should be elided for targets < ES2017
                        return undefined;
                    case 199 /* AwaitExpression */:
                        return visitAwaitExpression(node);
                    case 154 /* MethodDeclaration */:
                        return visitMethodDeclaration(node);
                    case 237 /* FunctionDeclaration */:
                        return visitFunctionDeclaration(node);
                    case 194 /* FunctionExpression */:
                        return visitFunctionExpression(node);
                    case 195 /* ArrowFunction */:
                        return visitArrowFunction(node);
                    default:
                        return ts.visitEachChild(node, visitor, context);
                }
            }
            function asyncBodyVisitor(node) {
                if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
                    switch (node.kind) {
                        case 217 /* VariableStatement */:
                            return visitVariableStatementInAsyncBody(node);
                        case 223 /* ForStatement */:
                            return visitForStatementInAsyncBody(node);
                        case 224 /* ForInStatement */:
                            return visitForInStatementInAsyncBody(node);
                        case 225 /* ForOfStatement */:
                            return visitForOfStatementInAsyncBody(node);
                        case 272 /* CatchClause */:
                            return visitCatchClauseInAsyncBody(node);
                        case 216 /* Block */:
                        case 230 /* SwitchStatement */:
                        case 244 /* CaseBlock */:
                        case 269 /* CaseClause */:
                        case 270 /* DefaultClause */:
                        case 233 /* TryStatement */:
                        case 221 /* DoStatement */:
                        case 222 /* WhileStatement */:
                        case 220 /* IfStatement */:
                        case 229 /* WithStatement */:
                        case 231 /* LabeledStatement */:
                            return ts.visitEachChild(node, asyncBodyVisitor, context);
                        default:
                            return ts.Debug.assertNever(node, "Unhandled node.");
                    }
                }
                return visitor(node);
            }
            function visitCatchClauseInAsyncBody(node) {
                var catchClauseNames = ts.createUnderscoreEscapedMap();
                recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
                // names declared in a catch variable are block scoped
                var catchClauseUnshadowedNames;
                catchClauseNames.forEach(function (_, escapedName) {
                    if (enclosingFunctionParameterNames.has(escapedName)) {
                        if (!catchClauseUnshadowedNames) {
                            catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
                        }
                        catchClauseUnshadowedNames.delete(escapedName);
                    }
                });
                if (catchClauseUnshadowedNames) {
                    var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
                    enclosingFunctionParameterNames = catchClauseUnshadowedNames;
                    var result = ts.visitEachChild(node, asyncBodyVisitor, context);
                    enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
                    return result;
                }
                else {
                    return ts.visitEachChild(node, asyncBodyVisitor, context);
                }
            }
            function visitVariableStatementInAsyncBody(node) {
                if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
                    var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
                    return expression ? ts.createExpressionStatement(expression) : undefined;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitForInStatementInAsyncBody(node) {
                return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
                    ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
                    : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
            }
            function visitForOfStatementInAsyncBody(node) {
                return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
                    ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
                    : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
            }
            function visitForStatementInAsyncBody(node) {
                var initializer = node.initializer; // TODO: GH#18217
                return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
                    ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
                    : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
            }
            /**
             * Visits an AwaitExpression node.
             *
             * This function will be called any time a ES2017 await expression is encountered.
             *
             * @param node The node to visit.
             */
            function visitAwaitExpression(node) {
                return ts.setOriginalNode(ts.setTextRange(ts.createYield(
                /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
            }
            /**
             * Visits a MethodDeclaration node.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is marked as async
             *
             * @param node The node to visit.
             */
            function visitMethodDeclaration(node) {
                return ts.updateMethod(node, 
                /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
                /*questionToken*/ undefined, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
                    ? transformAsyncFunctionBody(node)
                    : ts.visitFunctionBody(node.body, visitor, context));
            }
            /**
             * Visits a FunctionDeclaration node.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is marked async
             *
             * @param node The node to visit.
             */
            function visitFunctionDeclaration(node) {
                return ts.updateFunctionDeclaration(node, 
                /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
                    ? transformAsyncFunctionBody(node)
                    : ts.visitFunctionBody(node.body, visitor, context));
            }
            /**
             * Visits a FunctionExpression node.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is marked async
             *
             * @param node The node to visit.
             */
            function visitFunctionExpression(node) {
                return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
                    ? transformAsyncFunctionBody(node)
                    : ts.visitFunctionBody(node.body, visitor, context));
            }
            /**
             * Visits an ArrowFunction.
             *
             * This function will be called when one of the following conditions are met:
             * - The node is marked async
             *
             * @param node The node to visit.
             */
            function visitArrowFunction(node) {
                return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
                    ? transformAsyncFunctionBody(node)
                    : ts.visitFunctionBody(node.body, visitor, context));
            }
            function recordDeclarationName(_a, names) {
                var name = _a.name;
                if (ts.isIdentifier(name)) {
                    names.set(name.escapedText, true);
                }
                else {
                    for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
                        var element = _b[_i];
                        if (!ts.isOmittedExpression(element)) {
                            recordDeclarationName(element, names);
                        }
                    }
                }
            }
            function isVariableDeclarationListWithCollidingName(node) {
                return !!node
                    && ts.isVariableDeclarationList(node)
                    && !(node.flags & 3 /* BlockScoped */)
                    && node.declarations.some(collidesWithParameterName);
            }
            function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
                hoistVariableDeclarationList(node);
                var variables = ts.getInitializedVariables(node);
                if (variables.length === 0) {
                    if (hasReceiver) {
                        return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
                    }
                    return undefined;
                }
                return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
            }
            function hoistVariableDeclarationList(node) {
                ts.forEach(node.declarations, hoistVariable);
            }
            function hoistVariable(_a) {
                var name = _a.name;
                if (ts.isIdentifier(name)) {
                    hoistVariableDeclaration(name);
                }
                else {
                    for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
                        var element = _b[_i];
                        if (!ts.isOmittedExpression(element)) {
                            hoistVariable(element);
                        }
                    }
                }
            }
            function transformInitializedVariable(node) {
                var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
                return ts.visitNode(converted, visitor, ts.isExpression);
            }
            function collidesWithParameterName(_a) {
                var name = _a.name;
                if (ts.isIdentifier(name)) {
                    return enclosingFunctionParameterNames.has(name.escapedText);
                }
                else {
                    for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
                        var element = _b[_i];
                        if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
                            return true;
                        }
                    }
                }
                return false;
            }
            function transformAsyncFunctionBody(node) {
                resumeLexicalEnvironment();
                var original = ts.getOriginalNode(node, ts.isFunctionLike);
                var nodeType = original.type;
                var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
                var isArrowFunction = node.kind === 195 /* ArrowFunction */;
                var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
                // An async function is emit as an outer function that calls an inner
                // generator function. To preserve lexical bindings, we pass the current
                // `this` and `arguments` objects to `__awaiter`. The generator function
                // passed to `__awaiter` is executed inside of the callback to the
                // promise constructor.
                var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
                enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
                for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
                    var parameter = _a[_i];
                    recordDeclarationName(parameter, enclosingFunctionParameterNames);
                }
                var result;
                if (!isArrowFunction) {
                    var statements = [];
                    var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
                    statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
                    ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                    var block = ts.createBlock(statements, /*multiLine*/ true);
                    ts.setTextRange(block, node.body);
                    // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
                    // This step isn't needed if we eventually transform this to ES5.
                    if (languageVersion >= 2 /* ES2015 */) {
                        if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
                            enableSubstitutionForAsyncMethodsWithSuper();
                            ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
                        }
                        else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
                            enableSubstitutionForAsyncMethodsWithSuper();
                            ts.addEmitHelper(block, ts.asyncSuperHelper);
                        }
                    }
                    result = block;
                }
                else {
                    var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
                    var declarations = endLexicalEnvironment();
                    if (ts.some(declarations)) {
                        var block = ts.convertToFunctionBody(expression);
                        result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
                    }
                    else {
                        result = expression;
                    }
                }
                enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
                return result;
            }
            function transformAsyncFunctionBodyWorker(body, start) {
                if (ts.isBlock(body)) {
                    return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
                }
                else {
                    return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
                }
            }
            function getPromiseConstructor(type) {
                var typeName = type && ts.getEntityNameFromTypeNode(type);
                if (typeName && ts.isEntityName(typeName)) {
                    var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
                    if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
                        || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
                        return typeName;
                    }
                }
                return undefined;
            }
            function enableSubstitutionForAsyncMethodsWithSuper() {
                if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
                    enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
                    // We need to enable substitutions for call, property access, and element access
                    // if we need to rewrite super calls.
                    context.enableSubstitution(189 /* CallExpression */);
                    context.enableSubstitution(187 /* PropertyAccessExpression */);
                    context.enableSubstitution(188 /* ElementAccessExpression */);
                    // We need to be notified when entering and exiting declarations that bind super.
                    context.enableEmitNotification(238 /* ClassDeclaration */);
                    context.enableEmitNotification(154 /* MethodDeclaration */);
                    context.enableEmitNotification(156 /* GetAccessor */);
                    context.enableEmitNotification(157 /* SetAccessor */);
                    context.enableEmitNotification(155 /* Constructor */);
                }
            }
            /**
             * Hook for node emit.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emit A callback used to emit the node in the printer.
             */
            function onEmitNode(hint, node, emitCallback) {
                // If we need to support substitutions for `super` in an async method,
                // we should track it here.
                if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
                    var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
                    if (superContainerFlags !== enclosingSuperContainerFlags) {
                        var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
                        enclosingSuperContainerFlags = superContainerFlags;
                        previousOnEmitNode(hint, node, emitCallback);
                        enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
                        return;
                    }
                }
                previousOnEmitNode(hint, node, emitCallback);
            }
            /**
             * Hooks node substitutions.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
                    return substituteExpression(node);
                }
                return node;
            }
            function substituteExpression(node) {
                switch (node.kind) {
                    case 187 /* PropertyAccessExpression */:
                        return substitutePropertyAccessExpression(node);
                    case 188 /* ElementAccessExpression */:
                        return substituteElementAccessExpression(node);
                    case 189 /* CallExpression */:
                        return substituteCallExpression(node);
                }
                return node;
            }
            function substitutePropertyAccessExpression(node) {
                if (node.expression.kind === 97 /* SuperKeyword */) {
                    return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node);
                }
                return node;
            }
            function substituteElementAccessExpression(node) {
                if (node.expression.kind === 97 /* SuperKeyword */) {
                    return createSuperAccessInAsyncMethod(node.argumentExpression, node);
                }
                return node;
            }
            function substituteCallExpression(node) {
                var expression = node.expression;
                if (ts.isSuperProperty(expression)) {
                    var argumentExpression = ts.isPropertyAccessExpression(expression)
                        ? substitutePropertyAccessExpression(expression)
                        : substituteElementAccessExpression(expression);
                    return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
                    /*typeArguments*/ undefined, [
                        ts.createThis()
                    ].concat(node.arguments));
                }
                return node;
            }
            function isSuperContainer(node) {
                var kind = node.kind;
                return kind === 238 /* ClassDeclaration */
                    || kind === 155 /* Constructor */
                    || kind === 154 /* MethodDeclaration */
                    || kind === 156 /* GetAccessor */
                    || kind === 157 /* SetAccessor */;
            }
            function createSuperAccessInAsyncMethod(argumentExpression, location) {
                if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
                    return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), 
                    /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
                }
                else {
                    return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), 
                    /*typeArguments*/ undefined, [argumentExpression]), location);
                }
            }
        }
        ts.transformES2017 = transformES2017;
        var awaiterHelper = {
            name: "typescript:awaiter",
            scoped: false,
            priority: 5,
            text: "\n            var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n                return new (P || (P = Promise))(function (resolve, reject) {\n                    function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n                    function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n                    function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n                    step((generator = generator.apply(thisArg, _arguments || [])).next());\n                });\n            };"
        };
        function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
            context.requestEmitHelper(awaiterHelper);
            var generatorFunc = ts.createFunctionExpression(
            /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), 
            /*name*/ undefined, 
            /*typeParameters*/ undefined, 
            /*parameters*/ [], 
            /*type*/ undefined, body);
            // Mark this node as originally an async function
            (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
            return ts.createCall(ts.getHelperName("__awaiter"), 
            /*typeArguments*/ undefined, [
                ts.createThis(),
                hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
                promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
                generatorFunc
            ]);
        }
        ts.asyncSuperHelper = {
            name: "typescript:async-super",
            scoped: true,
            text: ts.helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_super")
        };
        ts.advancedAsyncSuperHelper = {
            name: "typescript:advanced-async-super",
            scoped: true,
            text: ts.helperString(__makeTemplateObject(["\n            const ", " = (function (geti, seti) {\n                const cache = Object.create(null);\n                return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n            })(name => super[name], (name, value) => super[name] = value);"], ["\n            const ", " = (function (geti, seti) {\n                const cache = Object.create(null);\n                return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n            })(name => super[name], (name, value) => super[name] = value);"]), "_super")
        };
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        var ESNextSubstitutionFlags;
        (function (ESNextSubstitutionFlags) {
            /** Enables substitutions for async methods with `super` calls. */
            ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
        })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
        function transformESNext(context) {
            var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
            var resolver = context.getEmitResolver();
            var compilerOptions = context.getCompilerOptions();
            var languageVersion = ts.getEmitScriptTarget(compilerOptions);
            var previousOnEmitNode = context.onEmitNode;
            context.onEmitNode = onEmitNode;
            var previousOnSubstituteNode = context.onSubstituteNode;
            context.onSubstituteNode = onSubstituteNode;
            var enabledSubstitutions;
            var enclosingFunctionFlags;
            var enclosingSuperContainerFlags = 0;
            return ts.chainBundle(transformSourceFile);
            function transformSourceFile(node) {
                if (node.isDeclarationFile) {
                    return node;
                }
                var visited = ts.visitEachChild(node, visitor, context);
                ts.addEmitHelpers(visited, context.readEmitHelpers());
                return visited;
            }
            function visitor(node) {
                return visitorWorker(node, /*noDestructuringValue*/ false);
            }
            function visitorNoDestructuringValue(node) {
                return visitorWorker(node, /*noDestructuringValue*/ true);
            }
            function visitorNoAsyncModifier(node) {
                if (node.kind === 120 /* AsyncKeyword */) {
                    return undefined;
                }
                return node;
            }
            function visitorWorker(node, noDestructuringValue) {
                if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
                    return node;
                }
                switch (node.kind) {
                    case 199 /* AwaitExpression */:
                        return visitAwaitExpression(node);
                    case 205 /* YieldExpression */:
                        return visitYieldExpression(node);
                    case 228 /* ReturnStatement */:
                        return visitReturnStatement(node);
                    case 231 /* LabeledStatement */:
                        return visitLabeledStatement(node);
                    case 186 /* ObjectLiteralExpression */:
                        return visitObjectLiteralExpression(node);
                    case 202 /* BinaryExpression */:
                        return visitBinaryExpression(node, noDestructuringValue);
                    case 235 /* VariableDeclaration */:
                        return visitVariableDeclaration(node);
                    case 225 /* ForOfStatement */:
                        return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
                    case 223 /* ForStatement */:
                        return visitForStatement(node);
                    case 198 /* VoidExpression */:
                        return visitVoidExpression(node);
                    case 155 /* Constructor */:
                        return visitConstructorDeclaration(node);
                    case 154 /* MethodDeclaration */:
                        return visitMethodDeclaration(node);
                    case 156 /* GetAccessor */:
                        return visitGetAccessorDeclaration(node);
                    case 157 /* SetAccessor */:
                        return visitSetAccessorDeclaration(node);
                    case 237 /* FunctionDeclaration */:
                        return visitFunctionDeclaration(node);
                    case 194 /* FunctionExpression */:
                        return visitFunctionExpression(node);
                    case 195 /* ArrowFunction */:
                        return visitArrowFunction(node);
                    case 149 /* Parameter */:
                        return visitParameter(node);
                    case 219 /* ExpressionStatement */:
                        return visitExpressionStatement(node);
                    case 193 /* ParenthesizedExpression */:
                        return visitParenthesizedExpression(node, noDestructuringValue);
                    case 272 /* CatchClause */:
                        return visitCatchClause(node);
                    default:
                        return ts.visitEachChild(node, visitor, context);
                }
            }
            function visitAwaitExpression(node) {
                if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
                    return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), 
                    /*location*/ node), node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitYieldExpression(node) {
                if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
                    if (node.asteriskToken) {
                        var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
                        return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
                    }
                    return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
                        ? ts.visitNode(node.expression, visitor, ts.isExpression)
                        : ts.createVoidZero())), node), node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitReturnStatement(node) {
                if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
                    return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitLabeledStatement(node) {
                if (enclosingFunctionFlags & 2 /* Async */) {
                    var statement = ts.unwrapInnermostStatementOfLabel(node);
                    if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) {
                        return visitForOfStatement(statement, node);
                    }
                    return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function chunkObjectLiteralElements(elements) {
                var chunkObject;
                var objects = [];
                for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
                    var e = elements_4[_i];
                    if (e.kind === 275 /* SpreadAssignment */) {
                        if (chunkObject) {
                            objects.push(ts.createObjectLiteral(chunkObject));
                            chunkObject = undefined;
                        }
                        var target = e.expression;
                        objects.push(ts.visitNode(target, visitor, ts.isExpression));
                    }
                    else {
                        chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */
                            ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
                            : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
                    }
                }
                if (chunkObject) {
                    objects.push(ts.createObjectLiteral(chunkObject));
                }
                return objects;
            }
            function visitObjectLiteralExpression(node) {
                if (node.transformFlags & 1048576 /* ContainsObjectSpread */) {
                    // spread elements emit like so:
                    // non-spread elements are chunked together into object literals, and then all are passed to __assign:
                    //     { a, ...o, b } => __assign({a}, o, {b});
                    // If the first element is a spread element, then the first argument to __assign is {}:
                    //     { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2)
                    var objects = chunkObjectLiteralElements(node.properties);
                    if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) {
                        objects.unshift(ts.createObjectLiteral());
                    }
                    return createAssignHelper(context, objects);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitExpressionStatement(node) {
                return ts.visitEachChild(node, visitorNoDestructuringValue, context);
            }
            function visitParenthesizedExpression(node, noDestructuringValue) {
                return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
            }
            function visitCatchClause(node) {
                if (!node.variableDeclaration) {
                    return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a BinaryExpression that contains a destructuring assignment.
             *
             * @param node A BinaryExpression node.
             */
            function visitBinaryExpression(node, noDestructuringValue) {
                if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) {
                    return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
                }
                else if (node.operatorToken.kind === 26 /* CommaToken */) {
                    return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a VariableDeclaration node with a binding pattern.
             *
             * @param node A VariableDeclaration node.
             */
            function visitVariableDeclaration(node) {
                // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
                if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) {
                    return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitForStatement(node) {
                return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
            }
            function visitVoidExpression(node) {
                return ts.visitEachChild(node, visitorNoDestructuringValue, context);
            }
            /**
             * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
             *
             * @param node A ForOfStatement.
             */
            function visitForOfStatement(node, outermostLabeledStatement) {
                if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) {
                    node = transformForOfStatementWithObjectRest(node);
                }
                if (node.awaitModifier) {
                    return transformForAwaitOfStatement(node, outermostLabeledStatement);
                }
                else {
                    return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
                }
            }
            function transformForOfStatementWithObjectRest(node) {
                var initializerWithoutParens = ts.skipParentheses(node.initializer);
                if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
                    var bodyLocation = void 0;
                    var statementsLocation = void 0;
                    var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
                    var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
                    if (ts.isBlock(node.statement)) {
                        ts.addRange(statements, node.statement.statements);
                        bodyLocation = node.statement;
                        statementsLocation = node.statement.statements;
                    }
                    else if (node.statement) {
                        ts.append(statements, node.statement);
                        bodyLocation = node.statement;
                        statementsLocation = node.statement;
                    }
                    return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
                        ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
                    ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
                    /*multiLine*/ true), bodyLocation));
                }
                return node;
            }
            function convertForOfStatementHead(node, boundValue) {
                var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
                var bodyLocation;
                var statementsLocation;
                var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
                var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
                if (ts.isBlock(statement)) {
                    ts.addRange(statements, statement.statements);
                    bodyLocation = statement;
                    statementsLocation = statement.statements;
                }
                else {
                    statements.push(statement);
                }
                return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
                /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
            }
            function createDownlevelAwait(expression) {
                return enclosingFunctionFlags & 1 /* Generator */
                    ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
                    : ts.createAwait(expression);
            }
            function transformForAwaitOfStatement(node, outermostLabeledStatement) {
                var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
                var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
                var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
                var errorRecord = ts.createUniqueName("e");
                var catchVariable = ts.getGeneratedNameForNode(errorRecord);
                var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
                var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
                var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
                var getDone = ts.createPropertyAccess(result, "done");
                var getValue = ts.createPropertyAccess(result, "value");
                var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
                hoistVariableDeclaration(errorRecord);
                hoistVariableDeclaration(returnMethod);
                var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
                /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
                    ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression),
                    ts.createVariableDeclaration(result)
                ]), node.expression), 2097152 /* NoHoisting */), 
                /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), 
                /*incrementor*/ undefined, 
                /*statement*/ convertForOfStatementHead(node, getValue)), 
                /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
                return ts.createTry(ts.createBlock([
                    ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
                ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
                    ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
                        ts.createPropertyAssignment("error", catchVariable)
                    ])))
                ]), 1 /* SingleLine */)), ts.createBlock([
                    ts.createTry(
                    /*tryBlock*/ ts.createBlock([
                        ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)
                    ]), 
                    /*catchClause*/ undefined, 
                    /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
                        ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
                    ]), 1 /* SingleLine */))
                ]));
            }
            function visitParameter(node) {
                if (node.transformFlags & 1048576 /* ContainsObjectRest */) {
                    // Binding patterns are converted into a generated name and are
                    // evaluated inside the function body.
                    return ts.updateParameter(node, 
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), 
                    /*questionToken*/ undefined, 
                    /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitConstructorDeclaration(node) {
                var savedEnclosingFunctionFlags = enclosingFunctionFlags;
                enclosingFunctionFlags = 0 /* Normal */;
                var updated = ts.updateConstructor(node, 
                /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
                enclosingFunctionFlags = savedEnclosingFunctionFlags;
                return updated;
            }
            function visitGetAccessorDeclaration(node) {
                var savedEnclosingFunctionFlags = enclosingFunctionFlags;
                enclosingFunctionFlags = 0 /* Normal */;
                var updated = ts.updateGetAccessor(node, 
                /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, transformFunctionBody(node));
                enclosingFunctionFlags = savedEnclosingFunctionFlags;
                return updated;
            }
            function visitSetAccessorDeclaration(node) {
                var savedEnclosingFunctionFlags = enclosingFunctionFlags;
                enclosingFunctionFlags = 0 /* Normal */;
                var updated = ts.updateSetAccessor(node, 
                /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
                enclosingFunctionFlags = savedEnclosingFunctionFlags;
                return updated;
            }
            function visitMethodDeclaration(node) {
                var savedEnclosingFunctionFlags = enclosingFunctionFlags;
                enclosingFunctionFlags = ts.getFunctionFlags(node);
                var updated = ts.updateMethod(node, 
                /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
                    ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
                    : node.modifiers, enclosingFunctionFlags & 2 /* Async */
                    ? undefined
                    : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
                    ? transformAsyncGeneratorFunctionBody(node)
                    : transformFunctionBody(node));
                enclosingFunctionFlags = savedEnclosingFunctionFlags;
                return updated;
            }
            function visitFunctionDeclaration(node) {
                var savedEnclosingFunctionFlags = enclosingFunctionFlags;
                enclosingFunctionFlags = ts.getFunctionFlags(node);
                var updated = ts.updateFunctionDeclaration(node, 
                /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
                    ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
                    : node.modifiers, enclosingFunctionFlags & 2 /* Async */
                    ? undefined
                    : node.asteriskToken, node.name, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
                    ? transformAsyncGeneratorFunctionBody(node)
                    : transformFunctionBody(node));
                enclosingFunctionFlags = savedEnclosingFunctionFlags;
                return updated;
            }
            function visitArrowFunction(node) {
                var savedEnclosingFunctionFlags = enclosingFunctionFlags;
                enclosingFunctionFlags = ts.getFunctionFlags(node);
                var updated = ts.updateArrowFunction(node, node.modifiers, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
                enclosingFunctionFlags = savedEnclosingFunctionFlags;
                return updated;
            }
            function visitFunctionExpression(node) {
                var savedEnclosingFunctionFlags = enclosingFunctionFlags;
                enclosingFunctionFlags = ts.getFunctionFlags(node);
                var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
                    ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
                    : node.modifiers, enclosingFunctionFlags & 2 /* Async */
                    ? undefined
                    : node.asteriskToken, node.name, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
                    ? transformAsyncGeneratorFunctionBody(node)
                    : transformFunctionBody(node));
                enclosingFunctionFlags = savedEnclosingFunctionFlags;
                return updated;
            }
            function transformAsyncGeneratorFunctionBody(node) {
                resumeLexicalEnvironment();
                var statements = [];
                var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
                appendObjectRestAssignmentsIfNeeded(statements, node);
                statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
                /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), 
                /*typeParameters*/ undefined, 
                /*parameters*/ [], 
                /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))));
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                var block = ts.updateBlock(node.body, statements);
                // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
                // This step isn't needed if we eventually transform this to ES5.
                if (languageVersion >= 2 /* ES2015 */) {
                    if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
                        enableSubstitutionForAsyncMethodsWithSuper();
                        ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
                    }
                    else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
                        enableSubstitutionForAsyncMethodsWithSuper();
                        ts.addEmitHelper(block, ts.asyncSuperHelper);
                    }
                }
                return block;
            }
            function transformFunctionBody(node) {
                resumeLexicalEnvironment();
                var statementOffset = 0;
                var statements = [];
                var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
                if (ts.isBlock(body)) {
                    statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
                }
                ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
                var leadingStatements = endLexicalEnvironment();
                if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
                    var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
                    ts.addStatementsAfterPrologue(statements, leadingStatements);
                    ts.addRange(statements, block.statements.slice(statementOffset));
                    return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
                }
                return body;
            }
            function appendObjectRestAssignmentsIfNeeded(statements, node) {
                for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
                    var parameter = _a[_i];
                    if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) {
                        var temp = ts.getGeneratedNameForNode(parameter);
                        var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
                        /*doNotRecordTempVariablesInLine*/ false, 
                        /*skipInitializer*/ true);
                        if (ts.some(declarations)) {
                            var statement = ts.createVariableStatement(
                            /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
                            ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
                            statements = ts.append(statements, statement);
                        }
                    }
                }
                return statements;
            }
            function enableSubstitutionForAsyncMethodsWithSuper() {
                if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
                    enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
                    // We need to enable substitutions for call, property access, and element access
                    // if we need to rewrite super calls.
                    context.enableSubstitution(189 /* CallExpression */);
                    context.enableSubstitution(187 /* PropertyAccessExpression */);
                    context.enableSubstitution(188 /* ElementAccessExpression */);
                    // We need to be notified when entering and exiting declarations that bind super.
                    context.enableEmitNotification(238 /* ClassDeclaration */);
                    context.enableEmitNotification(154 /* MethodDeclaration */);
                    context.enableEmitNotification(156 /* GetAccessor */);
                    context.enableEmitNotification(157 /* SetAccessor */);
                    context.enableEmitNotification(155 /* Constructor */);
                }
            }
            /**
             * Called by the printer just before a node is printed.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to be printed.
             * @param emitCallback The callback used to emit the node.
             */
            function onEmitNode(hint, node, emitCallback) {
                // If we need to support substitutions for `super` in an async method,
                // we should track it here.
                if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
                    var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
                    if (superContainerFlags !== enclosingSuperContainerFlags) {
                        var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
                        enclosingSuperContainerFlags = superContainerFlags;
                        previousOnEmitNode(hint, node, emitCallback);
                        enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
                        return;
                    }
                }
                previousOnEmitNode(hint, node, emitCallback);
            }
            /**
             * Hooks node substitutions.
             *
             * @param hint The context for the emitter.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
                    return substituteExpression(node);
                }
                return node;
            }
            function substituteExpression(node) {
                switch (node.kind) {
                    case 187 /* PropertyAccessExpression */:
                        return substitutePropertyAccessExpression(node);
                    case 188 /* ElementAccessExpression */:
                        return substituteElementAccessExpression(node);
                    case 189 /* CallExpression */:
                        return substituteCallExpression(node);
                }
                return node;
            }
            function substitutePropertyAccessExpression(node) {
                if (node.expression.kind === 97 /* SuperKeyword */) {
                    return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node);
                }
                return node;
            }
            function substituteElementAccessExpression(node) {
                if (node.expression.kind === 97 /* SuperKeyword */) {
                    return createSuperAccessInAsyncMethod(node.argumentExpression, node);
                }
                return node;
            }
            function substituteCallExpression(node) {
                var expression = node.expression;
                if (ts.isSuperProperty(expression)) {
                    var argumentExpression = ts.isPropertyAccessExpression(expression)
                        ? substitutePropertyAccessExpression(expression)
                        : substituteElementAccessExpression(expression);
                    return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
                    /*typeArguments*/ undefined, [
                        ts.createThis()
                    ].concat(node.arguments));
                }
                return node;
            }
            function isSuperContainer(node) {
                var kind = node.kind;
                return kind === 238 /* ClassDeclaration */
                    || kind === 155 /* Constructor */
                    || kind === 154 /* MethodDeclaration */
                    || kind === 156 /* GetAccessor */
                    || kind === 157 /* SetAccessor */;
            }
            function createSuperAccessInAsyncMethod(argumentExpression, location) {
                if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
                    return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), 
                    /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
                }
                else {
                    return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), 
                    /*typeArguments*/ undefined, [argumentExpression]), location);
                }
            }
        }
        ts.transformESNext = transformESNext;
        var assignHelper = {
            name: "typescript:assign",
            scoped: false,
            priority: 1,
            text: "\n            var __assign = (this && this.__assign) || function () {\n                __assign = Object.assign || function(t) {\n                    for (var s, i = 1, n = arguments.length; i < n; i++) {\n                        s = arguments[i];\n                        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n                            t[p] = s[p];\n                    }\n                    return t;\n                };\n                return __assign.apply(this, arguments);\n            };"
        };
        function createAssignHelper(context, attributesSegments) {
            if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
                return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), 
                /*typeArguments*/ undefined, attributesSegments);
            }
            context.requestEmitHelper(assignHelper);
            return ts.createCall(ts.getHelperName("__assign"), 
            /*typeArguments*/ undefined, attributesSegments);
        }
        ts.createAssignHelper = createAssignHelper;
        var awaitHelper = {
            name: "typescript:await",
            scoped: false,
            text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
        };
        function createAwaitHelper(context, expression) {
            context.requestEmitHelper(awaitHelper);
            return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
        }
        var asyncGeneratorHelper = {
            name: "typescript:asyncGenerator",
            scoped: false,
            text: "\n            var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n                if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n                var g = generator.apply(thisArg, _arguments || []), i, q = [];\n                return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n                function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n                function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n                function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n                function fulfill(value) { resume(\"next\", value); }\n                function reject(value) { resume(\"throw\", value); }\n                function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n            };"
        };
        function createAsyncGeneratorHelper(context, generatorFunc) {
            context.requestEmitHelper(awaitHelper);
            context.requestEmitHelper(asyncGeneratorHelper);
            // Mark this node as originally an async function
            (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
            return ts.createCall(ts.getHelperName("__asyncGenerator"), 
            /*typeArguments*/ undefined, [
                ts.createThis(),
                ts.createIdentifier("arguments"),
                generatorFunc
            ]);
        }
        var asyncDelegator = {
            name: "typescript:asyncDelegator",
            scoped: false,
            text: "\n            var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n                var i, p;\n                return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n                function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n            };"
        };
        function createAsyncDelegatorHelper(context, expression, location) {
            context.requestEmitHelper(awaitHelper);
            context.requestEmitHelper(asyncDelegator);
            return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), 
            /*typeArguments*/ undefined, [expression]), location);
        }
        var asyncValues = {
            name: "typescript:asyncValues",
            scoped: false,
            text: "\n            var __asyncValues = (this && this.__asyncValues) || function (o) {\n                if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n                var m = o[Symbol.asyncIterator], i;\n                return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n                function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n                function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n            };"
        };
        function createAsyncValuesHelper(context, expression, location) {
            context.requestEmitHelper(asyncValues);
            return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), 
            /*typeArguments*/ undefined, [expression]), location);
        }
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function transformJsx(context) {
            var compilerOptions = context.getCompilerOptions();
            var currentSourceFile;
            return ts.chainBundle(transformSourceFile);
            /**
             * Transform JSX-specific syntax in a SourceFile.
             *
             * @param node A SourceFile node.
             */
            function transformSourceFile(node) {
                if (node.isDeclarationFile) {
                    return node;
                }
                currentSourceFile = node;
                var visited = ts.visitEachChild(node, visitor, context);
                ts.addEmitHelpers(visited, context.readEmitHelpers());
                return visited;
            }
            function visitor(node) {
                if (node.transformFlags & 4 /* ContainsJsx */) {
                    return visitorWorker(node);
                }
                else {
                    return node;
                }
            }
            function visitorWorker(node) {
                switch (node.kind) {
                    case 258 /* JsxElement */:
                        return visitJsxElement(node, /*isChild*/ false);
                    case 259 /* JsxSelfClosingElement */:
                        return visitJsxSelfClosingElement(node, /*isChild*/ false);
                    case 262 /* JsxFragment */:
                        return visitJsxFragment(node, /*isChild*/ false);
                    case 268 /* JsxExpression */:
                        return visitJsxExpression(node);
                    default:
                        return ts.visitEachChild(node, visitor, context);
                }
            }
            function transformJsxChildToExpression(node) {
                switch (node.kind) {
                    case 10 /* JsxText */:
                        return visitJsxText(node);
                    case 268 /* JsxExpression */:
                        return visitJsxExpression(node);
                    case 258 /* JsxElement */:
                        return visitJsxElement(node, /*isChild*/ true);
                    case 259 /* JsxSelfClosingElement */:
                        return visitJsxSelfClosingElement(node, /*isChild*/ true);
                    case 262 /* JsxFragment */:
                        return visitJsxFragment(node, /*isChild*/ true);
                    default:
                        return ts.Debug.failBadSyntaxKind(node);
                }
            }
            function visitJsxElement(node, isChild) {
                return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
            }
            function visitJsxSelfClosingElement(node, isChild) {
                return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
            }
            function visitJsxFragment(node, isChild) {
                return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
            }
            function visitJsxOpeningLikeElement(node, children, isChild, location) {
                var tagName = getTagName(node);
                var objectProperties;
                var attrs = node.attributes.properties;
                if (attrs.length === 0) {
                    // When there are no attributes, React wants "null"
                    objectProperties = ts.createNull();
                }
                else {
                    // Map spans of JsxAttribute nodes into object literals and spans
                    // of JsxSpreadAttribute nodes into expressions.
                    var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) {
                        return isSpread
                            ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
                            : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement));
                    }));
                    if (ts.isJsxSpreadAttribute(attrs[0])) {
                        // We must always emit at least one object literal before a spread
                        // argument.
                        segments.unshift(ts.createObjectLiteral());
                    }
                    // Either emit one big object literal (no spread attribs), or
                    // a call to the __assign helper.
                    objectProperties = ts.singleOrUndefined(segments);
                    if (!objectProperties) {
                        objectProperties = ts.createAssignHelper(context, segments);
                    }
                }
                var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
                tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
                if (isChild) {
                    ts.startOnNewLine(element);
                }
                return element;
            }
            function visitJsxOpeningFragment(node, children, isChild, location) {
                var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
                ts.mapDefined(children, transformJsxChildToExpression), node, location);
                if (isChild) {
                    ts.startOnNewLine(element);
                }
                return element;
            }
            function transformJsxSpreadAttributeToExpression(node) {
                return ts.visitNode(node.expression, visitor, ts.isExpression);
            }
            function transformJsxAttributeToObjectLiteralElement(node) {
                var name = getAttributeName(node);
                var expression = transformJsxAttributeInitializer(node.initializer);
                return ts.createPropertyAssignment(name, expression);
            }
            function transformJsxAttributeInitializer(node) {
                if (node === undefined) {
                    return ts.createTrue();
                }
                else if (node.kind === 9 /* StringLiteral */) {
                    // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
                    // Need to be escaped to be handled correctly in a normal string
                    var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
                    literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
                    return ts.setTextRange(literal, node);
                }
                else if (node.kind === 268 /* JsxExpression */) {
                    if (node.expression === undefined) {
                        return ts.createTrue();
                    }
                    return visitJsxExpression(node);
                }
                else {
                    return ts.Debug.failBadSyntaxKind(node);
                }
            }
            function visitJsxText(node) {
                var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
                return fixed === undefined ? undefined : ts.createLiteral(fixed);
            }
            /**
             * JSX trims whitespace at the end and beginning of lines, except that the
             * start/end of a tag is considered a start/end of a line only if that line is
             * on the same line as the closing tag. See examples in
             * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
             * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model
             *
             * An equivalent algorithm would be:
             * - If there is only one line, return it.
             * - If there is only whitespace (but multiple lines), return `undefined`.
             * - Split the text into lines.
             * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
             * - Decode entities on each line (individually).
             * - Remove empty lines and join the rest with " ".
             */
            function fixupWhitespaceAndDecodeEntities(text) {
                var acc;
                // First non-whitespace character on this line.
                var firstNonWhitespace = 0;
                // Last non-whitespace character on this line.
                var lastNonWhitespace = -1;
                // These initial values are special because the first line is:
                // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
                // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
                for (var i = 0; i < text.length; i++) {
                    var c = text.charCodeAt(i);
                    if (ts.isLineBreak(c)) {
                        // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
                        // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
                        if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
                            acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
                        }
                        // Reset firstNonWhitespace for the next line.
                        // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
                        firstNonWhitespace = -1;
                    }
                    else if (!ts.isWhiteSpaceSingleLine(c)) {
                        lastNonWhitespace = i;
                        if (firstNonWhitespace === -1) {
                            firstNonWhitespace = i;
                        }
                    }
                }
                return firstNonWhitespace !== -1
                    // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
                    ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
                    // Last line was all whitespace, so ignore it
                    : acc;
            }
            function addLineOfJsxText(acc, trimmedLine) {
                // We do not escape the string here as that is handled by the printer
                // when it emits the literal. We do, however, need to decode JSX entities.
                var decoded = decodeEntities(trimmedLine);
                return acc === undefined ? decoded : acc + " " + decoded;
            }
            /**
             * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
             * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
             */
            function decodeEntities(text) {
                return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
                    if (decimal) {
                        return String.fromCharCode(parseInt(decimal, 10));
                    }
                    else if (hex) {
                        return String.fromCharCode(parseInt(hex, 16));
                    }
                    else {
                        var ch = entities.get(word);
                        // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
                        return ch ? String.fromCharCode(ch) : match;
                    }
                });
            }
            /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
            function tryDecodeEntities(text) {
                var decoded = decodeEntities(text);
                return decoded === text ? undefined : decoded;
            }
            function getTagName(node) {
                if (node.kind === 258 /* JsxElement */) {
                    return getTagName(node.openingElement);
                }
                else {
                    var name = node.tagName;
                    if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
                        return ts.createLiteral(ts.idText(name));
                    }
                    else {
                        return ts.createExpressionFromEntityName(name);
                    }
                }
            }
            /**
             * Emit an attribute name, which is quoted if it needs to be quoted. Because
             * these emit into an object literal property name, we don't need to be worried
             * about keywords, just non-identifier characters
             */
            function getAttributeName(node) {
                var name = node.name;
                var text = ts.idText(name);
                if (/^[A-Za-z_]\w*$/.test(text)) {
                    return name;
                }
                else {
                    return ts.createLiteral(text);
                }
            }
            function visitJsxExpression(node) {
                return ts.visitNode(node.expression, visitor, ts.isExpression);
            }
        }
        ts.transformJsx = transformJsx;
        var entities = ts.createMapFromTemplate({
            quot: 0x0022,
            amp: 0x0026,
            apos: 0x0027,
            lt: 0x003C,
            gt: 0x003E,
            nbsp: 0x00A0,
            iexcl: 0x00A1,
            cent: 0x00A2,
            pound: 0x00A3,
            curren: 0x00A4,
            yen: 0x00A5,
            brvbar: 0x00A6,
            sect: 0x00A7,
            uml: 0x00A8,
            copy: 0x00A9,
            ordf: 0x00AA,
            laquo: 0x00AB,
            not: 0x00AC,
            shy: 0x00AD,
            reg: 0x00AE,
            macr: 0x00AF,
            deg: 0x00B0,
            plusmn: 0x00B1,
            sup2: 0x00B2,
            sup3: 0x00B3,
            acute: 0x00B4,
            micro: 0x00B5,
            para: 0x00B6,
            middot: 0x00B7,
            cedil: 0x00B8,
            sup1: 0x00B9,
            ordm: 0x00BA,
            raquo: 0x00BB,
            frac14: 0x00BC,
            frac12: 0x00BD,
            frac34: 0x00BE,
            iquest: 0x00BF,
            Agrave: 0x00C0,
            Aacute: 0x00C1,
            Acirc: 0x00C2,
            Atilde: 0x00C3,
            Auml: 0x00C4,
            Aring: 0x00C5,
            AElig: 0x00C6,
            Ccedil: 0x00C7,
            Egrave: 0x00C8,
            Eacute: 0x00C9,
            Ecirc: 0x00CA,
            Euml: 0x00CB,
            Igrave: 0x00CC,
            Iacute: 0x00CD,
            Icirc: 0x00CE,
            Iuml: 0x00CF,
            ETH: 0x00D0,
            Ntilde: 0x00D1,
            Ograve: 0x00D2,
            Oacute: 0x00D3,
            Ocirc: 0x00D4,
            Otilde: 0x00D5,
            Ouml: 0x00D6,
            times: 0x00D7,
            Oslash: 0x00D8,
            Ugrave: 0x00D9,
            Uacute: 0x00DA,
            Ucirc: 0x00DB,
            Uuml: 0x00DC,
            Yacute: 0x00DD,
            THORN: 0x00DE,
            szlig: 0x00DF,
            agrave: 0x00E0,
            aacute: 0x00E1,
            acirc: 0x00E2,
            atilde: 0x00E3,
            auml: 0x00E4,
            aring: 0x00E5,
            aelig: 0x00E6,
            ccedil: 0x00E7,
            egrave: 0x00E8,
            eacute: 0x00E9,
            ecirc: 0x00EA,
            euml: 0x00EB,
            igrave: 0x00EC,
            iacute: 0x00ED,
            icirc: 0x00EE,
            iuml: 0x00EF,
            eth: 0x00F0,
            ntilde: 0x00F1,
            ograve: 0x00F2,
            oacute: 0x00F3,
            ocirc: 0x00F4,
            otilde: 0x00F5,
            ouml: 0x00F6,
            divide: 0x00F7,
            oslash: 0x00F8,
            ugrave: 0x00F9,
            uacute: 0x00FA,
            ucirc: 0x00FB,
            uuml: 0x00FC,
            yacute: 0x00FD,
            thorn: 0x00FE,
            yuml: 0x00FF,
            OElig: 0x0152,
            oelig: 0x0153,
            Scaron: 0x0160,
            scaron: 0x0161,
            Yuml: 0x0178,
            fnof: 0x0192,
            circ: 0x02C6,
            tilde: 0x02DC,
            Alpha: 0x0391,
            Beta: 0x0392,
            Gamma: 0x0393,
            Delta: 0x0394,
            Epsilon: 0x0395,
            Zeta: 0x0396,
            Eta: 0x0397,
            Theta: 0x0398,
            Iota: 0x0399,
            Kappa: 0x039A,
            Lambda: 0x039B,
            Mu: 0x039C,
            Nu: 0x039D,
            Xi: 0x039E,
            Omicron: 0x039F,
            Pi: 0x03A0,
            Rho: 0x03A1,
            Sigma: 0x03A3,
            Tau: 0x03A4,
            Upsilon: 0x03A5,
            Phi: 0x03A6,
            Chi: 0x03A7,
            Psi: 0x03A8,
            Omega: 0x03A9,
            alpha: 0x03B1,
            beta: 0x03B2,
            gamma: 0x03B3,
            delta: 0x03B4,
            epsilon: 0x03B5,
            zeta: 0x03B6,
            eta: 0x03B7,
            theta: 0x03B8,
            iota: 0x03B9,
            kappa: 0x03BA,
            lambda: 0x03BB,
            mu: 0x03BC,
            nu: 0x03BD,
            xi: 0x03BE,
            omicron: 0x03BF,
            pi: 0x03C0,
            rho: 0x03C1,
            sigmaf: 0x03C2,
            sigma: 0x03C3,
            tau: 0x03C4,
            upsilon: 0x03C5,
            phi: 0x03C6,
            chi: 0x03C7,
            psi: 0x03C8,
            omega: 0x03C9,
            thetasym: 0x03D1,
            upsih: 0x03D2,
            piv: 0x03D6,
            ensp: 0x2002,
            emsp: 0x2003,
            thinsp: 0x2009,
            zwnj: 0x200C,
            zwj: 0x200D,
            lrm: 0x200E,
            rlm: 0x200F,
            ndash: 0x2013,
            mdash: 0x2014,
            lsquo: 0x2018,
            rsquo: 0x2019,
            sbquo: 0x201A,
            ldquo: 0x201C,
            rdquo: 0x201D,
            bdquo: 0x201E,
            dagger: 0x2020,
            Dagger: 0x2021,
            bull: 0x2022,
            hellip: 0x2026,
            permil: 0x2030,
            prime: 0x2032,
            Prime: 0x2033,
            lsaquo: 0x2039,
            rsaquo: 0x203A,
            oline: 0x203E,
            frasl: 0x2044,
            euro: 0x20AC,
            image: 0x2111,
            weierp: 0x2118,
            real: 0x211C,
            trade: 0x2122,
            alefsym: 0x2135,
            larr: 0x2190,
            uarr: 0x2191,
            rarr: 0x2192,
            darr: 0x2193,
            harr: 0x2194,
            crarr: 0x21B5,
            lArr: 0x21D0,
            uArr: 0x21D1,
            rArr: 0x21D2,
            dArr: 0x21D3,
            hArr: 0x21D4,
            forall: 0x2200,
            part: 0x2202,
            exist: 0x2203,
            empty: 0x2205,
            nabla: 0x2207,
            isin: 0x2208,
            notin: 0x2209,
            ni: 0x220B,
            prod: 0x220F,
            sum: 0x2211,
            minus: 0x2212,
            lowast: 0x2217,
            radic: 0x221A,
            prop: 0x221D,
            infin: 0x221E,
            ang: 0x2220,
            and: 0x2227,
            or: 0x2228,
            cap: 0x2229,
            cup: 0x222A,
            int: 0x222B,
            there4: 0x2234,
            sim: 0x223C,
            cong: 0x2245,
            asymp: 0x2248,
            ne: 0x2260,
            equiv: 0x2261,
            le: 0x2264,
            ge: 0x2265,
            sub: 0x2282,
            sup: 0x2283,
            nsub: 0x2284,
            sube: 0x2286,
            supe: 0x2287,
            oplus: 0x2295,
            otimes: 0x2297,
            perp: 0x22A5,
            sdot: 0x22C5,
            lceil: 0x2308,
            rceil: 0x2309,
            lfloor: 0x230A,
            rfloor: 0x230B,
            lang: 0x2329,
            rang: 0x232A,
            loz: 0x25CA,
            spades: 0x2660,
            clubs: 0x2663,
            hearts: 0x2665,
            diams: 0x2666
        });
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function transformES2016(context) {
            var hoistVariableDeclaration = context.hoistVariableDeclaration;
            return ts.chainBundle(transformSourceFile);
            function transformSourceFile(node) {
                if (node.isDeclarationFile) {
                    return node;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitor(node) {
                if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
                    return node;
                }
                switch (node.kind) {
                    case 202 /* BinaryExpression */:
                        return visitBinaryExpression(node);
                    default:
                        return ts.visitEachChild(node, visitor, context);
                }
            }
            function visitBinaryExpression(node) {
                switch (node.operatorToken.kind) {
                    case 62 /* AsteriskAsteriskEqualsToken */:
                        return visitExponentiationAssignmentExpression(node);
                    case 40 /* AsteriskAsteriskToken */:
                        return visitExponentiationExpression(node);
                    default:
                        return ts.visitEachChild(node, visitor, context);
                }
            }
            function visitExponentiationAssignmentExpression(node) {
                var target;
                var value;
                var left = ts.visitNode(node.left, visitor, ts.isExpression);
                var right = ts.visitNode(node.right, visitor, ts.isExpression);
                if (ts.isElementAccessExpression(left)) {
                    // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
                    var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
                    var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
                    target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
                    value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
                }
                else if (ts.isPropertyAccessExpression(left)) {
                    // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
                    var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
                    target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
                    value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
                }
                else {
                    // Transforms `a **= b` into `a = Math.pow(a, b)`
                    target = left;
                    value = left;
                }
                return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
            }
            function visitExponentiationExpression(node) {
                // Transforms `a ** b` into `Math.pow(a, b)`
                var left = ts.visitNode(node.left, visitor, ts.isExpression);
                var right = ts.visitNode(node.right, visitor, ts.isExpression);
                return ts.createMathPow(left, right, /*location*/ node);
            }
        }
        ts.transformES2016 = transformES2016;
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        var ES2015SubstitutionFlags;
        (function (ES2015SubstitutionFlags) {
            /** Enables substitutions for captured `this` */
            ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
            /** Enables substitutions for block-scoped bindings. */
            ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
        })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
        var CopyDirection;
        (function (CopyDirection) {
            CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
            CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
        })(CopyDirection || (CopyDirection = {}));
        var Jump;
        (function (Jump) {
            Jump[Jump["Break"] = 2] = "Break";
            Jump[Jump["Continue"] = 4] = "Continue";
            Jump[Jump["Return"] = 8] = "Return";
        })(Jump || (Jump = {}));
        var SuperCaptureResult;
        (function (SuperCaptureResult) {
            /**
             * A capture may have been added for calls to 'super', but
             * the caller should emit subsequent statements normally.
             */
            SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement";
            /**
             * A call to 'super()' got replaced with a capturing statement like:
             *
             *  var _this = _super.call(...) || this;
             *
             * Callers should skip the current statement.
             */
            SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture";
            /**
             * A call to 'super()' got replaced with a capturing statement like:
             *
             *  return _super.call(...) || this;
             *
             * Callers should skip the current statement and avoid any returns of '_this'.
             */
            SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
        })(SuperCaptureResult || (SuperCaptureResult = {}));
        // Facts we track as we traverse the tree
        var HierarchyFacts;
        (function (HierarchyFacts) {
            HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
            //
            // Ancestor facts
            //
            HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
            HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
            HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
            HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
            HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
            HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
            HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
            HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
            HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
            HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
            HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
            HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
            HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
            HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
            // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
            //
            // Ancestor masks
            //
            HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
            // We are always in *some* kind of block scope, but only specific block-scope containers are
            // top-level or Blocks.
            HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
            HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes";
            // A source file is a top-level block scope.
            HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
            HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
            // Functions, methods, and accessors are both new lexical scopes and new block scopes.
            HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
            HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
            HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
            HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
            // Arrow functions are lexically scoped to their container, but are new block scopes.
            HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
            HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
            // Constructors are both new lexical scopes and new block scopes. Constructors are also
            // always considered non-static members of a class.
            HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
            HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
            // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
            // within an IterationStatement to indicate whether the embedded statement is an
            // IterationStatementBlock.
            HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes";
            HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
            // 'for' statements are new block scopes and have special handling for 'let' declarations.
            HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes";
            HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes";
            // 'for-in' and 'for-of' statements are new block scopes and have special handling for
            // 'let' declarations.
            HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes";
            HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes";
            // Blocks (other than function bodies) are new block scopes.
            HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
            HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
            HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
            HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
            // Computed property names track subtree flags differently than their containing members.
            HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
            HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
            //
            // Subtree facts
            //
            HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
            HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
            //
            // Subtree masks
            //
            HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
            HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
        })(HierarchyFacts || (HierarchyFacts = {}));
        function transformES2015(context) {
            var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
            var compilerOptions = context.getCompilerOptions();
            var resolver = context.getEmitResolver();
            var previousOnSubstituteNode = context.onSubstituteNode;
            var previousOnEmitNode = context.onEmitNode;
            context.onEmitNode = onEmitNode;
            context.onSubstituteNode = onSubstituteNode;
            var currentSourceFile;
            var currentText;
            var hierarchyFacts;
            var taggedTemplateStringDeclarations;
            function recordTaggedTemplateString(temp) {
                taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
            }
            /**
             * Used to track if we are emitting body of the converted loop
             */
            var convertedLoopState;
            /**
             * Keeps track of whether substitutions have been enabled for specific cases.
             * They are persisted between each SourceFile transformation and should not
             * be reset.
             */
            var enabledSubstitutions;
            return ts.chainBundle(transformSourceFile);
            function transformSourceFile(node) {
                if (node.isDeclarationFile) {
                    return node;
                }
                currentSourceFile = node;
                currentText = node.text;
                var visited = visitSourceFile(node);
                ts.addEmitHelpers(visited, context.readEmitHelpers());
                currentSourceFile = undefined;
                currentText = undefined;
                taggedTemplateStringDeclarations = undefined;
                hierarchyFacts = 0 /* None */;
                return visited;
            }
            /**
             * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
             * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
             * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
             */
            function enterSubtree(excludeFacts, includeFacts) {
                var ancestorFacts = hierarchyFacts;
                hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
                return ancestorFacts;
            }
            /**
             * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
             * subtree, propagating specific facts from the subtree.
             * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
             * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
             * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
             */
            function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
                hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
            }
            function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
                return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
                    && node.kind === 228 /* ReturnStatement */
                    && !node.expression;
            }
            function shouldVisitNode(node) {
                return (node.transformFlags & 128 /* ContainsES2015 */) !== 0
                    || convertedLoopState !== undefined
                    || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */)))
                    || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node))
                    || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
            }
            function visitor(node) {
                if (shouldVisitNode(node)) {
                    return visitJavaScript(node);
                }
                else {
                    return node;
                }
            }
            function functionBodyVisitor(node) {
                if (shouldVisitNode(node)) {
                    return visitBlock(node, /*isFunctionBody*/ true);
                }
                return node;
            }
            function callExpressionVisitor(node) {
                if (node.kind === 97 /* SuperKeyword */) {
                    return visitSuperKeyword(/*isExpressionOfCall*/ true);
                }
                return visitor(node);
            }
            function visitJavaScript(node) {
                switch (node.kind) {
                    case 115 /* StaticKeyword */:
                        return undefined; // elide static keyword
                    case 238 /* ClassDeclaration */:
                        return visitClassDeclaration(node);
                    case 207 /* ClassExpression */:
                        return visitClassExpression(node);
                    case 149 /* Parameter */:
                        return visitParameter(node);
                    case 237 /* FunctionDeclaration */:
                        return visitFunctionDeclaration(node);
                    case 195 /* ArrowFunction */:
                        return visitArrowFunction(node);
                    case 194 /* FunctionExpression */:
                        return visitFunctionExpression(node);
                    case 235 /* VariableDeclaration */:
                        return visitVariableDeclaration(node);
                    case 71 /* Identifier */:
                        return visitIdentifier(node);
                    case 236 /* VariableDeclarationList */:
                        return visitVariableDeclarationList(node);
                    case 230 /* SwitchStatement */:
                        return visitSwitchStatement(node);
                    case 244 /* CaseBlock */:
                        return visitCaseBlock(node);
                    case 216 /* Block */:
                        return visitBlock(node, /*isFunctionBody*/ false);
                    case 227 /* BreakStatement */:
                    case 226 /* ContinueStatement */:
                        return visitBreakOrContinueStatement(node);
                    case 231 /* LabeledStatement */:
                        return visitLabeledStatement(node);
                    case 221 /* DoStatement */:
                    case 222 /* WhileStatement */:
                        return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
                    case 223 /* ForStatement */:
                        return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
                    case 224 /* ForInStatement */:
                        return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
                    case 225 /* ForOfStatement */:
                        return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
                    case 219 /* ExpressionStatement */:
                        return visitExpressionStatement(node);
                    case 186 /* ObjectLiteralExpression */:
                        return visitObjectLiteralExpression(node);
                    case 272 /* CatchClause */:
                        return visitCatchClause(node);
                    case 274 /* ShorthandPropertyAssignment */:
                        return visitShorthandPropertyAssignment(node);
                    case 147 /* ComputedPropertyName */:
                        return visitComputedPropertyName(node);
                    case 185 /* ArrayLiteralExpression */:
                        return visitArrayLiteralExpression(node);
                    case 189 /* CallExpression */:
                        return visitCallExpression(node);
                    case 190 /* NewExpression */:
                        return visitNewExpression(node);
                    case 193 /* ParenthesizedExpression */:
                        return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
                    case 202 /* BinaryExpression */:
                        return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
                    case 13 /* NoSubstitutionTemplateLiteral */:
                    case 14 /* TemplateHead */:
                    case 15 /* TemplateMiddle */:
                    case 16 /* TemplateTail */:
                        return visitTemplateLiteral(node);
                    case 9 /* StringLiteral */:
                        return visitStringLiteral(node);
                    case 8 /* NumericLiteral */:
                        return visitNumericLiteral(node);
                    case 191 /* TaggedTemplateExpression */:
                        return visitTaggedTemplateExpression(node);
                    case 204 /* TemplateExpression */:
                        return visitTemplateExpression(node);
                    case 205 /* YieldExpression */:
                        return visitYieldExpression(node);
                    case 206 /* SpreadElement */:
                        return visitSpreadElement(node);
                    case 97 /* SuperKeyword */:
                        return visitSuperKeyword(/*isExpressionOfCall*/ false);
                    case 99 /* ThisKeyword */:
                        return visitThisKeyword(node);
                    case 212 /* MetaProperty */:
                        return visitMetaProperty(node);
                    case 154 /* MethodDeclaration */:
                        return visitMethodDeclaration(node);
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return visitAccessorDeclaration(node);
                    case 217 /* VariableStatement */:
                        return visitVariableStatement(node);
                    case 228 /* ReturnStatement */:
                        return visitReturnStatement(node);
                    default:
                        return ts.visitEachChild(node, visitor, context);
                }
            }
            function visitSourceFile(node) {
                var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
                var statements = [];
                startLexicalEnvironment();
                var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
                addCaptureThisForNodeIfNeeded(statements, node);
                statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
                ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
                if (taggedTemplateStringDeclarations) {
                    statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
                }
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
            }
            function visitSwitchStatement(node) {
                if (convertedLoopState !== undefined) {
                    var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
                    // for switch statement allow only non-labeled break
                    convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
                    var result = ts.visitEachChild(node, visitor, context);
                    convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
                    return result;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitCaseBlock(node) {
                var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
                var updated = ts.visitEachChild(node, visitor, context);
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                return updated;
            }
            function returnCapturedThis(node) {
                return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
            }
            function visitReturnStatement(node) {
                if (convertedLoopState) {
                    convertedLoopState.nonLocalJumps |= 8 /* Return */;
                    if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
                        node = returnCapturedThis(node);
                    }
                    return ts.createReturn(ts.createObjectLiteral([
                        ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
                            ? ts.visitNode(node.expression, visitor, ts.isExpression)
                            : ts.createVoidZero())
                    ]));
                }
                else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
                    return returnCapturedThis(node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitThisKeyword(node) {
                if (convertedLoopState) {
                    if (hierarchyFacts & 2 /* ArrowFunction */) {
                        // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
                        convertedLoopState.containsLexicalThis = true;
                        return node;
                    }
                    return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
                }
                return node;
            }
            function visitIdentifier(node) {
                if (!convertedLoopState) {
                    return node;
                }
                if (ts.isGeneratedIdentifier(node)) {
                    return node;
                }
                if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
                    return node;
                }
                return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
            }
            function visitBreakOrContinueStatement(node) {
                if (convertedLoopState) {
                    // check if we can emit break/continue as is
                    // it is possible if either
                    //   - break/continue is labeled and label is located inside the converted loop
                    //   - break/continue is non-labeled and located in non-converted loop/switch statement
                    var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
                    var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
                        (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
                    if (!canUseBreakOrContinue) {
                        var labelMarker = void 0;
                        var label = node.label;
                        if (!label) {
                            if (node.kind === 227 /* BreakStatement */) {
                                convertedLoopState.nonLocalJumps |= 2 /* Break */;
                                labelMarker = "break";
                            }
                            else {
                                convertedLoopState.nonLocalJumps |= 4 /* Continue */;
                                // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
                                labelMarker = "continue";
                            }
                        }
                        else {
                            if (node.kind === 227 /* BreakStatement */) {
                                labelMarker = "break-" + label.escapedText;
                                setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
                            }
                            else {
                                labelMarker = "continue-" + label.escapedText;
                                setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
                            }
                        }
                        var returnExpression = ts.createLiteral(labelMarker);
                        if (convertedLoopState.loopOutParameters.length) {
                            var outParams = convertedLoopState.loopOutParameters;
                            var expr = void 0;
                            for (var i = 0; i < outParams.length; i++) {
                                var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
                                if (i === 0) {
                                    expr = copyExpr;
                                }
                                else {
                                    expr = ts.createBinary(expr, 26 /* CommaToken */, copyExpr);
                                }
                            }
                            returnExpression = ts.createBinary(expr, 26 /* CommaToken */, returnExpression);
                        }
                        return ts.createReturn(returnExpression);
                    }
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a ClassDeclaration and transforms it into a variable statement.
             *
             * @param node A ClassDeclaration node.
             */
            function visitClassDeclaration(node) {
                // [source]
                //      class C { }
                //
                // [output]
                //      var C = (function () {
                //          function C() {
                //          }
                //          return C;
                //      }());
                var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), 
                /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
                ts.setOriginalNode(variable, node);
                var statements = [];
                var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
                ts.setOriginalNode(statement, node);
                ts.setTextRange(statement, node);
                ts.startOnNewLine(statement);
                statements.push(statement);
                // Add an `export default` statement for default exports (for `--target es5 --module es6`)
                if (ts.hasModifier(node, 1 /* Export */)) {
                    var exportStatement = ts.hasModifier(node, 512 /* Default */)
                        ? ts.createExportDefault(ts.getLocalName(node))
                        : ts.createExternalModuleExport(ts.getLocalName(node));
                    ts.setOriginalNode(exportStatement, statement);
                    statements.push(exportStatement);
                }
                var emitFlags = ts.getEmitFlags(node);
                if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
                    // Add a DeclarationMarker as a marker for the end of the declaration
                    statements.push(ts.createEndOfDeclarationMarker(node));
                    ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits a ClassExpression and transforms it into an expression.
             *
             * @param node A ClassExpression node.
             */
            function visitClassExpression(node) {
                // [source]
                //      C = class { }
                //
                // [output]
                //      C = (function () {
                //          function class_1() {
                //          }
                //          return class_1;
                //      }())
                return transformClassLikeDeclarationToExpression(node);
            }
            /**
             * Transforms a ClassExpression or ClassDeclaration into an expression.
             *
             * @param node A ClassExpression or ClassDeclaration node.
             */
            function transformClassLikeDeclarationToExpression(node) {
                // [source]
                //      class C extends D {
                //          constructor() {}
                //          method() {}
                //          get prop() {}
                //          set prop(v) {}
                //      }
                //
                // [output]
                //      (function (_super) {
                //          __extends(C, _super);
                //          function C() {
                //          }
                //          C.prototype.method = function () {}
                //          Object.defineProperty(C.prototype, "prop", {
                //              get: function() {},
                //              set: function() {},
                //              enumerable: true,
                //              configurable: true
                //          });
                //          return C;
                //      }(D))
                if (node.name) {
                    enableSubstitutionsForBlockScopedBindings();
                }
                var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
                var classFunction = ts.createFunctionExpression(
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], 
                /*type*/ undefined, transformClassBody(node, extendsClauseElement));
                // To preserve the behavior of the old emitter, we explicitly indent
                // the body of the function here if it was requested in an earlier
                // transformation.
                ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
                // "inner" and "outer" below are added purely to preserve source map locations from
                // the old emitter
                var inner = ts.createPartiallyEmittedExpression(classFunction);
                inner.end = node.end;
                ts.setEmitFlags(inner, 1536 /* NoComments */);
                var outer = ts.createPartiallyEmittedExpression(inner);
                outer.end = ts.skipTrivia(currentText, node.pos);
                ts.setEmitFlags(outer, 1536 /* NoComments */);
                var result = ts.createParen(ts.createCall(outer, 
                /*typeArguments*/ undefined, extendsClauseElement
                    ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
                    : []));
                ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
                return result;
            }
            /**
             * Transforms a ClassExpression or ClassDeclaration into a function body.
             *
             * @param node A ClassExpression or ClassDeclaration node.
             * @param extendsClauseElement The expression for the class `extends` clause.
             */
            function transformClassBody(node, extendsClauseElement) {
                var statements = [];
                startLexicalEnvironment();
                addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
                addConstructor(statements, node, extendsClauseElement);
                addClassMembers(statements, node);
                // Create a synthetic text range for the return statement.
                var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */);
                var localName = ts.getInternalName(node);
                // The following partially-emitted expression exists purely to align our sourcemap
                // emit with the original emitter.
                var outer = ts.createPartiallyEmittedExpression(localName);
                outer.end = closingBraceLocation.end;
                ts.setEmitFlags(outer, 1536 /* NoComments */);
                var statement = ts.createReturn(outer);
                statement.pos = closingBraceLocation.pos;
                ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
                statements.push(statement);
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
                ts.setEmitFlags(block, 1536 /* NoComments */);
                return block;
            }
            /**
             * Adds a call to the `__extends` helper if needed for a class.
             *
             * @param statements The statements of the class body function.
             * @param node The ClassExpression or ClassDeclaration node.
             * @param extendsClauseElement The expression for the class `extends` clause.
             */
            function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
                if (extendsClauseElement) {
                    statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), 
                    /*location*/ extendsClauseElement));
                }
            }
            /**
             * Adds the constructor of the class to a class body function.
             *
             * @param statements The statements of the class body function.
             * @param node The ClassExpression or ClassDeclaration node.
             * @param extendsClauseElement The expression for the class `extends` clause.
             */
            function addConstructor(statements, node, extendsClauseElement) {
                var savedConvertedLoopState = convertedLoopState;
                convertedLoopState = undefined;
                var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
                var constructor = ts.getFirstConstructorWithBody(node);
                var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
                var constructorFunction = ts.createFunctionDeclaration(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, ts.getInternalName(node), 
                /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
                /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
                ts.setTextRange(constructorFunction, constructor || node);
                if (extendsClauseElement) {
                    ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
                }
                statements.push(constructorFunction);
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
                convertedLoopState = savedConvertedLoopState;
            }
            /**
             * Transforms the parameters of the constructor declaration of a class.
             *
             * @param constructor The constructor for the class.
             * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
             *                            synthesized `super` call.
             */
            function transformConstructorParameters(constructor, hasSynthesizedSuper) {
                // If the TypeScript transformer needed to synthesize a constructor for property
                // initializers, it would have also added a synthetic `...args` parameter and
                // `super` call.
                // If this is the case, we do not include the synthetic `...args` parameter and
                // will instead use the `arguments` object in ES5/3.
                return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
                    || [];
            }
            /**
             * Transforms the body of a constructor declaration of a class.
             *
             * @param constructor The constructor for the class.
             * @param node The node which contains the constructor.
             * @param extendsClauseElement The expression for the class `extends` clause.
             * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
             *                            synthesized `super` call.
             */
            function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
                var statements = [];
                resumeLexicalEnvironment();
                var statementOffset = -1;
                if (hasSynthesizedSuper) {
                    // If a super call has already been synthesized,
                    // we're going to assume that we should just transform everything after that.
                    // The assumption is that no prior step in the pipeline has added any prologue directives.
                    statementOffset = 0;
                }
                else if (constructor) {
                    statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
                }
                if (constructor) {
                    addDefaultValueAssignmentsIfNeeded(statements, constructor);
                    addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
                    if (!hasSynthesizedSuper) {
                        // If no super call has been synthesized, emit custom prologue directives.
                        statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
                    }
                    ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
                }
                // determine whether the class is known syntactically to be a derived class (e.g. a
                // class that extends a value that is not syntactically known to be `null`).
                var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */;
                var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
                // The last statement expression was replaced. Skip it.
                if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
                    statementOffset++;
                }
                if (constructor) {
                    if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
                        hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
                    }
                    ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
                }
                // Return `_this` unless we're sure enough that it would be pointless to add a return statement.
                // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
                if (isDerivedClass
                    && superCaptureStatus !== 2 /* ReplaceWithReturn */
                    && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
                    statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
                }
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                if (constructor) {
                    prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
                }
                var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
                /*location*/ constructor ? constructor.body.statements : node.members), 
                /*multiLine*/ true);
                ts.setTextRange(block, constructor ? constructor.body : node);
                if (!constructor) {
                    ts.setEmitFlags(block, 1536 /* NoComments */);
                }
                return block;
            }
            /**
             * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
             * It would generate obviously dead code, so we'll try to make things a little bit prettier
             * by doing a minimal check on whether some common patterns always explicitly return.
             */
            function isSufficientlyCoveredByReturnStatements(statement) {
                // A return statement is considered covered.
                if (statement.kind === 228 /* ReturnStatement */) {
                    return true;
                }
                // An if-statement with two covered branches is covered.
                else if (statement.kind === 220 /* IfStatement */) {
                    var ifStatement = statement;
                    if (ifStatement.elseStatement) {
                        return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
                            isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
                    }
                }
                // A block is covered if it has a last statement which is covered.
                else if (statement.kind === 216 /* Block */) {
                    var lastStatement = ts.lastOrUndefined(statement.statements);
                    if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
                        return true;
                    }
                }
                return false;
            }
            /**
             * Declares a `_this` variable for derived classes and for when arrow functions capture `this`.
             *
             * @returns The new statement offset into the `statements` array.
             */
            function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
                // If this isn't a derived class, just capture 'this' for arrow functions if necessary.
                if (!isDerivedClass) {
                    if (ctor) {
                        addCaptureThisForNodeIfNeeded(statements, ctor);
                    }
                    return 0 /* NoReplacement */;
                }
                // We must be here because the user didn't write a constructor
                // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
                // If that's the case we can just immediately return the result of a 'super()' call.
                if (!ctor) {
                    statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
                    return 2 /* ReplaceWithReturn */;
                }
                // The constructor exists, but it and the 'super()' call it contains were generated
                // for something like property initializers.
                // Create a captured '_this' variable and assume it will subsequently be used.
                if (hasSynthesizedSuper) {
                    captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
                    enableSubstitutionsForCapturedThis();
                    return 1 /* ReplaceSuperCapture */;
                }
                // Most of the time, a 'super' call will be the first real statement in a constructor body.
                // In these cases, we'd like to transform these into a *single* statement instead of a declaration
                // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer,
                // we'd get:
                //
                //      var _this;
                //      _this = _super.call(...) || this;
                //
                // instead of
                //
                //      var _this = _super.call(...) || this;
                //
                // Additionally, if the 'super()' call is the last statement, we should just avoid capturing
                // entirely and immediately return the result like so:
                //
                //      return _super.call(...) || this;
                //
                var firstStatement;
                var superCallExpression;
                var ctorStatements = ctor.body.statements;
                if (statementOffset < ctorStatements.length) {
                    firstStatement = ctorStatements[statementOffset];
                    if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
                        superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
                    }
                }
                // Return the result if we have an immediate super() call on the last statement,
                // but only if the constructor itself doesn't use 'this' elsewhere.
                if (superCallExpression
                    && statementOffset === ctorStatements.length - 1
                    && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) {
                    var returnStatement = ts.createReturn(superCallExpression);
                    if (superCallExpression.kind !== 202 /* BinaryExpression */
                        || superCallExpression.left.kind !== 189 /* CallExpression */) {
                        ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'.");
                    }
                    // Shift comments from the original super call to the return statement.
                    ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */)));
                    statements.push(returnStatement);
                    return 2 /* ReplaceWithReturn */;
                }
                // Perform the capture.
                captureThisForNode(statements, ctor, superCallExpression || createActualThis());
                // If we're actually replacing the original statement, we need to signal this to the caller.
                if (superCallExpression) {
                    return 1 /* ReplaceSuperCapture */;
                }
                return 0 /* NoReplacement */;
            }
            function createActualThis() {
                return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
            }
            function createDefaultSuperCallOrThis() {
                return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
            }
            /**
             * Visits a parameter declaration.
             *
             * @param node A ParameterDeclaration node.
             */
            function visitParameter(node) {
                if (node.dotDotDotToken) {
                    // rest parameters are elided
                    return undefined;
                }
                else if (ts.isBindingPattern(node.name)) {
                    // Binding patterns are converted into a generated name and are
                    // evaluated inside the function body.
                    return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, 
                    /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), 
                    /*questionToken*/ undefined, 
                    /*type*/ undefined, 
                    /*initializer*/ undefined), 
                    /*location*/ node), 
                    /*original*/ node);
                }
                else if (node.initializer) {
                    // Initializers are elided
                    return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, 
                    /*dotDotDotToken*/ undefined, node.name, 
                    /*questionToken*/ undefined, 
                    /*type*/ undefined, 
                    /*initializer*/ undefined), 
                    /*location*/ node), 
                    /*original*/ node);
                }
                else {
                    return node;
                }
            }
            /**
             * Gets a value indicating whether we need to add default value assignments for a
             * function-like node.
             *
             * @param node A function-like node.
             */
            function shouldAddDefaultValueAssignments(node) {
                return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0;
            }
            /**
             * Adds statements to the body of a function-like node if it contains parameters with
             * binding patterns or initializers.
             *
             * @param statements The statements for the new function body.
             * @param node A function-like node.
             */
            function addDefaultValueAssignmentsIfNeeded(statements, node) {
                if (!shouldAddDefaultValueAssignments(node)) {
                    return;
                }
                for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
                    var parameter = _a[_i];
                    var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
                    // A rest parameter cannot have a binding pattern or an initializer,
                    // so let's just ignore it.
                    if (dotDotDotToken) {
                        continue;
                    }
                    if (ts.isBindingPattern(name)) {
                        addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
                    }
                    else if (initializer) {
                        addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
                    }
                }
            }
            /**
             * Adds statements to the body of a function-like node for parameters with binding patterns
             *
             * @param statements The statements for the new function body.
             * @param parameter The parameter for the function.
             * @param name The name of the parameter.
             * @param initializer The initializer for the parameter.
             */
            function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
                var temp = ts.getGeneratedNameForNode(parameter);
                // In cases where a binding pattern is simply '[]' or '{}',
                // we usually don't want to emit a var declaration; however, in the presence
                // of an initializer, we must emit that expression to preserve side effects.
                if (name.elements.length > 0) {
                    statements.push(ts.setEmitFlags(ts.createVariableStatement(
                    /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */));
                }
                else if (initializer) {
                    statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
                }
            }
            /**
             * Adds statements to the body of a function-like node for parameters with initializers.
             *
             * @param statements The statements for the new function body.
             * @param parameter The parameter for the function.
             * @param name The name of the parameter.
             * @param initializer The initializer for the parameter.
             */
            function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
                initializer = ts.visitNode(initializer, visitor, ts.isExpression);
                var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
                    ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
                ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
                ts.startOnNewLine(statement);
                ts.setTextRange(statement, parameter);
                ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
                statements.push(statement);
            }
            /**
             * Gets a value indicating whether we need to add statements to handle a rest parameter.
             *
             * @param node A ParameterDeclaration node.
             * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
             *                                          part of a constructor declaration with a
             *                                          synthesized call to `super`
             */
            function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
                return node && node.dotDotDotToken && node.name.kind === 71 /* Identifier */ && !inConstructorWithSynthesizedSuper;
            }
            /**
             * Adds statements to the body of a function-like node if it contains a rest parameter.
             *
             * @param statements The statements for the new function body.
             * @param node A function-like node.
             * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
             *                                          part of a constructor declaration with a
             *                                          synthesized call to `super`
             */
            function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
                var parameter = ts.lastOrUndefined(node.parameters);
                if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
                    return;
                }
                // `declarationName` is the name of the local declaration for the parameter.
                var declarationName = ts.getMutableClone(parameter.name);
                ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
                // `expressionName` is the name of the parameter used in expressions.
                var expressionName = ts.getSynthesizedClone(parameter.name);
                var restIndex = node.parameters.length - 1;
                var temp = ts.createLoopVariable();
                // var param = [];
                statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
                /*modifiers*/ undefined, ts.createVariableDeclarationList([
                    ts.createVariableDeclaration(declarationName, 
                    /*type*/ undefined, ts.createArrayLiteral([]))
                ])), 
                /*location*/ parameter), 1048576 /* CustomPrologue */));
                // for (var _i = restIndex; _i < arguments.length; _i++) {
                //   param[_i - restIndex] = arguments[_i];
                // }
                var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
                    ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
                ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
                    ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
                        ? temp
                        : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), 
                    /*location*/ parameter))
                ]));
                ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
                ts.startOnNewLine(forStatement);
                statements.push(forStatement);
            }
            /**
             * Adds a statement to capture the `this` of a function declaration if it is needed.
             *
             * @param statements The statements for the new function body.
             * @param node A node.
             */
            function addCaptureThisForNodeIfNeeded(statements, node) {
                if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) {
                    captureThisForNode(statements, node, ts.createThis());
                }
            }
            function captureThisForNode(statements, node, initializer) {
                enableSubstitutionsForCapturedThis();
                var captureThisStatement = ts.createVariableStatement(
                /*modifiers*/ undefined, ts.createVariableDeclarationList([
                    ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), 
                    /*type*/ undefined, initializer)
                ]));
                ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
                ts.setSourceMapRange(captureThisStatement, node);
                statements.push(captureThisStatement);
            }
            function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
                if (hierarchyFacts & 16384 /* NewTarget */) {
                    var newTarget = void 0;
                    switch (node.kind) {
                        case 195 /* ArrowFunction */:
                            return statements;
                        case 154 /* MethodDeclaration */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            // Methods and accessors cannot be constructors, so 'new.target' will
                            // always return 'undefined'.
                            newTarget = ts.createVoidZero();
                            break;
                        case 155 /* Constructor */:
                            // Class constructors can only be called with `new`, so `this.constructor`
                            // should be relatively safe to use.
                            newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
                            break;
                        case 237 /* FunctionDeclaration */:
                        case 194 /* FunctionExpression */:
                            // Functions can be called or constructed, and may have a `this` due to
                            // being a member or when calling an imported function via `other_1.f()`.
                            newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero());
                            break;
                        default:
                            return ts.Debug.failBadSyntaxKind(node);
                    }
                    var captureNewTargetStatement = ts.createVariableStatement(
                    /*modifiers*/ undefined, ts.createVariableDeclarationList([
                        ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), 
                        /*type*/ undefined, newTarget)
                    ]));
                    if (copyOnWrite) {
                        return [captureNewTargetStatement].concat(statements);
                    }
                    statements.unshift(captureNewTargetStatement);
                }
                return statements;
            }
            /**
             * Adds statements to the class body function for a class to define the members of the
             * class.
             *
             * @param statements The statements for the class body function.
             * @param node The ClassExpression or ClassDeclaration node.
             */
            function addClassMembers(statements, node) {
                for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
                    var member = _a[_i];
                    switch (member.kind) {
                        case 215 /* SemicolonClassElement */:
                            statements.push(transformSemicolonClassElementToStatement(member));
                            break;
                        case 154 /* MethodDeclaration */:
                            statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
                            break;
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            var accessors = ts.getAllAccessorDeclarations(node.members, member);
                            if (member === accessors.firstAccessor) {
                                statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
                            }
                            break;
                        case 155 /* Constructor */:
                            // Constructors are handled in visitClassExpression/visitClassDeclaration
                            break;
                        default:
                            ts.Debug.failBadSyntaxKind(node);
                            break;
                    }
                }
            }
            /**
             * Transforms a SemicolonClassElement into a statement for a class body function.
             *
             * @param member The SemicolonClassElement node.
             */
            function transformSemicolonClassElementToStatement(member) {
                return ts.setTextRange(ts.createEmptyStatement(), member);
            }
            /**
             * Transforms a MethodDeclaration into a statement for a class body function.
             *
             * @param receiver The receiver for the member.
             * @param member The MethodDeclaration node.
             */
            function transformClassMethodDeclarationToStatement(receiver, member, container) {
                var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
                var commentRange = ts.getCommentRange(member);
                var sourceMapRange = ts.getSourceMapRange(member);
                var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
                var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
                ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
                ts.setSourceMapRange(memberFunction, sourceMapRange);
                var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), 
                /*location*/ member);
                ts.setOriginalNode(statement, member);
                ts.setCommentRange(statement, commentRange);
                // The location for the statement is used to emit comments only.
                // No source map should be emitted for this statement to align with the
                // old emitter.
                ts.setEmitFlags(statement, 48 /* NoSourceMap */);
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
                return statement;
            }
            /**
             * Transforms a set of related of get/set accessors into a statement for a class body function.
             *
             * @param receiver The receiver for the member.
             * @param accessors The set of related get/set accessors.
             */
            function transformAccessorsToStatement(receiver, accessors, container) {
                var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
                // The location for the statement is used to emit source maps only.
                // No comments should be emitted for this statement to align with the
                // old emitter.
                ts.setEmitFlags(statement, 1536 /* NoComments */);
                ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
                return statement;
            }
            /**
             * Transforms a set of related get/set accessors into an expression for either a class
             * body function or an ObjectLiteralExpression with computed properties.
             *
             * @param receiver The receiver for the member.
             */
            function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
                var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
                var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
                // To align with source maps in the old emitter, the receiver and property name
                // arguments are both mapped contiguously to the accessor name.
                var target = ts.getMutableClone(receiver);
                ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
                ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217
                var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName));
                ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
                ts.setSourceMapRange(propertyName, firstAccessor.name);
                var properties = [];
                if (getAccessor) {
                    var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
                    ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
                    ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
                    var getter = ts.createPropertyAssignment("get", getterFunction);
                    ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
                    properties.push(getter);
                }
                if (setAccessor) {
                    var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
                    ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
                    ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
                    var setter = ts.createPropertyAssignment("set", setterFunction);
                    ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
                    properties.push(setter);
                }
                properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
                var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
                /*typeArguments*/ undefined, [
                    target,
                    propertyName,
                    ts.createObjectLiteral(properties, /*multiLine*/ true)
                ]);
                if (startsOnNewLine) {
                    ts.startOnNewLine(call);
                }
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
                return call;
            }
            /**
             * Visits an ArrowFunction and transforms it into a FunctionExpression.
             *
             * @param node An ArrowFunction node.
             */
            function visitArrowFunction(node) {
                if (node.transformFlags & 16384 /* ContainsLexicalThis */) {
                    enableSubstitutionsForCapturedThis();
                }
                var savedConvertedLoopState = convertedLoopState;
                convertedLoopState = undefined;
                var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
                var func = ts.createFunctionExpression(
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                /*type*/ undefined, transformFunctionBody(node));
                ts.setTextRange(func, node);
                ts.setOriginalNode(func, node);
                ts.setEmitFlags(func, 8 /* CapturesThis */);
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                convertedLoopState = savedConvertedLoopState;
                return func;
            }
            /**
             * Visits a FunctionExpression node.
             *
             * @param node a FunctionExpression node.
             */
            function visitFunctionExpression(node) {
                var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
                    ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
                    : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
                var savedConvertedLoopState = convertedLoopState;
                convertedLoopState = undefined;
                var parameters = ts.visitParameterList(node.parameters, visitor, context);
                var body = node.transformFlags & 64 /* ES2015 */
                    ? transformFunctionBody(node)
                    : visitFunctionBodyDownLevel(node);
                var name = hierarchyFacts & 16384 /* NewTarget */
                    ? ts.getLocalName(node)
                    : node.name;
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
                convertedLoopState = savedConvertedLoopState;
                return ts.updateFunctionExpression(node, 
                /*modifiers*/ undefined, node.asteriskToken, name, 
                /*typeParameters*/ undefined, parameters, 
                /*type*/ undefined, body);
            }
            /**
             * Visits a FunctionDeclaration node.
             *
             * @param node a FunctionDeclaration node.
             */
            function visitFunctionDeclaration(node) {
                var savedConvertedLoopState = convertedLoopState;
                convertedLoopState = undefined;
                var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
                var parameters = ts.visitParameterList(node.parameters, visitor, context);
                var body = node.transformFlags & 64 /* ES2015 */
                    ? transformFunctionBody(node)
                    : visitFunctionBodyDownLevel(node);
                var name = hierarchyFacts & 16384 /* NewTarget */
                    ? ts.getLocalName(node)
                    : node.name;
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
                convertedLoopState = savedConvertedLoopState;
                return ts.updateFunctionDeclaration(node, 
                /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
                /*typeParameters*/ undefined, parameters, 
                /*type*/ undefined, body);
            }
            /**
             * Transforms a function-like node into a FunctionExpression.
             *
             * @param node The function-like node to transform.
             * @param location The source-map location for the new FunctionExpression.
             * @param name The name of the new FunctionExpression.
             */
            function transformFunctionLikeToExpression(node, location, name, container) {
                var savedConvertedLoopState = convertedLoopState;
                convertedLoopState = undefined;
                var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
                    ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
                    : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
                var parameters = ts.visitParameterList(node.parameters, visitor, context);
                var body = transformFunctionBody(node);
                if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) {
                    name = ts.getGeneratedNameForNode(node);
                }
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
                convertedLoopState = savedConvertedLoopState;
                return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
                /*modifiers*/ undefined, node.asteriskToken, name, 
                /*typeParameters*/ undefined, parameters, 
                /*type*/ undefined, body), location), 
                /*original*/ node);
            }
            /**
             * Transforms the body of a function-like node.
             *
             * @param node A function-like node.
             */
            function transformFunctionBody(node) {
                var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
                var singleLine = false; // indicates whether the block *may* be emitted as a single line
                var statementsLocation;
                var closeBraceLocation;
                var leadingStatements = [];
                var statements = [];
                var body = node.body;
                var statementOffset;
                resumeLexicalEnvironment();
                if (ts.isBlock(body)) {
                    // ensureUseStrict is false because no new prologue-directive should be added.
                    // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
                    statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false);
                }
                addCaptureThisForNodeIfNeeded(leadingStatements, node);
                addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
                addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false);
                if (ts.isBlock(body)) {
                    // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
                    statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
                    statementsLocation = body.statements;
                    ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
                    // If the original body was a multi-line block, this must be a multi-line block.
                    if (!multiLine && body.multiLine) {
                        multiLine = true;
                    }
                }
                else {
                    ts.Debug.assert(node.kind === 195 /* ArrowFunction */);
                    // To align with the old emitter, we use a synthetic end position on the location
                    // for the statement list we synthesize when we down-level an arrow function with
                    // an expression function body. This prevents both comments and source maps from
                    // being emitted for the end position only.
                    statementsLocation = ts.moveRangeEnd(body, -1);
                    var equalsGreaterThanToken = node.equalsGreaterThanToken;
                    if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
                        if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
                            singleLine = true;
                        }
                        else {
                            multiLine = true;
                        }
                    }
                    var expression = ts.visitNode(body, visitor, ts.isExpression);
                    var returnStatement = ts.createReturn(expression);
                    ts.setTextRange(returnStatement, body);
                    ts.moveSyntheticComments(returnStatement, body);
                    ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
                    statements.push(returnStatement);
                    // To align with the source map emit for the old emitter, we set a custom
                    // source map location for the close brace.
                    closeBraceLocation = body;
                }
                var lexicalEnvironment = context.endLexicalEnvironment();
                ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
                prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
                // If we added any final generated statements, this must be a multi-line block
                if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
                    multiLine = true;
                }
                var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
                ts.setTextRange(block, node.body);
                if (!multiLine && singleLine) {
                    ts.setEmitFlags(block, 1 /* SingleLine */);
                }
                if (closeBraceLocation) {
                    ts.setTokenSourceMapRange(block, 18 /* CloseBraceToken */, closeBraceLocation);
                }
                ts.setOriginalNode(block, node.body);
                return block;
            }
            function visitFunctionBodyDownLevel(node) {
                var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
                return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), 
                /*location*/ updated.statements));
            }
            function visitBlock(node, isFunctionBody) {
                if (isFunctionBody) {
                    // A function body is not a block scope.
                    return ts.visitEachChild(node, visitor, context);
                }
                var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
                    ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
                    : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */);
                var updated = ts.visitEachChild(node, visitor, context);
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                return updated;
            }
            /**
             * Visits an ExpressionStatement that contains a destructuring assignment.
             *
             * @param node An ExpressionStatement node.
             */
            function visitExpressionStatement(node) {
                // If we are here it is most likely because our expression is a destructuring assignment.
                switch (node.expression.kind) {
                    case 193 /* ParenthesizedExpression */:
                        return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
                    case 202 /* BinaryExpression */:
                        return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a ParenthesizedExpression that may contain a destructuring assignment.
             *
             * @param node A ParenthesizedExpression node.
             * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
             *                                of a destructuring assignment.
             */
            function visitParenthesizedExpression(node, needsDestructuringValue) {
                // If we are here it is most likely because our expression is a destructuring assignment.
                if (!needsDestructuringValue) {
                    // By default we always emit the RHS at the end of a flattened destructuring
                    // expression. If we are in a state where we do not need the destructuring value,
                    // we pass that information along to the children that care about it.
                    switch (node.expression.kind) {
                        case 193 /* ParenthesizedExpression */:
                            return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
                        case 202 /* BinaryExpression */:
                            return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
                    }
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a BinaryExpression that contains a destructuring assignment.
             *
             * @param node A BinaryExpression node.
             * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
             *                                of a destructuring assignment.
             */
            function visitBinaryExpression(node, needsDestructuringValue) {
                // If we are here it is because this is a destructuring assignment.
                if (ts.isDestructuringAssignment(node)) {
                    return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitVariableStatement(node) {
                var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
                var updated;
                if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) {
                    // we are inside a converted loop - hoist variable declarations
                    var assignments = void 0;
                    for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
                        if (decl.initializer) {
                            var assignment = void 0;
                            if (ts.isBindingPattern(decl.name)) {
                                assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
                            }
                            else {
                                assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
                                ts.setTextRange(assignment, decl);
                            }
                            assignments = ts.append(assignments, assignment);
                        }
                    }
                    if (assignments) {
                        updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
                    }
                    else {
                        // none of declarations has initializer - the entire variable statement can be deleted
                        updated = undefined;
                    }
                }
                else {
                    updated = ts.visitEachChild(node, visitor, context);
                }
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                return updated;
            }
            /**
             * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
             *
             * @param node A VariableDeclarationList node.
             */
            function visitVariableDeclarationList(node) {
                if (node.transformFlags & 64 /* ES2015 */) {
                    if (node.flags & 3 /* BlockScoped */) {
                        enableSubstitutionsForBlockScopedBindings();
                    }
                    var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
                        ? visitVariableDeclarationInLetDeclarationList
                        : visitVariableDeclaration);
                    var declarationList = ts.createVariableDeclarationList(declarations);
                    ts.setOriginalNode(declarationList, node);
                    ts.setTextRange(declarationList, node);
                    ts.setCommentRange(declarationList, node);
                    // If the first or last declaration is a binding pattern, we need to modify
                    // the source map range for the declaration list.
                    if (node.transformFlags & 8388608 /* ContainsBindingPattern */
                        && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
                        ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
                    }
                    return declarationList;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function getRangeUnion(declarations) {
                // declarations may not be sorted by position.
                // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
                var pos = -1, end = -1;
                for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
                    var node = declarations_10[_i];
                    pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
                    end = Math.max(end, node.end);
                }
                return ts.createRange(pos, end);
            }
            /**
             * Gets a value indicating whether we should emit an explicit initializer for a variable
             * declaration in a `let` declaration list.
             *
             * @param node A VariableDeclaration node.
             */
            function shouldEmitExplicitInitializerForLetDeclaration(node) {
                // Nested let bindings might need to be initialized explicitly to preserve
                // ES6 semantic:
                //
                //  { let x = 1; }
                //  { let x; } // x here should be undefined. not 1
                //
                // Top level bindings never collide with anything and thus don't require
                // explicit initialization. As for nested let bindings there are two cases:
                //
                // - Nested let bindings that were not renamed definitely should be
                //   initialized explicitly:
                //
                //    { let x = 1; }
                //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
                //
                //   Without explicit initialization code in /*1*/ can be executed even if
                //   some-condition is evaluated to false.
                //
                // - Renaming introduces fresh name that should not collide with any
                //   existing names, however renamed bindings sometimes also should be
                //   explicitly initialized. One particular case: non-captured binding
                //   declared inside loop body (but not in loop initializer):
                //
                //    let x;
                //    for (;;) {
                //        let x;
                //    }
                //
                //   In downlevel codegen inner 'x' will be renamed so it won't collide
                //   with outer 'x' however it will should be reset on every iteration as
                //   if it was declared anew.
                //
                //   * Why non-captured binding?
                //     - Because if loop contains block scoped binding captured in some
                //       function then loop body will be rewritten to have a fresh scope
                //       on every iteration so everything will just work.
                //
                //   * Why loop initializer is excluded?
                //     - Since we've introduced a fresh name it already will be undefined.
                var flags = resolver.getNodeCheckFlags(node);
                var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */;
                var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */;
                var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
                    || (isCapturedInFunction
                        && isDeclaredInLoop
                        && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
                var emitExplicitInitializer = !emittedAsTopLevel
                    && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0
                    && (!resolver.isDeclarationWithCollidingName(node)
                        || (isDeclaredInLoop
                            && !isCapturedInFunction
                            && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0));
                return emitExplicitInitializer;
            }
            /**
             * Visits a VariableDeclaration in a `let` declaration list.
             *
             * @param node A VariableDeclaration node.
             */
            function visitVariableDeclarationInLetDeclarationList(node) {
                // For binding pattern names that lack initializers there is no point to emit
                // explicit initializer since downlevel codegen for destructuring will fail
                // in the absence of initializer so all binding elements will say uninitialized
                var name = node.name;
                if (ts.isBindingPattern(name)) {
                    return visitVariableDeclaration(node);
                }
                if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
                    var clone_2 = ts.getMutableClone(node);
                    clone_2.initializer = ts.createVoidZero();
                    return clone_2;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a VariableDeclaration node with a binding pattern.
             *
             * @param node A VariableDeclaration node.
             */
            function visitVariableDeclaration(node) {
                var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
                var updated;
                if (ts.isBindingPattern(node.name)) {
                    updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
                    /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
                }
                else {
                    updated = ts.visitEachChild(node, visitor, context);
                }
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                return updated;
            }
            function recordLabel(node) {
                convertedLoopState.labels.set(ts.idText(node.label), true);
            }
            function resetLabel(node) {
                convertedLoopState.labels.set(ts.idText(node.label), false);
            }
            function visitLabeledStatement(node) {
                if (convertedLoopState && !convertedLoopState.labels) {
                    convertedLoopState.labels = ts.createMap();
                }
                var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
                return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
                    ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
                    : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
            }
            function visitIterationStatement(node, outermostLabeledStatement) {
                switch (node.kind) {
                    case 221 /* DoStatement */:
                    case 222 /* WhileStatement */:
                        return visitDoOrWhileStatement(node, outermostLabeledStatement);
                    case 223 /* ForStatement */:
                        return visitForStatement(node, outermostLabeledStatement);
                    case 224 /* ForInStatement */:
                        return visitForInStatement(node, outermostLabeledStatement);
                    case 225 /* ForOfStatement */:
                        return visitForOfStatement(node, outermostLabeledStatement);
                }
            }
            function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
                var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
                var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert);
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                return updated;
            }
            function visitDoOrWhileStatement(node, outermostLabeledStatement) {
                return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
            }
            function visitForStatement(node, outermostLabeledStatement) {
                return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement);
            }
            function visitForInStatement(node, outermostLabeledStatement) {
                return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
            }
            function visitForOfStatement(node, outermostLabeledStatement) {
                return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
            }
            function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
                var statements = [];
                var initializer = node.initializer;
                if (ts.isVariableDeclarationList(initializer)) {
                    if (node.initializer.flags & 3 /* BlockScoped */) {
                        enableSubstitutionsForBlockScopedBindings();
                    }
                    var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
                    if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
                        // This works whether the declaration is a var, let, or const.
                        // It will use rhsIterationValue _a[_i] as the initializer.
                        var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
                        var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
                        ts.setOriginalNode(declarationList, node.initializer);
                        // Adjust the source map range for the first declaration to align with the old
                        // emitter.
                        ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
                        statements.push(ts.createVariableStatement(
                        /*modifiers*/ undefined, declarationList));
                    }
                    else {
                        // The following call does not include the initializer, so we have
                        // to emit it separately.
                        statements.push(ts.setTextRange(ts.createVariableStatement(
                        /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
                            ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), 
                            /*type*/ undefined, boundValue)
                        ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
                    }
                }
                else {
                    // Initializer is an expression. Emit the expression in the body, so that it's
                    // evaluated on every iteration.
                    var assignment = ts.createAssignment(initializer, boundValue);
                    if (ts.isDestructuringAssignment(assignment)) {
                        ts.aggregateTransformFlags(assignment);
                        statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
                    }
                    else {
                        assignment.end = initializer.end;
                        statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
                    }
                }
                if (convertedLoopBodyStatements) {
                    return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
                }
                else {
                    var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
                    if (ts.isBlock(statement)) {
                        return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
                    }
                    else {
                        statements.push(statement);
                        return createSyntheticBlockForConvertedStatements(statements);
                    }
                }
            }
            function createSyntheticBlockForConvertedStatements(statements) {
                return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), 
                /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
            }
            function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
                // The following ES6 code:
                //
                //    for (let v of expr) { }
                //
                // should be emitted as
                //
                //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
                //        var v = _a[_i];
                //    }
                //
                // where _a and _i are temps emitted to capture the RHS and the counter,
                // respectively.
                // When the left hand side is an expression instead of a let declaration,
                // the "let v" is not emitted.
                // When the left hand side is a let/const, the v is renamed if there is
                // another v in scope.
                // Note that all assignments to the LHS are emitted in the body, including
                // all destructuring.
                // Note also that because an extra statement is needed to assign to the LHS,
                // for-of bodies are always emitted as blocks.
                var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
                // In the case where the user wrote an identifier as the RHS, like this:
                //
                //     for (let v of arr) { }
                //
                // we don't want to emit a temporary variable for the RHS, just use it directly.
                var counter = ts.createLoopVariable();
                var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
                // The old emitter does not emit source maps for the expression
                ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
                var forStatement = ts.setTextRange(ts.createFor(
                /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
                    ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
                    ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
                ]), node.expression), 2097152 /* NoHoisting */), 
                /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), 
                /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), 
                /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), 
                /*location*/ node);
                // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
                ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
                ts.setTextRange(forStatement, node);
                return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
            }
            function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) {
                var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
                var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
                var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
                var errorRecord = ts.createUniqueName("e");
                var catchVariable = ts.getGeneratedNameForNode(errorRecord);
                var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
                var values = ts.createValuesHelper(context, expression, node.expression);
                var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
                hoistVariableDeclaration(errorRecord);
                hoistVariableDeclaration(returnMethod);
                var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
                /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
                    ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression),
                    ts.createVariableDeclaration(result, /*type*/ undefined, next)
                ]), node.expression), 2097152 /* NoHoisting */), 
                /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), 
                /*incrementor*/ ts.createAssignment(result, next), 
                /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), 
                /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
                return ts.createTry(ts.createBlock([
                    ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
                ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
                    ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
                        ts.createPropertyAssignment("error", catchVariable)
                    ])))
                ]), 1 /* SingleLine */)), ts.createBlock([
                    ts.createTry(
                    /*tryBlock*/ ts.createBlock([
                        ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */),
                    ]), 
                    /*catchClause*/ undefined, 
                    /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
                        ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
                    ]), 1 /* SingleLine */))
                ]));
            }
            /**
             * Visits an ObjectLiteralExpression with computed property names.
             *
             * @param node An ObjectLiteralExpression node.
             */
            function visitObjectLiteralExpression(node) {
                // We are here because a ComputedPropertyName was used somewhere in the expression.
                var properties = node.properties;
                var numProperties = properties.length;
                // Find the first computed property.
                // Everything until that point can be emitted as part of the initial object literal.
                var numInitialProperties = numProperties;
                var numInitialPropertiesWithoutYield = numProperties;
                for (var i = 0; i < numProperties; i++) {
                    var property = properties[i];
                    if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
                        && i < numInitialPropertiesWithoutYield) {
                        numInitialPropertiesWithoutYield = i;
                    }
                    if (property.name.kind === 147 /* ComputedPropertyName */) {
                        numInitialProperties = i;
                        break;
                    }
                }
                if (numInitialProperties !== numProperties) {
                    if (numInitialPropertiesWithoutYield < numInitialProperties) {
                        numInitialProperties = numInitialPropertiesWithoutYield;
                    }
                    // For computed properties, we need to create a unique handle to the object
                    // literal so we can modify it without risking internal assignments tainting the object.
                    var temp = ts.createTempVariable(hoistVariableDeclaration);
                    // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
                    var expressions = [];
                    var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
                    if (node.multiLine) {
                        ts.startOnNewLine(assignment);
                    }
                    expressions.push(assignment);
                    addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
                    // We need to clone the temporary identifier so that we can write it on a
                    // new line
                    expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
                    return ts.inlineExpressions(expressions);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function shouldConvertIterationStatementBody(node) {
                return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
            }
            /**
             * Records constituents of name for the given variable to be hoisted in the outer scope.
             */
            function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
                if (!state.hoistedLocalVariables) {
                    state.hoistedLocalVariables = [];
                }
                visit(node.name);
                function visit(node) {
                    if (node.kind === 71 /* Identifier */) {
                        state.hoistedLocalVariables.push(node);
                    }
                    else {
                        for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
                            var element = _a[_i];
                            if (!ts.isOmittedExpression(element)) {
                                visit(element.name);
                            }
                        }
                    }
                }
            }
            function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) {
                if (!shouldConvertIterationStatementBody(node)) {
                    var saveAllowedNonLabeledJumps = void 0;
                    if (convertedLoopState) {
                        // we get here if we are trying to emit normal loop loop inside converted loop
                        // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
                        saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
                        convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
                    }
                    var result = convert
                        ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined)
                        : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
                    if (convertedLoopState) {
                        convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
                    }
                    return result;
                }
                var functionName = ts.createUniqueName("_loop");
                var loopInitializer;
                switch (node.kind) {
                    case 223 /* ForStatement */:
                    case 224 /* ForInStatement */:
                    case 225 /* ForOfStatement */:
                        var initializer = node.initializer;
                        if (initializer && initializer.kind === 236 /* VariableDeclarationList */) {
                            loopInitializer = initializer;
                        }
                        break;
                }
                // variables that will be passed to the loop as parameters
                var loopParameters = [];
                // variables declared in the loop initializer that will be changed inside the loop
                var loopOutParameters = [];
                if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
                    for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        processLoopVariableDeclaration(decl, loopParameters, loopOutParameters);
                    }
                }
                var outerConvertedLoopState = convertedLoopState;
                convertedLoopState = { loopOutParameters: loopOutParameters };
                if (outerConvertedLoopState) {
                    // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
                    // if outer converted loop has already accumulated some state - pass it through
                    if (outerConvertedLoopState.argumentsName) {
                        // outer loop has already used 'arguments' so we've already have some name to alias it
                        // use the same name in all nested loops
                        convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName;
                    }
                    if (outerConvertedLoopState.thisName) {
                        // outer loop has already used 'this' so we've already have some name to alias it
                        // use the same name in all nested loops
                        convertedLoopState.thisName = outerConvertedLoopState.thisName;
                    }
                    if (outerConvertedLoopState.hoistedLocalVariables) {
                        // we've already collected some non-block scoped variable declarations in enclosing loop
                        // use the same storage in nested loop
                        convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables;
                    }
                }
                startLexicalEnvironment();
                var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
                var lexicalEnvironment = endLexicalEnvironment();
                var currentState = convertedLoopState;
                convertedLoopState = outerConvertedLoopState;
                if (loopOutParameters.length || lexicalEnvironment) {
                    var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody];
                    if (loopOutParameters.length) {
                        copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4);
                    }
                    ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment);
                    loopBody = ts.createBlock(statements_4, /*multiline*/ true);
                }
                if (ts.isBlock(loopBody)) {
                    loopBody.multiLine = true;
                }
                else {
                    loopBody = ts.createBlock([loopBody], /*multiline*/ true);
                }
                var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0;
                var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0;
                var loopBodyFlags = 0;
                if (currentState.containsLexicalThis) {
                    loopBodyFlags |= 8 /* CapturesThis */;
                }
                if (isAsyncBlockContainingAwait) {
                    loopBodyFlags |= 262144 /* AsyncFunctionBody */;
                }
                var convertedLoopVariable = ts.createVariableStatement(
                /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
                    ts.createVariableDeclaration(functionName, 
                    /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
                    /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, 
                    /*name*/ undefined, 
                    /*typeParameters*/ undefined, loopParameters, 
                    /*type*/ undefined, loopBody), loopBodyFlags))
                ]), 2097152 /* NoHoisting */));
                var statements = [convertedLoopVariable];
                var extraVariableDeclarations;
                // propagate state from the inner loop to the outer loop if necessary
                if (currentState.argumentsName) {
                    // if alias for arguments is set
                    if (outerConvertedLoopState) {
                        // pass it to outer converted loop
                        outerConvertedLoopState.argumentsName = currentState.argumentsName;
                    }
                    else {
                        // this is top level converted loop and we need to create an alias for 'arguments' object
                        (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, 
                        /*type*/ undefined, ts.createIdentifier("arguments")));
                    }
                }
                if (currentState.thisName) {
                    // if alias for this is set
                    if (outerConvertedLoopState) {
                        // pass it to outer converted loop
                        outerConvertedLoopState.thisName = currentState.thisName;
                    }
                    else {
                        // this is top level converted loop so we need to create an alias for 'this' here
                        // NOTE:
                        // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
                        // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
                        (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, 
                        /*type*/ undefined, ts.createIdentifier("this")));
                    }
                }
                if (currentState.hoistedLocalVariables) {
                    // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
                    if (outerConvertedLoopState) {
                        // pass them to outer converted loop
                        outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables;
                    }
                    else {
                        if (!extraVariableDeclarations) {
                            extraVariableDeclarations = [];
                        }
                        // hoist collected variable declarations
                        for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) {
                            var identifier = _c[_b];
                            extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
                        }
                    }
                }
                // add extra variables to hold out parameters if necessary
                if (loopOutParameters.length) {
                    if (!extraVariableDeclarations) {
                        extraVariableDeclarations = [];
                    }
                    for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) {
                        var outParam = loopOutParameters_1[_d];
                        extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
                    }
                }
                // create variable statement to hold all introduced variable declarations
                if (extraVariableDeclarations) {
                    statements.push(ts.createVariableStatement(
                    /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
                }
                var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield);
                var loop;
                if (convert) {
                    loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements);
                }
                else {
                    var clone_3 = ts.getMutableClone(node);
                    // clean statement part
                    clone_3.statement = undefined;
                    // visit childnodes to transform initializer/condition/incrementor parts
                    clone_3 = ts.visitEachChild(clone_3, visitor, context);
                    // set loop statement
                    clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true);
                    // reset and re-aggregate the transform flags
                    clone_3.transformFlags = 0;
                    ts.aggregateTransformFlags(clone_3);
                    loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel);
                }
                statements.push(loop);
                return statements;
            }
            function copyOutParameter(outParam, copyDirection) {
                var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
                var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
                return ts.createBinary(target, 58 /* EqualsToken */, source);
            }
            function copyOutParameters(outParams, copyDirection, statements) {
                for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
                    var outParam = outParams_1[_i];
                    statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
                }
            }
            function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) {
                var outerConvertedLoopState = convertedLoopState;
                var statements = [];
                // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
                // simple loops are emitted as just 'loop()';
                // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
                var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
                    !state.labeledNonLocalBreaks &&
                    !state.labeledNonLocalContinues;
                var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; }));
                var callResult = isAsyncBlockContainingAwait
                    ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
                    : call;
                if (isSimpleLoop) {
                    statements.push(ts.createExpressionStatement(callResult));
                    copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements);
                }
                else {
                    var loopResultName = ts.createUniqueName("state");
                    var stateVariable = ts.createVariableStatement(
                    /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
                    statements.push(stateVariable);
                    copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements);
                    if (state.nonLocalJumps & 8 /* Return */) {
                        var returnStatement = void 0;
                        if (outerConvertedLoopState) {
                            outerConvertedLoopState.nonLocalJumps |= 8 /* Return */;
                            returnStatement = ts.createReturn(loopResultName);
                        }
                        else {
                            returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
                        }
                        statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
                    }
                    if (state.nonLocalJumps & 2 /* Break */) {
                        statements.push(ts.createIf(ts.createBinary(loopResultName, 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
                    }
                    if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
                        var caseClauses = [];
                        processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses);
                        processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses);
                        statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
                    }
                }
                return statements;
            }
            function setLabeledJump(state, isBreak, labelText, labelMarker) {
                if (isBreak) {
                    if (!state.labeledNonLocalBreaks) {
                        state.labeledNonLocalBreaks = ts.createMap();
                    }
                    state.labeledNonLocalBreaks.set(labelText, labelMarker);
                }
                else {
                    if (!state.labeledNonLocalContinues) {
                        state.labeledNonLocalContinues = ts.createMap();
                    }
                    state.labeledNonLocalContinues.set(labelText, labelMarker);
                }
            }
            function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
                if (!table) {
                    return;
                }
                table.forEach(function (labelMarker, labelText) {
                    var statements = [];
                    // if there are no outer converted loop or outer label in question is located inside outer converted loop
                    // then emit labeled break\continue
                    // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
                    if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
                        var label = ts.createIdentifier(labelText);
                        statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
                    }
                    else {
                        setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
                        statements.push(ts.createReturn(loopResultName));
                    }
                    caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
                });
            }
            function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) {
                var name = decl.name;
                if (ts.isBindingPattern(name)) {
                    for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
                        var element = _a[_i];
                        if (!ts.isOmittedExpression(element)) {
                            processLoopVariableDeclaration(element, loopParameters, loopOutParameters);
                        }
                    }
                }
                else {
                    loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
                    if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) {
                        var outParamName = ts.createUniqueName("out_" + ts.idText(name));
                        loopOutParameters.push({ originalName: name, outParamName: outParamName });
                    }
                }
            }
            /**
             * Adds the members of an object literal to an array of expressions.
             *
             * @param expressions An array of expressions.
             * @param node An ObjectLiteralExpression node.
             * @param receiver The receiver for members of the ObjectLiteralExpression.
             * @param numInitialNonComputedProperties The number of initial properties without
             *                                        computed property names.
             */
            function addObjectLiteralMembers(expressions, node, receiver, start) {
                var properties = node.properties;
                var numProperties = properties.length;
                for (var i = start; i < numProperties; i++) {
                    var property = properties[i];
                    switch (property.kind) {
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            var accessors = ts.getAllAccessorDeclarations(node.properties, property);
                            if (property === accessors.firstAccessor) {
                                expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
                            }
                            break;
                        case 154 /* MethodDeclaration */:
                            expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
                            break;
                        case 273 /* PropertyAssignment */:
                            expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
                            break;
                        case 274 /* ShorthandPropertyAssignment */:
                            expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
                            break;
                        default:
                            ts.Debug.failBadSyntaxKind(node);
                            break;
                    }
                }
            }
            /**
             * Transforms a PropertyAssignment node into an expression.
             *
             * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
             * @param property The PropertyAssignment node.
             * @param receiver The receiver for the assignment.
             */
            function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
                var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
                ts.setTextRange(expression, property);
                if (startsOnNewLine) {
                    ts.startOnNewLine(expression);
                }
                return expression;
            }
            /**
             * Transforms a ShorthandPropertyAssignment node into an expression.
             *
             * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
             * @param property The ShorthandPropertyAssignment node.
             * @param receiver The receiver for the assignment.
             */
            function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
                var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
                ts.setTextRange(expression, property);
                if (startsOnNewLine) {
                    ts.startOnNewLine(expression);
                }
                return expression;
            }
            /**
             * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
             *
             * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
             * @param method The MethodDeclaration node.
             * @param receiver The receiver for the assignment.
             */
            function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
                var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
                var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
                ts.setTextRange(expression, method);
                if (startsOnNewLine) {
                    ts.startOnNewLine(expression);
                }
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
                return expression;
            }
            function visitCatchClause(node) {
                var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
                var updated;
                ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
                if (ts.isBindingPattern(node.variableDeclaration.name)) {
                    var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
                    var newVariableDeclaration = ts.createVariableDeclaration(temp);
                    ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
                    var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
                    var list = ts.createVariableDeclarationList(vars);
                    ts.setTextRange(list, node.variableDeclaration);
                    var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
                    updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
                }
                else {
                    updated = ts.visitEachChild(node, visitor, context);
                }
                exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                return updated;
            }
            function addStatementToStartOfBlock(block, statement) {
                var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
                return ts.updateBlock(block, [statement].concat(transformedStatements));
            }
            /**
             * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
             * PropertyAssignment.
             *
             * @param node A MethodDeclaration node.
             */
            function visitMethodDeclaration(node) {
                // We should only get here for methods on an object literal with regular identifier names.
                // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
                // Methods with computed property names are handled in visitObjectLiteralExpression.
                ts.Debug.assert(!ts.isComputedPropertyName(node.name));
                var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
                ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
                return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), 
                /*location*/ node);
            }
            /**
             * Visits an AccessorDeclaration of an ObjectLiteralExpression.
             *
             * @param node An AccessorDeclaration node.
             */
            function visitAccessorDeclaration(node) {
                ts.Debug.assert(!ts.isComputedPropertyName(node.name));
                var savedConvertedLoopState = convertedLoopState;
                convertedLoopState = undefined;
                var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
                var updated;
                var parameters = ts.visitParameterList(node.parameters, visitor, context);
                var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */)
                    ? transformFunctionBody(node)
                    : visitFunctionBodyDownLevel(node);
                if (node.kind === 156 /* GetAccessor */) {
                    updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
                }
                else {
                    updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
                }
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
                convertedLoopState = savedConvertedLoopState;
                return updated;
            }
            /**
             * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
             *
             * @param node A ShorthandPropertyAssignment node.
             */
            function visitShorthandPropertyAssignment(node) {
                return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), 
                /*location*/ node);
            }
            function visitComputedPropertyName(node) {
                var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
                var updated = ts.visitEachChild(node, visitor, context);
                exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
                return updated;
            }
            /**
             * Visits a YieldExpression node.
             *
             * @param node A YieldExpression node.
             */
            function visitYieldExpression(node) {
                // `yield` expressions are transformed using the generators transformer.
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits an ArrayLiteralExpression that contains a spread element.
             *
             * @param node An ArrayLiteralExpression node.
             */
            function visitArrayLiteralExpression(node) {
                if (node.transformFlags & 64 /* ES2015 */) {
                    // We are here because we contain a SpreadElementExpression.
                    return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a CallExpression that contains either a spread element or `super`.
             *
             * @param node a CallExpression.
             */
            function visitCallExpression(node) {
                if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
                    return visitTypeScriptClassWrapper(node);
                }
                if (node.transformFlags & 64 /* ES2015 */) {
                    return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
                }
                return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
                /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
            }
            function visitTypeScriptClassWrapper(node) {
                // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
                // The wrapper has a form similar to:
                //
                //  (function() {
                //      class C { // 1
                //      }
                //      C.x = 1; // 2
                //      return C;
                //  }())
                //
                // When we transform the class, we end up with something like this:
                //
                //  (function () {
                //      var C = (function () { // 3
                //          function C() {
                //          }
                //          return C; // 4
                //      }());
                //      C.x = 1;
                //      return C;
                //  }())
                //
                // We want to simplify the two nested IIFEs to end up with something like this:
                //
                //  (function () {
                //      function C() {
                //      }
                //      C.x = 1;
                //      return C;
                //  }())
                // We skip any outer expressions in a number of places to get to the innermost
                // expression, but we will restore them later to preserve comments and source maps.
                var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
                // The class statements are the statements generated by visiting the first statement with initializer of the
                // body (1), while all other statements are added to remainingStatements (2)
                var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
                var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
                var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
                var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
                var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
                // We know there is only one variable declaration here as we verified this in an
                // earlier call to isTypeScriptClassWrapper
                var variable = varStatement.declarationList.declarations[0];
                var initializer = ts.skipOuterExpressions(variable.initializer);
                // Under certain conditions, the 'ts' transformer may introduce a class alias, which
                // we see as an assignment, for example:
                //
                //  (function () {
                //      var C_1;
                //      var C = C_1 = (function () {
                //          function C() {
                //          }
                //          C.x = function () { return C_1; }
                //          return C;
                //      }());
                //      C = C_1 = __decorate([dec], C);
                //      return C;
                //  }())
                //
                var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
                // The underlying call (3) is another IIFE that may contain a '_super' argument.
                var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
                var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
                var funcStatements = func.body.statements;
                var classBodyStart = 0;
                var classBodyEnd = -1;
                var statements = [];
                if (aliasAssignment) {
                    // If we have a class alias assignment, we need to move it to the down-level constructor
                    // function we generated for the class.
                    var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
                    if (extendsCall) {
                        statements.push(extendsCall);
                        classBodyStart++;
                    }
                    // The next statement is the function declaration.
                    statements.push(funcStatements[classBodyStart]);
                    classBodyStart++;
                    // Add the class alias following the declaration.
                    statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
                }
                // Find the trailing 'return' statement (4)
                while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
                    classBodyEnd--;
                }
                // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
                // as we already have one that has been introduced by the 'ts' transformer.
                ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
                if (classBodyEnd < -1) {
                    // If there were any hoisted declarations following the return statement, we should
                    // append them.
                    ts.addRange(statements, funcStatements, classBodyEnd + 1);
                }
                // Add the remaining statements of the outer wrapper.
                ts.addRange(statements, remainingStatements);
                // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
                // after the remaining statements from the 'ts' transformer.
                ts.addRange(statements, classStatements, /*start*/ 1);
                // Recreate any outer parentheses or partially-emitted expressions to preserve source map
                // and comment locations.
                return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, 
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, func.parameters, 
                /*type*/ undefined, ts.updateBlock(func.body, statements))), 
                /*typeArguments*/ undefined, call.arguments))));
            }
            function visitImmediateSuperCallInBody(node) {
                return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
            }
            function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
                // We are here either because SuperKeyword was used somewhere in the expression, or
                // because we contain a SpreadElementExpression.
                if (node.transformFlags & 524288 /* ContainsSpread */ ||
                    node.expression.kind === 97 /* SuperKeyword */ ||
                    ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
                    var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
                    if (node.expression.kind === 97 /* SuperKeyword */) {
                        ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
                    }
                    var resultingCall = void 0;
                    if (node.transformFlags & 524288 /* ContainsSpread */) {
                        // [source]
                        //      f(...a, b)
                        //      x.m(...a, b)
                        //      super(...a, b)
                        //      super.m(...a, b) // in static
                        //      super.m(...a, b) // in instance
                        //
                        // [output]
                        //      f.apply(void 0, a.concat([b]))
                        //      (_a = x).m.apply(_a, a.concat([b]))
                        //      _super.apply(this, a.concat([b]))
                        //      _super.m.apply(this, a.concat([b]))
                        //      _super.prototype.m.apply(this, a.concat([b]))
                        resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
                    }
                    else {
                        // [source]
                        //      super(a)
                        //      super.m(a) // in static
                        //      super.m(a) // in instance
                        //
                        // [output]
                        //      _super.call(this, a)
                        //      _super.m.call(this, a)
                        //      _super.prototype.m.call(this, a)
                        resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), 
                        /*location*/ node);
                    }
                    if (node.expression.kind === 97 /* SuperKeyword */) {
                        var actualThis = ts.createThis();
                        ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
                        var initializer = ts.createLogicalOr(resultingCall, actualThis);
                        resultingCall = assignToCapturedThis
                            ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
                            : initializer;
                    }
                    return ts.setOriginalNode(resultingCall, node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a NewExpression that contains a spread element.
             *
             * @param node A NewExpression node.
             */
            function visitNewExpression(node) {
                if (node.transformFlags & 524288 /* ContainsSpread */) {
                    // We are here because we contain a SpreadElementExpression.
                    // [source]
                    //      new C(...a)
                    //
                    // [output]
                    //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
                    var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
                    return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), 
                    /*typeArguments*/ undefined, []);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Transforms an array of Expression nodes that contains a SpreadExpression.
             *
             * @param elements The array of Expression nodes.
             * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
             * @param multiLine A value indicating whether the result should be emitted on multiple lines.
             */
            function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
                // [source]
                //      [a, ...b, c]
                //
                // [output]
                //      [a].concat(b, [c])
                // Map spans of spread expressions into their expressions and spans of other
                // expressions into an array literal.
                var numElements = elements.length;
                var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
                    return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
                }));
                if (compilerOptions.downlevelIteration) {
                    if (segments.length === 1) {
                        var firstSegment = segments[0];
                        if (ts.isCallExpression(firstSegment)
                            && ts.isIdentifier(firstSegment.expression)
                            && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
                            && firstSegment.expression.escapedText === "___spread") {
                            return segments[0];
                        }
                    }
                    return ts.createSpreadHelper(context, segments);
                }
                else {
                    if (segments.length === 1) {
                        var firstElement = elements[0];
                        return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */
                            ? ts.createArraySlice(segments[0])
                            : segments[0];
                    }
                    // Rewrite using the pattern <segment0>.concat(<segment1>, <segment2>, ...)
                    return ts.createArrayConcat(segments.shift(), segments);
                }
            }
            function partitionSpread(node) {
                return ts.isSpreadElement(node)
                    ? visitSpanOfSpreads
                    : visitSpanOfNonSpreads;
            }
            function visitSpanOfSpreads(chunk) {
                return ts.map(chunk, visitExpressionOfSpread);
            }
            function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
                return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
            }
            function visitSpreadElement(node) {
                return ts.visitNode(node.expression, visitor, ts.isExpression);
            }
            /**
             * Transforms the expression of a SpreadExpression node.
             *
             * @param node A SpreadExpression node.
             */
            function visitExpressionOfSpread(node) {
                return ts.visitNode(node.expression, visitor, ts.isExpression);
            }
            /**
             * Visits a template literal.
             *
             * @param node A template literal.
             */
            function visitTemplateLiteral(node) {
                return ts.setTextRange(ts.createLiteral(node.text), node);
            }
            /**
             * Visits a string literal with an extended unicode escape.
             *
             * @param node A string literal.
             */
            function visitStringLiteral(node) {
                if (node.hasExtendedUnicodeEscape) {
                    return ts.setTextRange(ts.createLiteral(node.text), node);
                }
                return node;
            }
            /**
             * Visits a binary or octal (ES6) numeric literal.
             *
             * @param node A string literal.
             */
            function visitNumericLiteral(node) {
                if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
                    return ts.setTextRange(ts.createNumericLiteral(node.text), node);
                }
                return node;
            }
            /**
             * Visits a TaggedTemplateExpression node.
             *
             * @param node A TaggedTemplateExpression node.
             */
            function visitTaggedTemplateExpression(node) {
                // Visit the tag expression
                var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
                // Build up the template arguments and the raw and cooked strings for the template.
                // We start out with 'undefined' for the first argument and revisit later
                // to avoid walking over the template string twice and shifting all our arguments over after the fact.
                var templateArguments = [undefined];
                var cookedStrings = [];
                var rawStrings = [];
                var template = node.template;
                if (ts.isNoSubstitutionTemplateLiteral(template)) {
                    cookedStrings.push(ts.createLiteral(template.text));
                    rawStrings.push(getRawLiteral(template));
                }
                else {
                    cookedStrings.push(ts.createLiteral(template.head.text));
                    rawStrings.push(getRawLiteral(template.head));
                    for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
                        var templateSpan = _a[_i];
                        cookedStrings.push(ts.createLiteral(templateSpan.literal.text));
                        rawStrings.push(getRawLiteral(templateSpan.literal));
                        templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
                    }
                }
                var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
                // Create a variable to cache the template object if we're in a module.
                // Do not do this in the global scope, as any variable we currently generate could conflict with
                // variables from outside of the current compilation. In the future, we can revisit this behavior.
                if (ts.isExternalModule(currentSourceFile)) {
                    var tempVar = ts.createUniqueName("templateObject");
                    recordTaggedTemplateString(tempVar);
                    templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
                }
                else {
                    templateArguments[0] = helperCall;
                }
                return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
            }
            /**
             * Creates an ES5 compatible literal from an ES6 template literal.
             *
             * @param node The ES6 template literal.
             */
            function getRawLiteral(node) {
                // Find original source text, since we need to emit the raw strings of the tagged template.
                // The raw strings contain the (escaped) strings of what the user wrote.
                // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
                var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
                // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
                // thus we need to remove those characters.
                // First template piece starts with "`", others with "}"
                // Last template piece ends with "`", others with "${"
                var isLast = node.kind === 13 /* NoSubstitutionTemplateLiteral */ || node.kind === 16 /* TemplateTail */;
                text = text.substring(1, text.length - (isLast ? 1 : 2));
                // Newline normalization:
                // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
                // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
                text = text.replace(/\r\n?/g, "\n");
                return ts.setTextRange(ts.createLiteral(text), node);
            }
            /**
             * Visits a TemplateExpression node.
             *
             * @param node A TemplateExpression node.
             */
            function visitTemplateExpression(node) {
                var expressions = [];
                addTemplateHead(expressions, node);
                addTemplateSpans(expressions, node);
                // createAdd will check if each expression binds less closely than binary '+'.
                // If it does, it wraps the expression in parentheses. Otherwise, something like
                //    `abc${ 1 << 2 }`
                // becomes
                //    "abc" + 1 << 2 + ""
                // which is really
                //    ("abc" + 1) << (2 + "")
                // rather than
                //    "abc" + (1 << 2) + ""
                var expression = ts.reduceLeft(expressions, ts.createAdd);
                if (ts.nodeIsSynthesized(expression)) {
                    expression.pos = node.pos;
                    expression.end = node.end;
                }
                return expression;
            }
            /**
             * Gets a value indicating whether we need to include the head of a TemplateExpression.
             *
             * @param node A TemplateExpression node.
             */
            function shouldAddTemplateHead(node) {
                // If this expression has an empty head literal and the first template span has a non-empty
                // literal, then emitting the empty head literal is not necessary.
                //     `${ foo } and ${ bar }`
                // can be emitted as
                //     foo + " and " + bar
                // This is because it is only required that one of the first two operands in the emit
                // output must be a string literal, so that the other operand and all following operands
                // are forced into strings.
                //
                // If the first template span has an empty literal, then the head must still be emitted.
                //     `${ foo }${ bar }`
                // must still be emitted as
                //     "" + foo + bar
                // There is always atleast one templateSpan in this code path, since
                // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
                ts.Debug.assert(node.templateSpans.length !== 0);
                return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
            }
            /**
             * Adds the head of a TemplateExpression to an array of expressions.
             *
             * @param expressions An array of expressions.
             * @param node A TemplateExpression node.
             */
            function addTemplateHead(expressions, node) {
                if (!shouldAddTemplateHead(node)) {
                    return;
                }
                expressions.push(ts.createLiteral(node.head.text));
            }
            /**
             * Visits and adds the template spans of a TemplateExpression to an array of expressions.
             *
             * @param expressions An array of expressions.
             * @param node A TemplateExpression node.
             */
            function addTemplateSpans(expressions, node) {
                for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
                    var span = _a[_i];
                    expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
                    // Only emit if the literal is non-empty.
                    // The binary '+' operator is left-associative, so the first string concatenation
                    // with the head will force the result up to this point to be a string.
                    // Emitting a '+ ""' has no semantic effect for middles and tails.
                    if (span.literal.text.length !== 0) {
                        expressions.push(ts.createLiteral(span.literal.text));
                    }
                }
            }
            /**
             * Visits the `super` keyword
             */
            function visitSuperKeyword(isExpressionOfCall) {
                return hierarchyFacts & 8 /* NonStaticClassElement */
                    && !isExpressionOfCall
                    ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype")
                    : ts.createFileLevelUniqueName("_super");
            }
            function visitMetaProperty(node) {
                if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") {
                    if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
                        hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
                    }
                    else {
                        hierarchyFacts |= 16384 /* NewTarget */;
                    }
                    return ts.createFileLevelUniqueName("_newTarget");
                }
                return node;
            }
            /**
             * Called by the printer just before a node is printed.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to be printed.
             * @param emitCallback The callback used to emit the node.
             */
            function onEmitNode(hint, node, emitCallback) {
                if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
                    // If we are tracking a captured `this`, keep track of the enclosing function.
                    var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
                        ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
                        : 65 /* FunctionIncludes */);
                    previousOnEmitNode(hint, node, emitCallback);
                    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
                    return;
                }
                previousOnEmitNode(hint, node, emitCallback);
            }
            /**
             * Enables a more costly code path for substitutions when we determine a source file
             * contains block-scoped bindings (e.g. `let` or `const`).
             */
            function enableSubstitutionsForBlockScopedBindings() {
                if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
                    enabledSubstitutions |= 2 /* BlockScopedBindings */;
                    context.enableSubstitution(71 /* Identifier */);
                }
            }
            /**
             * Enables a more costly code path for substitutions when we determine a source file
             * contains a captured `this`.
             */
            function enableSubstitutionsForCapturedThis() {
                if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
                    enabledSubstitutions |= 1 /* CapturedThis */;
                    context.enableSubstitution(99 /* ThisKeyword */);
                    context.enableEmitNotification(155 /* Constructor */);
                    context.enableEmitNotification(154 /* MethodDeclaration */);
                    context.enableEmitNotification(156 /* GetAccessor */);
                    context.enableEmitNotification(157 /* SetAccessor */);
                    context.enableEmitNotification(195 /* ArrowFunction */);
                    context.enableEmitNotification(194 /* FunctionExpression */);
                    context.enableEmitNotification(237 /* FunctionDeclaration */);
                }
            }
            /**
             * Hooks node substitutions.
             *
             * @param hint The context for the emitter.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (hint === 1 /* Expression */) {
                    return substituteExpression(node);
                }
                if (ts.isIdentifier(node)) {
                    return substituteIdentifier(node);
                }
                return node;
            }
            /**
             * Hooks substitutions for non-expression identifiers.
             */
            function substituteIdentifier(node) {
                // Only substitute the identifier if we have enabled substitutions for block-scoped
                // bindings.
                if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
                    var original = ts.getParseTreeNode(node, ts.isIdentifier);
                    if (original && isNameOfDeclarationWithCollidingName(original)) {
                        return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
                    }
                }
                return node;
            }
            /**
             * Determines whether a name is the name of a declaration with a colliding name.
             * NOTE: This function expects to be called with an original source tree node.
             *
             * @param node An original source tree node.
             */
            function isNameOfDeclarationWithCollidingName(node) {
                switch (node.parent.kind) {
                    case 184 /* BindingElement */:
                    case 238 /* ClassDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 235 /* VariableDeclaration */:
                        return node.parent.name === node
                            && resolver.isDeclarationWithCollidingName(node.parent);
                }
                return false;
            }
            /**
             * Substitutes an expression.
             *
             * @param node An Expression node.
             */
            function substituteExpression(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return substituteExpressionIdentifier(node);
                    case 99 /* ThisKeyword */:
                        return substituteThisKeyword(node);
                }
                return node;
            }
            /**
             * Substitutes an expression identifier.
             *
             * @param node An Identifier node.
             */
            function substituteExpressionIdentifier(node) {
                if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
                    var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
                    if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
                        return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
                    }
                }
                return node;
            }
            function isPartOfClassBody(declaration, node) {
                var currentNode = ts.getParseTreeNode(node);
                if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
                    // if the node has no correlation to a parse tree node, its definitely not
                    // part of the body.
                    // if the node is outside of the document range of the declaration, its
                    // definitely not part of the body.
                    return false;
                }
                var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
                while (currentNode) {
                    if (currentNode === blockScope || currentNode === declaration) {
                        // if we are in the enclosing block scope of the declaration, we are definitely
                        // not inside the class body.
                        return false;
                    }
                    if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
                        return true;
                    }
                    currentNode = currentNode.parent;
                }
                return false;
            }
            /**
             * Substitutes `this` when contained within an arrow function.
             *
             * @param node The ThisKeyword node.
             */
            function substituteThisKeyword(node) {
                if (enabledSubstitutions & 1 /* CapturedThis */
                    && hierarchyFacts & 16 /* CapturesThis */) {
                    return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
                }
                return node;
            }
            function getClassMemberPrefix(node, member) {
                return ts.hasModifier(member, 32 /* Static */)
                    ? ts.getInternalName(node)
                    : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
            }
            function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
                if (!constructor || !hasExtendsClause) {
                    return false;
                }
                if (ts.some(constructor.parameters)) {
                    return false;
                }
                var statement = ts.firstOrUndefined(constructor.body.statements);
                if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) {
                    return false;
                }
                var statementExpression = statement.expression;
                if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) {
                    return false;
                }
                var callTarget = statementExpression.expression;
                if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97 /* SuperKeyword */) {
                    return false;
                }
                var callArgument = ts.singleOrUndefined(statementExpression.arguments);
                if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) {
                    return false;
                }
                var expression = callArgument.expression;
                return ts.isIdentifier(expression) && expression.escapedText === "arguments";
            }
        }
        ts.transformES2015 = transformES2015;
        function createExtendsHelper(context, name) {
            context.requestEmitHelper(extendsHelper);
            return ts.createCall(ts.getHelperName("__extends"), 
            /*typeArguments*/ undefined, [
                name,
                ts.createFileLevelUniqueName("_super")
            ]);
        }
        function createTemplateObjectHelper(context, cooked, raw) {
            context.requestEmitHelper(templateObjectHelper);
            return ts.createCall(ts.getHelperName("__makeTemplateObject"), 
            /*typeArguments*/ undefined, [
                cooked,
                raw
            ]);
        }
        var extendsHelper = {
            name: "typescript:extends",
            scoped: false,
            priority: 0,
            text: "\n            var __extends = (this && this.__extends) || (function () {\n                var extendStatics = function (d, b) {\n                    extendStatics = Object.setPrototypeOf ||\n                        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n                        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n                    return extendStatics(d, b);\n                }\n\n                return function (d, b) {\n                    extendStatics(d, b);\n                    function __() { this.constructor = d; }\n                    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n                };\n            })();"
        };
        var templateObjectHelper = {
            name: "typescript:makeTemplateObject",
            scoped: false,
            priority: 0,
            text: "\n            var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n                if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n                return cooked;\n            };"
        };
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        /**
         * Transforms ES5 syntax into ES3 syntax.
         *
         * @param context Context and state information for the transformation.
         */
        function transformES5(context) {
            var compilerOptions = context.getCompilerOptions();
            // enable emit notification only if using --jsx preserve or react-native
            var previousOnEmitNode;
            var noSubstitution;
            if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
                previousOnEmitNode = context.onEmitNode;
                context.onEmitNode = onEmitNode;
                context.enableEmitNotification(260 /* JsxOpeningElement */);
                context.enableEmitNotification(261 /* JsxClosingElement */);
                context.enableEmitNotification(259 /* JsxSelfClosingElement */);
                noSubstitution = [];
            }
            var previousOnSubstituteNode = context.onSubstituteNode;
            context.onSubstituteNode = onSubstituteNode;
            context.enableSubstitution(187 /* PropertyAccessExpression */);
            context.enableSubstitution(273 /* PropertyAssignment */);
            return ts.chainBundle(transformSourceFile);
            /**
             * Transforms an ES5 source file to ES3.
             *
             * @param node A SourceFile
             */
            function transformSourceFile(node) {
                return node;
            }
            /**
             * Called by the printer just before a node is printed.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emitCallback A callback used to emit the node.
             */
            function onEmitNode(hint, node, emitCallback) {
                switch (node.kind) {
                    case 260 /* JsxOpeningElement */:
                    case 261 /* JsxClosingElement */:
                    case 259 /* JsxSelfClosingElement */:
                        var tagName = node.tagName;
                        noSubstitution[ts.getOriginalNodeId(tagName)] = true;
                        break;
                }
                previousOnEmitNode(hint, node, emitCallback);
            }
            /**
             * Hooks node substitutions.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                if (node.id && noSubstitution && noSubstitution[node.id]) {
                    return previousOnSubstituteNode(hint, node);
                }
                node = previousOnSubstituteNode(hint, node);
                if (ts.isPropertyAccessExpression(node)) {
                    return substitutePropertyAccessExpression(node);
                }
                else if (ts.isPropertyAssignment(node)) {
                    return substitutePropertyAssignment(node);
                }
                return node;
            }
            /**
             * Substitutes a PropertyAccessExpression whose name is a reserved word.
             *
             * @param node A PropertyAccessExpression
             */
            function substitutePropertyAccessExpression(node) {
                var literalName = trySubstituteReservedName(node.name);
                if (literalName) {
                    return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
                }
                return node;
            }
            /**
             * Substitutes a PropertyAssignment whose name is a reserved word.
             *
             * @param node A PropertyAssignment
             */
            function substitutePropertyAssignment(node) {
                var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
                if (literalName) {
                    return ts.updatePropertyAssignment(node, literalName, node.initializer);
                }
                return node;
            }
            /**
             * If an identifier name is a reserved word, returns a string literal for the name.
             *
             * @param name An Identifier
             */
            function trySubstituteReservedName(name) {
                var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
                if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) {
                    return ts.setTextRange(ts.createLiteral(name), name);
                }
                return undefined;
            }
        }
        ts.transformES5 = transformES5;
    })(ts || (ts = {}));
    // Transforms generator functions into a compatible ES5 representation with similar runtime
    // semantics. This is accomplished by first transforming the body of each generator
    // function into an intermediate representation that is the compiled into a JavaScript
    // switch statement.
    //
    // Many functions in this transformer will contain comments indicating the expected
    // intermediate representation. For illustrative purposes, the following intermediate
    // language is used to define this intermediate representation:
    //
    //  .nop                            - Performs no operation.
    //  .local NAME, ...                - Define local variable declarations.
    //  .mark LABEL                     - Mark the location of a label.
    //  .br LABEL                       - Jump to a label. If jumping out of a protected
    //                                    region, all .finally blocks are executed.
    //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
    //                                    If jumping out of a protected region, all .finally
    //                                    blocks are executed.
    //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
    //                                    If jumping out of a protected region, all .finally
    //                                    blocks are executed.
    //  .yield (x)                      - Yield the value of the optional expression `x`.
    //                                    Resume at the next label.
    //  .yieldstar (x)                  - Delegate yield to the value of the optional
    //                                    expression `x`. Resume at the next label.
    //                                    NOTE: `x` must be an Iterator, not an Iterable.
    //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
    //                                    "break" abrupt completions jump to the CONTINUE or
    //                                    BREAK labels, respectively.
    //  .endloop                        - Marks the end of a loop.
    //  .with (x)                       - Marks the beginning of a WithStatement block, using
    //                                    the supplied expression.
    //  .endwith                        - Marks the end of a WithStatement.
    //  .switch                         - Marks the beginning of a SwitchStatement.
    //  .endswitch                      - Marks the end of a SwitchStatement.
    //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
    //                                    supplied name.
    //  .endlabeled                     - Marks the end of a LabeledStatement.
    //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
    //                                    labels for each block.
    //  .catch (x)                      - Marks the beginning of a catch block.
    //  .finally                        - Marks the beginning of a finally block.
    //  .endfinally                     - Marks the end of a finally block.
    //  .endtry                         - Marks the end of a protected region.
    //  .throw (x)                      - Throws the value of the expression `x`.
    //  .return (x)                     - Returns the value of the expression `x`.
    //
    // In addition, the illustrative intermediate representation introduces some special
    // variables:
    //
    //  %sent%                          - Either returns the next value sent to the generator,
    //                                    returns the result of a delegated yield, or throws
    //                                    the exception sent to the generator.
    //  %error%                         - Returns the value of the current exception in a
    //                                    catch block.
    //
    // This intermediate representation is then compiled into JavaScript syntax. The resulting
    // compilation output looks something like the following:
    //
    //  function f() {
    //      var /*locals*/;
    //      /*functions*/
    //      return __generator(function (state) {
    //          switch (state.label) {
    //              /*cases per label*/
    //          }
    //      });
    //  }
    //
    // Each of the above instructions corresponds to JavaScript emit similar to the following:
    //
    //  .local NAME                   | var NAME;
    // -------------------------------|----------------------------------------------
    //  .mark LABEL                   | case LABEL:
    // -------------------------------|----------------------------------------------
    //  .br LABEL                     |     return [3 /*break*/, LABEL];
    // -------------------------------|----------------------------------------------
    //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
    // -------------------------------|----------------------------------------------
    //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
    // -------------------------------|----------------------------------------------
    //  .yield (x)                    |     return [4 /*yield*/, x];
    //  .mark RESUME                  | case RESUME:
    //      a = %sent%;               |     a = state.sent();
    // -------------------------------|----------------------------------------------
    //  .yieldstar (x)                |     return [5 /*yield**/, x];
    //  .mark RESUME                  | case RESUME:
    //      a = %sent%;               |     a = state.sent();
    // -------------------------------|----------------------------------------------
    //  .with (_a)                    |     with (_a) {
    //      a();                      |         a();
    //                                |     }
    //                                |     state.label = LABEL;
    //  .mark LABEL                   | case LABEL:
    //                                |     with (_a) {
    //      b();                      |         b();
    //                                |     }
    //  .endwith                      |
    // -------------------------------|----------------------------------------------
    //                                | case 0:
    //                                |     state.trys = [];
    //                                | ...
    //  .try TRY, CATCH, FINALLY, END |
    //  .mark TRY                     | case TRY:
    //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
    //  .nop                          |
    //      a();                      |     a();
    //  .br END                       |     return [3 /*break*/, END];
    //  .catch (e)                    |
    //  .mark CATCH                   | case CATCH:
    //                                |     e = state.sent();
    //      b();                      |     b();
    //  .br END                       |     return [3 /*break*/, END];
    //  .finally                      |
    //  .mark FINALLY                 | case FINALLY:
    //      c();                      |     c();
    //  .endfinally                   |     return [7 /*endfinally*/];
    //  .endtry                       |
    //  .mark END                     | case END:
    /*@internal*/
    var ts;
    (function (ts) {
        var OpCode;
        (function (OpCode) {
            OpCode[OpCode["Nop"] = 0] = "Nop";
            OpCode[OpCode["Statement"] = 1] = "Statement";
            OpCode[OpCode["Assign"] = 2] = "Assign";
            OpCode[OpCode["Break"] = 3] = "Break";
            OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
            OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
            OpCode[OpCode["Yield"] = 6] = "Yield";
            OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
            OpCode[OpCode["Return"] = 8] = "Return";
            OpCode[OpCode["Throw"] = 9] = "Throw";
            OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
        })(OpCode || (OpCode = {}));
        // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
        var BlockAction;
        (function (BlockAction) {
            BlockAction[BlockAction["Open"] = 0] = "Open";
            BlockAction[BlockAction["Close"] = 1] = "Close";
        })(BlockAction || (BlockAction = {}));
        // the kind for a generated code block in a FunctionBuilder
        var CodeBlockKind;
        (function (CodeBlockKind) {
            CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
            CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
            CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
            CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
            CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
        })(CodeBlockKind || (CodeBlockKind = {}));
        // the state for a generated code exception block
        var ExceptionBlockState;
        (function (ExceptionBlockState) {
            ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
            ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
            ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
            ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
        })(ExceptionBlockState || (ExceptionBlockState = {}));
        // NOTE: changes to this enum should be reflected in the __generator helper.
        var Instruction;
        (function (Instruction) {
            Instruction[Instruction["Next"] = 0] = "Next";
            Instruction[Instruction["Throw"] = 1] = "Throw";
            Instruction[Instruction["Return"] = 2] = "Return";
            Instruction[Instruction["Break"] = 3] = "Break";
            Instruction[Instruction["Yield"] = 4] = "Yield";
            Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
            Instruction[Instruction["Catch"] = 6] = "Catch";
            Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
        })(Instruction || (Instruction = {}));
        function getInstructionName(instruction) {
            switch (instruction) {
                case 2 /* Return */: return "return";
                case 3 /* Break */: return "break";
                case 4 /* Yield */: return "yield";
                case 5 /* YieldStar */: return "yield*";
                case 7 /* Endfinally */: return "endfinally";
                default: return undefined; // TODO: GH#18217
            }
        }
        function transformGenerators(context) {
            var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
            var compilerOptions = context.getCompilerOptions();
            var languageVersion = ts.getEmitScriptTarget(compilerOptions);
            var resolver = context.getEmitResolver();
            var previousOnSubstituteNode = context.onSubstituteNode;
            context.onSubstituteNode = onSubstituteNode;
            var renamedCatchVariables;
            var renamedCatchVariableDeclarations;
            var inGeneratorFunctionBody;
            var inStatementContainingYield;
            // The following three arrays store information about generated code blocks.
            // All three arrays are correlated by their index. This approach is used over allocating
            // objects to store the same information to avoid GC overhead.
            //
            var blocks; // Information about the code block
            var blockOffsets; // The operation offset at which a code block begins or ends
            var blockActions; // Whether the code block is opened or closed
            var blockStack; // A stack of currently open code blocks
            // Labels are used to mark locations in the code that can be the target of a Break (jump)
            // operation. These are translated into case clauses in a switch statement.
            // The following two arrays are correlated by their index. This approach is used over
            // allocating objects to store the same information to avoid GC overhead.
            //
            var labelOffsets; // The operation offset at which the label is defined.
            var labelExpressions; // The NumericLiteral nodes bound to each label.
            var nextLabelId = 1; // The next label id to use.
            // Operations store information about generated code for the function body. This
            // Includes things like statements, assignments, breaks (jumps), and yields.
            // The following three arrays are correlated by their index. This approach is used over
            // allocating objects to store the same information to avoid GC overhead.
            //
            var operations; // The operation to perform.
            var operationArguments; // The arguments to the operation.
            var operationLocations; // The source map location for the operation.
            var state; // The name of the state object used by the generator at runtime.
            // The following variables store information used by the `build` function:
            //
            var blockIndex = 0; // The index of the current block.
            var labelNumber = 0; // The current label number.
            var labelNumbers;
            var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
            var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
            var clauses; // The case clauses generated for labels.
            var statements; // The statements for the current label.
            var exceptionBlockStack; // A stack of containing exception blocks.
            var currentExceptionBlock; // The current exception block.
            var withBlockStack; // A stack containing `with` blocks.
            return ts.chainBundle(transformSourceFile);
            function transformSourceFile(node) {
                if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
                    return node;
                }
                var visited = ts.visitEachChild(node, visitor, context);
                ts.addEmitHelpers(visited, context.readEmitHelpers());
                return visited;
            }
            /**
             * Visits a node.
             *
             * @param node The node to visit.
             */
            function visitor(node) {
                var transformFlags = node.transformFlags;
                if (inStatementContainingYield) {
                    return visitJavaScriptInStatementContainingYield(node);
                }
                else if (inGeneratorFunctionBody) {
                    return visitJavaScriptInGeneratorFunctionBody(node);
                }
                else if (transformFlags & 256 /* Generator */) {
                    return visitGenerator(node);
                }
                else if (transformFlags & 512 /* ContainsGenerator */) {
                    return ts.visitEachChild(node, visitor, context);
                }
                else {
                    return node;
                }
            }
            /**
             * Visits a node that is contained within a statement that contains yield.
             *
             * @param node The node to visit.
             */
            function visitJavaScriptInStatementContainingYield(node) {
                switch (node.kind) {
                    case 221 /* DoStatement */:
                        return visitDoStatement(node);
                    case 222 /* WhileStatement */:
                        return visitWhileStatement(node);
                    case 230 /* SwitchStatement */:
                        return visitSwitchStatement(node);
                    case 231 /* LabeledStatement */:
                        return visitLabeledStatement(node);
                    default:
                        return visitJavaScriptInGeneratorFunctionBody(node);
                }
            }
            /**
             * Visits a node that is contained within a generator function.
             *
             * @param node The node to visit.
             */
            function visitJavaScriptInGeneratorFunctionBody(node) {
                switch (node.kind) {
                    case 237 /* FunctionDeclaration */:
                        return visitFunctionDeclaration(node);
                    case 194 /* FunctionExpression */:
                        return visitFunctionExpression(node);
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return visitAccessorDeclaration(node);
                    case 217 /* VariableStatement */:
                        return visitVariableStatement(node);
                    case 223 /* ForStatement */:
                        return visitForStatement(node);
                    case 224 /* ForInStatement */:
                        return visitForInStatement(node);
                    case 227 /* BreakStatement */:
                        return visitBreakStatement(node);
                    case 226 /* ContinueStatement */:
                        return visitContinueStatement(node);
                    case 228 /* ReturnStatement */:
                        return visitReturnStatement(node);
                    default:
                        if (node.transformFlags & 16777216 /* ContainsYield */) {
                            return visitJavaScriptContainingYield(node);
                        }
                        else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) {
                            return ts.visitEachChild(node, visitor, context);
                        }
                        else {
                            return node;
                        }
                }
            }
            /**
             * Visits a node that contains a YieldExpression.
             *
             * @param node The node to visit.
             */
            function visitJavaScriptContainingYield(node) {
                switch (node.kind) {
                    case 202 /* BinaryExpression */:
                        return visitBinaryExpression(node);
                    case 203 /* ConditionalExpression */:
                        return visitConditionalExpression(node);
                    case 205 /* YieldExpression */:
                        return visitYieldExpression(node);
                    case 185 /* ArrayLiteralExpression */:
                        return visitArrayLiteralExpression(node);
                    case 186 /* ObjectLiteralExpression */:
                        return visitObjectLiteralExpression(node);
                    case 188 /* ElementAccessExpression */:
                        return visitElementAccessExpression(node);
                    case 189 /* CallExpression */:
                        return visitCallExpression(node);
                    case 190 /* NewExpression */:
                        return visitNewExpression(node);
                    default:
                        return ts.visitEachChild(node, visitor, context);
                }
            }
            /**
             * Visits a generator function.
             *
             * @param node The node to visit.
             */
            function visitGenerator(node) {
                switch (node.kind) {
                    case 237 /* FunctionDeclaration */:
                        return visitFunctionDeclaration(node);
                    case 194 /* FunctionExpression */:
                        return visitFunctionExpression(node);
                    default:
                        return ts.Debug.failBadSyntaxKind(node);
                }
            }
            /**
             * Visits a function declaration.
             *
             * This will be called when one of the following conditions are met:
             * - The function declaration is a generator function.
             * - The function declaration is contained within the body of a generator function.
             *
             * @param node The node to visit.
             */
            function visitFunctionDeclaration(node) {
                // Currently, we only support generators that were originally async functions.
                if (node.asteriskToken) {
                    node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
                    /*decorators*/ undefined, node.modifiers, 
                    /*asteriskToken*/ undefined, node.name, 
                    /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                    /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
                    /*location*/ node), node);
                }
                else {
                    var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
                    var savedInStatementContainingYield = inStatementContainingYield;
                    inGeneratorFunctionBody = false;
                    inStatementContainingYield = false;
                    node = ts.visitEachChild(node, visitor, context);
                    inGeneratorFunctionBody = savedInGeneratorFunctionBody;
                    inStatementContainingYield = savedInStatementContainingYield;
                }
                if (inGeneratorFunctionBody) {
                    // Function declarations in a generator function body are hoisted
                    // to the top of the lexical scope and elided from the current statement.
                    hoistFunctionDeclaration(node);
                    return undefined;
                }
                else {
                    return node;
                }
            }
            /**
             * Visits a function expression.
             *
             * This will be called when one of the following conditions are met:
             * - The function expression is a generator function.
             * - The function expression is contained within the body of a generator function.
             *
             * @param node The node to visit.
             */
            function visitFunctionExpression(node) {
                // Currently, we only support generators that were originally async functions.
                if (node.asteriskToken) {
                    node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
                    /*modifiers*/ undefined, 
                    /*asteriskToken*/ undefined, node.name, 
                    /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
                    /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
                    /*location*/ node), node);
                }
                else {
                    var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
                    var savedInStatementContainingYield = inStatementContainingYield;
                    inGeneratorFunctionBody = false;
                    inStatementContainingYield = false;
                    node = ts.visitEachChild(node, visitor, context);
                    inGeneratorFunctionBody = savedInGeneratorFunctionBody;
                    inStatementContainingYield = savedInStatementContainingYield;
                }
                return node;
            }
            /**
             * Visits a get or set accessor declaration.
             *
             * This will be called when one of the following conditions are met:
             * - The accessor is contained within the body of a generator function.
             *
             * @param node The node to visit.
             */
            function visitAccessorDeclaration(node) {
                var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
                var savedInStatementContainingYield = inStatementContainingYield;
                inGeneratorFunctionBody = false;
                inStatementContainingYield = false;
                node = ts.visitEachChild(node, visitor, context);
                inGeneratorFunctionBody = savedInGeneratorFunctionBody;
                inStatementContainingYield = savedInStatementContainingYield;
                return node;
            }
            /**
             * Transforms the body of a generator function declaration.
             *
             * @param node The function body to transform.
             */
            function transformGeneratorFunctionBody(body) {
                // Save existing generator state
                var statements = [];
                var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
                var savedInStatementContainingYield = inStatementContainingYield;
                var savedBlocks = blocks;
                var savedBlockOffsets = blockOffsets;
                var savedBlockActions = blockActions;
                var savedBlockStack = blockStack;
                var savedLabelOffsets = labelOffsets;
                var savedLabelExpressions = labelExpressions;
                var savedNextLabelId = nextLabelId;
                var savedOperations = operations;
                var savedOperationArguments = operationArguments;
                var savedOperationLocations = operationLocations;
                var savedState = state;
                // Initialize generator state
                inGeneratorFunctionBody = true;
                inStatementContainingYield = false;
                blocks = undefined;
                blockOffsets = undefined;
                blockActions = undefined;
                blockStack = undefined;
                labelOffsets = undefined;
                labelExpressions = undefined;
                nextLabelId = 1;
                operations = undefined;
                operationArguments = undefined;
                operationLocations = undefined;
                state = ts.createTempVariable(/*recordTempVariable*/ undefined);
                // Build the generator
                resumeLexicalEnvironment();
                var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
                transformAndEmitStatements(body.statements, statementOffset);
                var buildResult = build();
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                statements.push(ts.createReturn(buildResult));
                // Restore previous generator state
                inGeneratorFunctionBody = savedInGeneratorFunctionBody;
                inStatementContainingYield = savedInStatementContainingYield;
                blocks = savedBlocks;
                blockOffsets = savedBlockOffsets;
                blockActions = savedBlockActions;
                blockStack = savedBlockStack;
                labelOffsets = savedLabelOffsets;
                labelExpressions = savedLabelExpressions;
                nextLabelId = savedNextLabelId;
                operations = savedOperations;
                operationArguments = savedOperationArguments;
                operationLocations = savedOperationLocations;
                state = savedState;
                return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
            }
            /**
             * Visits a variable statement.
             *
             * This will be called when one of the following conditions are met:
             * - The variable statement is contained within the body of a generator function.
             *
             * @param node The node to visit.
             */
            function visitVariableStatement(node) {
                if (node.transformFlags & 16777216 /* ContainsYield */) {
                    transformAndEmitVariableDeclarationList(node.declarationList);
                    return undefined;
                }
                else {
                    // Do not hoist custom prologues.
                    if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
                        return node;
                    }
                    for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                        var variable = _a[_i];
                        hoistVariableDeclaration(variable.name);
                    }
                    var variables = ts.getInitializedVariables(node.declarationList);
                    if (variables.length === 0) {
                        return undefined;
                    }
                    return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
                }
            }
            /**
             * Visits a binary expression.
             *
             * This will be called when one of the following conditions are met:
             * - The node contains a YieldExpression.
             *
             * @param node The node to visit.
             */
            function visitBinaryExpression(node) {
                var assoc = ts.getExpressionAssociativity(node);
                switch (assoc) {
                    case 0 /* Left */:
                        return visitLeftAssociativeBinaryExpression(node);
                    case 1 /* Right */:
                        return visitRightAssociativeBinaryExpression(node);
                    default:
                        return ts.Debug.assertNever(assoc);
                }
            }
            function isCompoundAssignment(kind) {
                return kind >= 59 /* FirstCompoundAssignment */
                    && kind <= 70 /* LastCompoundAssignment */;
            }
            function getOperatorForCompoundAssignment(kind) {
                switch (kind) {
                    case 59 /* PlusEqualsToken */: return 37 /* PlusToken */;
                    case 60 /* MinusEqualsToken */: return 38 /* MinusToken */;
                    case 61 /* AsteriskEqualsToken */: return 39 /* AsteriskToken */;
                    case 62 /* AsteriskAsteriskEqualsToken */: return 40 /* AsteriskAsteriskToken */;
                    case 63 /* SlashEqualsToken */: return 41 /* SlashToken */;
                    case 64 /* PercentEqualsToken */: return 42 /* PercentToken */;
                    case 65 /* LessThanLessThanEqualsToken */: return 45 /* LessThanLessThanToken */;
                    case 66 /* GreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanToken */;
                    case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanGreaterThanToken */;
                    case 68 /* AmpersandEqualsToken */: return 48 /* AmpersandToken */;
                    case 69 /* BarEqualsToken */: return 49 /* BarToken */;
                    case 70 /* CaretEqualsToken */: return 50 /* CaretToken */;
                }
            }
            /**
             * Visits a right-associative binary expression containing `yield`.
             *
             * @param node The node to visit.
             */
            function visitRightAssociativeBinaryExpression(node) {
                var left = node.left, right = node.right;
                if (containsYield(right)) {
                    var target = void 0;
                    switch (left.kind) {
                        case 187 /* PropertyAccessExpression */:
                            // [source]
                            //      a.b = yield;
                            //
                            // [intermediate]
                            //  .local _a
                            //      _a = a;
                            //  .yield resumeLabel
                            //  .mark resumeLabel
                            //      _a.b = %sent%;
                            target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
                            break;
                        case 188 /* ElementAccessExpression */:
                            // [source]
                            //      a[b] = yield;
                            //
                            // [intermediate]
                            //  .local _a, _b
                            //      _a = a;
                            //      _b = b;
                            //  .yield resumeLabel
                            //  .mark resumeLabel
                            //      _a[_b] = %sent%;
                            target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
                            break;
                        default:
                            target = ts.visitNode(left, visitor, ts.isExpression);
                            break;
                    }
                    var operator = node.operatorToken.kind;
                    if (isCompoundAssignment(operator)) {
                        return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
                    }
                    else {
                        return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
                    }
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitLeftAssociativeBinaryExpression(node) {
                if (containsYield(node.right)) {
                    if (ts.isLogicalOperator(node.operatorToken.kind)) {
                        return visitLogicalBinaryExpression(node);
                    }
                    else if (node.operatorToken.kind === 26 /* CommaToken */) {
                        return visitCommaExpression(node);
                    }
                    // [source]
                    //      a() + (yield) + c()
                    //
                    // [intermediate]
                    //  .local _a
                    //      _a = a();
                    //  .yield resumeLabel
                    //      _a + %sent% + c()
                    var clone_4 = ts.getMutableClone(node);
                    clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
                    clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression);
                    return clone_4;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a logical binary expression containing `yield`.
             *
             * @param node A node to visit.
             */
            function visitLogicalBinaryExpression(node) {
                // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
                // to be transformed as such:
                //
                // [source]
                //      x = a() && yield;
                //
                // [intermediate]
                //  .local _a
                //      _a = a();
                //  .brfalse resultLabel, (_a)
                //  .yield resumeLabel
                //  .mark resumeLabel
                //      _a = %sent%;
                //  .mark resultLabel
                //      x = _a;
                //
                // [source]
                //      x = a() || yield;
                //
                // [intermediate]
                //  .local _a
                //      _a = a();
                //  .brtrue resultLabel, (_a)
                //  .yield resumeLabel
                //  .mark resumeLabel
                //      _a = %sent%;
                //  .mark resultLabel
                //      x = _a;
                var resultLabel = defineLabel();
                var resultLocal = declareLocal();
                emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
                if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) {
                    // Logical `&&` shortcuts when the left-hand operand is falsey.
                    emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
                }
                else {
                    // Logical `||` shortcuts when the left-hand operand is truthy.
                    emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
                }
                emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
                markLabel(resultLabel);
                return resultLocal;
            }
            /**
             * Visits a comma expression containing `yield`.
             *
             * @param node The node to visit.
             */
            function visitCommaExpression(node) {
                // [source]
                //      x = a(), yield, b();
                //
                // [intermediate]
                //      a();
                //  .yield resumeLabel
                //  .mark resumeLabel
                //      x = %sent%, b();
                var pendingExpressions = [];
                visit(node.left);
                visit(node.right);
                return ts.inlineExpressions(pendingExpressions);
                function visit(node) {
                    if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) {
                        visit(node.left);
                        visit(node.right);
                    }
                    else {
                        if (containsYield(node) && pendingExpressions.length > 0) {
                            emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
                            pendingExpressions = [];
                        }
                        pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
                    }
                }
            }
            /**
             * Visits a conditional expression containing `yield`.
             *
             * @param node The node to visit.
             */
            function visitConditionalExpression(node) {
                // [source]
                //      x = a() ? yield : b();
                //
                // [intermediate]
                //  .local _a
                //  .brfalse whenFalseLabel, (a())
                //  .yield resumeLabel
                //  .mark resumeLabel
                //      _a = %sent%;
                //  .br resultLabel
                //  .mark whenFalseLabel
                //      _a = b();
                //  .mark resultLabel
                //      x = _a;
                // We only need to perform a specific transformation if a `yield` expression exists
                // in either the `whenTrue` or `whenFalse` branches.
                // A `yield` in the condition will be handled by the normal visitor.
                if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
                    var whenFalseLabel = defineLabel();
                    var resultLabel = defineLabel();
                    var resultLocal = declareLocal();
                    emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
                    emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
                    emitBreak(resultLabel);
                    markLabel(whenFalseLabel);
                    emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
                    markLabel(resultLabel);
                    return resultLocal;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            /**
             * Visits a `yield` expression.
             *
             * @param node The node to visit.
             */
            function visitYieldExpression(node) {
                // [source]
                //      x = yield a();
                //
                // [intermediate]
                //  .yield resumeLabel, (a())
                //  .mark resumeLabel
                //      x = %sent%;
                var resumeLabel = defineLabel();
                var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
                if (node.asteriskToken) {
                    var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
                        ? ts.createValuesHelper(context, expression, /*location*/ node)
                        : expression;
                    emitYieldStar(iterator, /*location*/ node);
                }
                else {
                    emitYield(expression, /*location*/ node);
                }
                markLabel(resumeLabel);
                return createGeneratorResume(/*location*/ node);
            }
            /**
             * Visits an ArrayLiteralExpression that contains a YieldExpression.
             *
             * @param node The node to visit.
             */
            function visitArrayLiteralExpression(node) {
                return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
            }
            /**
             * Visits an array of expressions containing one or more YieldExpression nodes
             * and returns an expression for the resulting value.
             *
             * @param elements The elements to visit.
             * @param multiLine Whether array literals created should be emitted on multiple lines.
             */
            function visitElements(elements, leadingElement, location, multiLine) {
                // [source]
                //      ar = [1, yield, 2];
                //
                // [intermediate]
                //  .local _a
                //      _a = [1];
                //  .yield resumeLabel
                //  .mark resumeLabel
                //      ar = _a.concat([%sent%, 2]);
                var numInitialElements = countInitialNodesWithoutYield(elements);
                var temp;
                if (numInitialElements > 0) {
                    temp = declareLocal();
                    var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
                    emitAssignment(temp, ts.createArrayLiteral(leadingElement
                        ? [leadingElement].concat(initialElements) : initialElements));
                    leadingElement = undefined;
                }
                var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
                return temp
                    ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
                    : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location);
                function reduceElement(expressions, element) {
                    if (containsYield(element) && expressions.length > 0) {
                        var hasAssignedTemp = temp !== undefined;
                        if (!temp) {
                            temp = declareLocal();
                        }
                        emitAssignment(temp, hasAssignedTemp
                            ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
                            : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine));
                        leadingElement = undefined;
                        expressions = [];
                    }
                    expressions.push(ts.visitNode(element, visitor, ts.isExpression));
                    return expressions;
                }
            }
            function visitObjectLiteralExpression(node) {
                // [source]
                //      o = {
                //          a: 1,
                //          b: yield,
                //          c: 2
                //      };
                //
                // [intermediate]
                //  .local _a
                //      _a = {
                //          a: 1
                //      };
                //  .yield resumeLabel
                //  .mark resumeLabel
                //      o = (_a.b = %sent%,
                //          _a.c = 2,
                //          _a);
                var properties = node.properties;
                var multiLine = node.multiLine;
                var numInitialProperties = countInitialNodesWithoutYield(properties);
                var temp = declareLocal();
                emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
                var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
                expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
                return ts.inlineExpressions(expressions);
                function reduceProperty(expressions, property) {
                    if (containsYield(property) && expressions.length > 0) {
                        emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
                        expressions = [];
                    }
                    var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
                    var visited = ts.visitNode(expression, visitor, ts.isExpression);
                    if (visited) {
                        if (multiLine) {
                            ts.startOnNewLine(visited);
                        }
                        expressions.push(visited);
                    }
                    return expressions;
                }
            }
            /**
             * Visits an ElementAccessExpression that contains a YieldExpression.
             *
             * @param node The node to visit.
             */
            function visitElementAccessExpression(node) {
                if (containsYield(node.argumentExpression)) {
                    // [source]
                    //      a = x[yield];
                    //
                    // [intermediate]
                    //  .local _a
                    //      _a = x;
                    //  .yield resumeLabel
                    //  .mark resumeLabel
                    //      a = _a[%sent%]
                    var clone_5 = ts.getMutableClone(node);
                    clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
                    clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
                    return clone_5;
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitCallExpression(node) {
                if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
                    // [source]
                    //      a.b(1, yield, 2);
                    //
                    // [intermediate]
                    //  .local _a, _b, _c
                    //      _b = (_a = a).b;
                    //      _c = [1];
                    //  .yield resumeLabel
                    //  .mark resumeLabel
                    //      _b.apply(_a, _c.concat([%sent%, 2]));
                    var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
                    return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), 
                    /*location*/ node), node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function visitNewExpression(node) {
                if (ts.forEach(node.arguments, containsYield)) {
                    // [source]
                    //      new a.b(1, yield, 2);
                    //
                    // [intermediate]
                    //  .local _a, _b, _c
                    //      _b = (_a = a.b).bind;
                    //      _c = [1];
                    //  .yield resumeLabel
                    //  .mark resumeLabel
                    //      new (_b.apply(_a, _c.concat([%sent%, 2])));
                    var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
                    return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
                    /*leadingElement*/ ts.createVoidZero())), 
                    /*typeArguments*/ undefined, []), node), node);
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function transformAndEmitStatements(statements, start) {
                if (start === void 0) {
                    start = 0;
                }
                var numStatements = statements.length;
                for (var i = start; i < numStatements; i++) {
                    transformAndEmitStatement(statements[i]);
                }
            }
            function transformAndEmitEmbeddedStatement(node) {
                if (ts.isBlock(node)) {
                    transformAndEmitStatements(node.statements);
                }
                else {
                    transformAndEmitStatement(node);
                }
            }
            function transformAndEmitStatement(node) {
                var savedInStatementContainingYield = inStatementContainingYield;
                if (!inStatementContainingYield) {
                    inStatementContainingYield = containsYield(node);
                }
                transformAndEmitStatementWorker(node);
                inStatementContainingYield = savedInStatementContainingYield;
            }
            function transformAndEmitStatementWorker(node) {
                switch (node.kind) {
                    case 216 /* Block */:
                        return transformAndEmitBlock(node);
                    case 219 /* ExpressionStatement */:
                        return transformAndEmitExpressionStatement(node);
                    case 220 /* IfStatement */:
                        return transformAndEmitIfStatement(node);
                    case 221 /* DoStatement */:
                        return transformAndEmitDoStatement(node);
                    case 222 /* WhileStatement */:
                        return transformAndEmitWhileStatement(node);
                    case 223 /* ForStatement */:
                        return transformAndEmitForStatement(node);
                    case 224 /* ForInStatement */:
                        return transformAndEmitForInStatement(node);
                    case 226 /* ContinueStatement */:
                        return transformAndEmitContinueStatement(node);
                    case 227 /* BreakStatement */:
                        return transformAndEmitBreakStatement(node);
                    case 228 /* ReturnStatement */:
                        return transformAndEmitReturnStatement(node);
                    case 229 /* WithStatement */:
                        return transformAndEmitWithStatement(node);
                    case 230 /* SwitchStatement */:
                        return transformAndEmitSwitchStatement(node);
                    case 231 /* LabeledStatement */:
                        return transformAndEmitLabeledStatement(node);
                    case 232 /* ThrowStatement */:
                        return transformAndEmitThrowStatement(node);
                    case 233 /* TryStatement */:
                        return transformAndEmitTryStatement(node);
                    default:
                        return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function transformAndEmitBlock(node) {
                if (containsYield(node)) {
                    transformAndEmitStatements(node.statements);
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function transformAndEmitExpressionStatement(node) {
                emitStatement(ts.visitNode(node, visitor, ts.isStatement));
            }
            function transformAndEmitVariableDeclarationList(node) {
                for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
                    var variable = _a[_i];
                    var name = ts.getSynthesizedClone(variable.name);
                    ts.setCommentRange(name, variable.name);
                    hoistVariableDeclaration(name);
                }
                var variables = ts.getInitializedVariables(node);
                var numVariables = variables.length;
                var variablesWritten = 0;
                var pendingExpressions = [];
                while (variablesWritten < numVariables) {
                    for (var i = variablesWritten; i < numVariables; i++) {
                        var variable = variables[i];
                        if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
                            break;
                        }
                        pendingExpressions.push(transformInitializedVariable(variable));
                    }
                    if (pendingExpressions.length) {
                        emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
                        variablesWritten += pendingExpressions.length;
                        pendingExpressions = [];
                    }
                }
                return undefined;
            }
            function transformInitializedVariable(node) {
                return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
            }
            function transformAndEmitIfStatement(node) {
                if (containsYield(node)) {
                    // [source]
                    //      if (x)
                    //          /*thenStatement*/
                    //      else
                    //          /*elseStatement*/
                    //
                    // [intermediate]
                    //  .brfalse elseLabel, (x)
                    //      /*thenStatement*/
                    //  .br endLabel
                    //  .mark elseLabel
                    //      /*elseStatement*/
                    //  .mark endLabel
                    if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
                        var endLabel = defineLabel();
                        var elseLabel = node.elseStatement ? defineLabel() : undefined;
                        emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
                        transformAndEmitEmbeddedStatement(node.thenStatement);
                        if (node.elseStatement) {
                            emitBreak(endLabel);
                            markLabel(elseLabel);
                            transformAndEmitEmbeddedStatement(node.elseStatement);
                        }
                        markLabel(endLabel);
                    }
                    else {
                        emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                    }
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function transformAndEmitDoStatement(node) {
                if (containsYield(node)) {
                    // [source]
                    //      do {
                    //          /*body*/
                    //      }
                    //      while (i < 10);
                    //
                    // [intermediate]
                    //  .loop conditionLabel, endLabel
                    //  .mark loopLabel
                    //      /*body*/
                    //  .mark conditionLabel
                    //  .brtrue loopLabel, (i < 10)
                    //  .endloop
                    //  .mark endLabel
                    var conditionLabel = defineLabel();
                    var loopLabel = defineLabel();
                    beginLoopBlock(/*continueLabel*/ conditionLabel);
                    markLabel(loopLabel);
                    transformAndEmitEmbeddedStatement(node.statement);
                    markLabel(conditionLabel);
                    emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
                    endLoopBlock();
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function visitDoStatement(node) {
                if (inStatementContainingYield) {
                    beginScriptLoopBlock();
                    node = ts.visitEachChild(node, visitor, context);
                    endLoopBlock();
                    return node;
                }
                else {
                    return ts.visitEachChild(node, visitor, context);
                }
            }
            function transformAndEmitWhileStatement(node) {
                if (containsYield(node)) {
                    // [source]
                    //      while (i < 10) {
                    //          /*body*/
                    //      }
                    //
                    // [intermediate]
                    //  .loop loopLabel, endLabel
                    //  .mark loopLabel
                    //  .brfalse endLabel, (i < 10)
                    //      /*body*/
                    //  .br loopLabel
                    //  .endloop
                    //  .mark endLabel
                    var loopLabel = defineLabel();
                    var endLabel = beginLoopBlock(loopLabel);
                    markLabel(loopLabel);
                    emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
                    transformAndEmitEmbeddedStatement(node.statement);
                    emitBreak(loopLabel);
                    endLoopBlock();
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function visitWhileStatement(node) {
                if (inStatementContainingYield) {
                    beginScriptLoopBlock();
                    node = ts.visitEachChild(node, visitor, context);
                    endLoopBlock();
                    return node;
                }
                else {
                    return ts.visitEachChild(node, visitor, context);
                }
            }
            function transformAndEmitForStatement(node) {
                if (containsYield(node)) {
                    // [source]
                    //      for (var i = 0; i < 10; i++) {
                    //          /*body*/
                    //      }
                    //
                    // [intermediate]
                    //  .local i
                    //      i = 0;
                    //  .loop incrementLabel, endLoopLabel
                    //  .mark conditionLabel
                    //  .brfalse endLoopLabel, (i < 10)
                    //      /*body*/
                    //  .mark incrementLabel
                    //      i++;
                    //  .br conditionLabel
                    //  .endloop
                    //  .mark endLoopLabel
                    var conditionLabel = defineLabel();
                    var incrementLabel = defineLabel();
                    var endLabel = beginLoopBlock(incrementLabel);
                    if (node.initializer) {
                        var initializer = node.initializer;
                        if (ts.isVariableDeclarationList(initializer)) {
                            transformAndEmitVariableDeclarationList(initializer);
                        }
                        else {
                            emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
                        }
                    }
                    markLabel(conditionLabel);
                    if (node.condition) {
                        emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
                    }
                    transformAndEmitEmbeddedStatement(node.statement);
                    markLabel(incrementLabel);
                    if (node.incrementor) {
                        emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
                    }
                    emitBreak(conditionLabel);
                    endLoopBlock();
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function visitForStatement(node) {
                if (inStatementContainingYield) {
                    beginScriptLoopBlock();
                }
                var initializer = node.initializer;
                if (initializer && ts.isVariableDeclarationList(initializer)) {
                    for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
                        var variable = _a[_i];
                        hoistVariableDeclaration(variable.name);
                    }
                    var variables = ts.getInitializedVariables(initializer);
                    node = ts.updateFor(node, variables.length > 0
                        ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
                        : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                }
                else {
                    node = ts.visitEachChild(node, visitor, context);
                }
                if (inStatementContainingYield) {
                    endLoopBlock();
                }
                return node;
            }
            function transformAndEmitForInStatement(node) {
                // TODO(rbuckton): Source map locations
                if (containsYield(node)) {
                    // [source]
                    //      for (var p in o) {
                    //          /*body*/
                    //      }
                    //
                    // [intermediate]
                    //  .local _a, _b, _i
                    //      _a = [];
                    //      for (_b in o) _a.push(_b);
                    //      _i = 0;
                    //  .loop incrementLabel, endLoopLabel
                    //  .mark conditionLabel
                    //  .brfalse endLoopLabel, (_i < _a.length)
                    //      p = _a[_i];
                    //      /*body*/
                    //  .mark incrementLabel
                    //      _b++;
                    //  .br conditionLabel
                    //  .endloop
                    //  .mark endLoopLabel
                    var keysArray = declareLocal(); // _a
                    var key = declareLocal(); // _b
                    var keysIndex = ts.createLoopVariable(); // _i
                    var initializer = node.initializer;
                    hoistVariableDeclaration(keysIndex);
                    emitAssignment(keysArray, ts.createArrayLiteral());
                    emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), 
                    /*typeArguments*/ undefined, [key]))));
                    emitAssignment(keysIndex, ts.createLiteral(0));
                    var conditionLabel = defineLabel();
                    var incrementLabel = defineLabel();
                    var endLabel = beginLoopBlock(incrementLabel);
                    markLabel(conditionLabel);
                    emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
                    var variable = void 0;
                    if (ts.isVariableDeclarationList(initializer)) {
                        for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
                            var variable_1 = _a[_i];
                            hoistVariableDeclaration(variable_1.name);
                        }
                        variable = ts.getSynthesizedClone(initializer.declarations[0].name);
                    }
                    else {
                        variable = ts.visitNode(initializer, visitor, ts.isExpression);
                        ts.Debug.assert(ts.isLeftHandSideExpression(variable));
                    }
                    emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
                    transformAndEmitEmbeddedStatement(node.statement);
                    markLabel(incrementLabel);
                    emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
                    emitBreak(conditionLabel);
                    endLoopBlock();
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function visitForInStatement(node) {
                // [source]
                //      for (var x in a) {
                //          /*body*/
                //      }
                //
                // [intermediate]
                //  .local x
                //  .loop
                //      for (x in a) {
                //          /*body*/
                //      }
                //  .endloop
                if (inStatementContainingYield) {
                    beginScriptLoopBlock();
                }
                var initializer = node.initializer;
                if (ts.isVariableDeclarationList(initializer)) {
                    for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
                        var variable = _a[_i];
                        hoistVariableDeclaration(variable.name);
                    }
                    node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
                }
                else {
                    node = ts.visitEachChild(node, visitor, context);
                }
                if (inStatementContainingYield) {
                    endLoopBlock();
                }
                return node;
            }
            function transformAndEmitContinueStatement(node) {
                var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
                if (label > 0) {
                    emitBreak(label, /*location*/ node);
                }
                else {
                    // invalid continue without a containing loop. Leave the node as is, per #17875.
                    emitStatement(node);
                }
            }
            function visitContinueStatement(node) {
                if (inStatementContainingYield) {
                    var label = findContinueTarget(node.label && ts.idText(node.label));
                    if (label > 0) {
                        return createInlineBreak(label, /*location*/ node);
                    }
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function transformAndEmitBreakStatement(node) {
                var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
                if (label > 0) {
                    emitBreak(label, /*location*/ node);
                }
                else {
                    // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
                    emitStatement(node);
                }
            }
            function visitBreakStatement(node) {
                if (inStatementContainingYield) {
                    var label = findBreakTarget(node.label && ts.idText(node.label));
                    if (label > 0) {
                        return createInlineBreak(label, /*location*/ node);
                    }
                }
                return ts.visitEachChild(node, visitor, context);
            }
            function transformAndEmitReturnStatement(node) {
                emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
                /*location*/ node);
            }
            function visitReturnStatement(node) {
                return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
                /*location*/ node);
            }
            function transformAndEmitWithStatement(node) {
                if (containsYield(node)) {
                    // [source]
                    //      with (x) {
                    //          /*body*/
                    //      }
                    //
                    // [intermediate]
                    //  .with (x)
                    //      /*body*/
                    //  .endwith
                    beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
                    transformAndEmitEmbeddedStatement(node.statement);
                    endWithBlock();
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function transformAndEmitSwitchStatement(node) {
                if (containsYield(node.caseBlock)) {
                    // [source]
                    //      switch (x) {
                    //          case a:
                    //              /*caseStatements*/
                    //          case b:
                    //              /*caseStatements*/
                    //          default:
                    //              /*defaultStatements*/
                    //      }
                    //
                    // [intermediate]
                    //  .local _a
                    //  .switch endLabel
                    //      _a = x;
                    //      switch (_a) {
                    //          case a:
                    //  .br clauseLabels[0]
                    //      }
                    //      switch (_a) {
                    //          case b:
                    //  .br clauseLabels[1]
                    //      }
                    //  .br clauseLabels[2]
                    //  .mark clauseLabels[0]
                    //      /*caseStatements*/
                    //  .mark clauseLabels[1]
                    //      /*caseStatements*/
                    //  .mark clauseLabels[2]
                    //      /*caseStatements*/
                    //  .endswitch
                    //  .mark endLabel
                    var caseBlock = node.caseBlock;
                    var numClauses = caseBlock.clauses.length;
                    var endLabel = beginSwitchBlock();
                    var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
                    // Create labels for each clause and find the index of the first default clause.
                    var clauseLabels = [];
                    var defaultClauseIndex = -1;
                    for (var i = 0; i < numClauses; i++) {
                        var clause = caseBlock.clauses[i];
                        clauseLabels.push(defineLabel());
                        if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) {
                            defaultClauseIndex = i;
                        }
                    }
                    // Emit switch statements for each run of case clauses either from the first case
                    // clause or the next case clause with a `yield` in its expression, up to the next
                    // case clause with a `yield` in its expression.
                    var clausesWritten = 0;
                    var pendingClauses = [];
                    while (clausesWritten < numClauses) {
                        var defaultClausesSkipped = 0;
                        for (var i = clausesWritten; i < numClauses; i++) {
                            var clause = caseBlock.clauses[i];
                            if (clause.kind === 269 /* CaseClause */) {
                                if (containsYield(clause.expression) && pendingClauses.length > 0) {
                                    break;
                                }
                                pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
                                    createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
                                ]));
                            }
                            else {
                                defaultClausesSkipped++;
                            }
                        }
                        if (pendingClauses.length) {
                            emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
                            clausesWritten += pendingClauses.length;
                            pendingClauses = [];
                        }
                        if (defaultClausesSkipped > 0) {
                            clausesWritten += defaultClausesSkipped;
                            defaultClausesSkipped = 0;
                        }
                    }
                    if (defaultClauseIndex >= 0) {
                        emitBreak(clauseLabels[defaultClauseIndex]);
                    }
                    else {
                        emitBreak(endLabel);
                    }
                    for (var i = 0; i < numClauses; i++) {
                        markLabel(clauseLabels[i]);
                        transformAndEmitStatements(caseBlock.clauses[i].statements);
                    }
                    endSwitchBlock();
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function visitSwitchStatement(node) {
                if (inStatementContainingYield) {
                    beginScriptSwitchBlock();
                }
                node = ts.visitEachChild(node, visitor, context);
                if (inStatementContainingYield) {
                    endSwitchBlock();
                }
                return node;
            }
            function transformAndEmitLabeledStatement(node) {
                if (containsYield(node)) {
                    // [source]
                    //      x: {
                    //          /*body*/
                    //      }
                    //
                    // [intermediate]
                    //  .labeled "x", endLabel
                    //      /*body*/
                    //  .endlabeled
                    //  .mark endLabel
                    beginLabeledBlock(ts.idText(node.label));
                    transformAndEmitEmbeddedStatement(node.statement);
                    endLabeledBlock();
                }
                else {
                    emitStatement(ts.visitNode(node, visitor, ts.isStatement));
                }
            }
            function visitLabeledStatement(node) {
                if (inStatementContainingYield) {
                    beginScriptLabeledBlock(ts.idText(node.label));
                }
                node = ts.visitEachChild(node, visitor, context);
                if (inStatementContainingYield) {
                    endLabeledBlock();
                }
                return node;
            }
            function transformAndEmitThrowStatement(node) {
                emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), 
                /*location*/ node);
            }
            function transformAndEmitTryStatement(node) {
                if (containsYield(node)) {
                    // [source]
                    //      try {
                    //          /*tryBlock*/
                    //      }
                    //      catch (e) {
                    //          /*catchBlock*/
                    //      }
                    //      finally {
                    //          /*finallyBlock*/
                    //      }
                    //
                    // [intermediate]
                    //  .local _a
                    //  .try tryLabel, catchLabel, finallyLabel, endLabel
                    //  .mark tryLabel
                    //  .nop
                    //      /*tryBlock*/
                    //  .br endLabel
                    //  .catch
                    //  .mark catchLabel
                    //      _a = %error%;
                    //      /*catchBlock*/
                    //  .br endLabel
                    //  .finally
                    //  .mark finallyLabel
                    //      /*finallyBlock*/
                    //  .endfinally
                    //  .endtry
                    //  .mark endLabel
                    beginExceptionBlock();
                    transformAndEmitEmbeddedStatement(node.tryBlock);
                    if (node.catchClause) {
                        beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
                        transformAndEmitEmbeddedStatement(node.catchClause.block);
                    }
                    if (node.finallyBlock) {
                        beginFinallyBlock();
                        transformAndEmitEmbeddedStatement(node.finallyBlock);
                    }
                    endExceptionBlock();
                }
                else {
                    emitStatement(ts.visitEachChild(node, visitor, context));
                }
            }
            function containsYield(node) {
                return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0;
            }
            function countInitialNodesWithoutYield(nodes) {
                var numNodes = nodes.length;
                for (var i = 0; i < numNodes; i++) {
                    if (containsYield(nodes[i])) {
                        return i;
                    }
                }
                return -1;
            }
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (hint === 1 /* Expression */) {
                    return substituteExpression(node);
                }
                return node;
            }
            function substituteExpression(node) {
                if (ts.isIdentifier(node)) {
                    return substituteExpressionIdentifier(node);
                }
                return node;
            }
            function substituteExpressionIdentifier(node) {
                if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
                    var original = ts.getOriginalNode(node);
                    if (ts.isIdentifier(original) && original.parent) {
                        var declaration = resolver.getReferencedValueDeclaration(original);
                        if (declaration) {
                            var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
                            if (name) {
                                var clone_6 = ts.getMutableClone(name);
                                ts.setSourceMapRange(clone_6, node);
                                ts.setCommentRange(clone_6, node);
                                return clone_6;
                            }
                        }
                    }
                }
                return node;
            }
            function cacheExpression(node) {
                var temp;
                if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
                    return node;
                }
                temp = ts.createTempVariable(hoistVariableDeclaration);
                emitAssignment(temp, node, /*location*/ node);
                return temp;
            }
            function declareLocal(name) {
                var temp = name
                    ? ts.createUniqueName(name)
                    : ts.createTempVariable(/*recordTempVariable*/ undefined);
                hoistVariableDeclaration(temp);
                return temp;
            }
            /**
             * Defines a label, uses as the target of a Break operation.
             */
            function defineLabel() {
                if (!labelOffsets) {
                    labelOffsets = [];
                }
                var label = nextLabelId;
                nextLabelId++;
                labelOffsets[label] = -1;
                return label;
            }
            /**
             * Marks the current operation with the specified label.
             */
            function markLabel(label) {
                ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
                labelOffsets[label] = operations ? operations.length : 0;
            }
            /**
             * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
             *
             * @param block Information about the block.
             */
            function beginBlock(block) {
                if (!blocks) {
                    blocks = [];
                    blockActions = [];
                    blockOffsets = [];
                    blockStack = [];
                }
                var index = blockActions.length;
                blockActions[index] = 0 /* Open */;
                blockOffsets[index] = operations ? operations.length : 0;
                blocks[index] = block;
                blockStack.push(block);
                return index;
            }
            /**
             * Ends the current block operation.
             */
            function endBlock() {
                var block = peekBlock();
                if (block === undefined)
                    return ts.Debug.fail("beginBlock was never called.");
                var index = blockActions.length;
                blockActions[index] = 1 /* Close */;
                blockOffsets[index] = operations ? operations.length : 0;
                blocks[index] = block;
                blockStack.pop();
                return block;
            }
            /**
             * Gets the current open block.
             */
            function peekBlock() {
                return ts.lastOrUndefined(blockStack);
            }
            /**
             * Gets the kind of the current open block.
             */
            function peekBlockKind() {
                var block = peekBlock();
                return block && block.kind;
            }
            /**
             * Begins a code block for a generated `with` statement.
             *
             * @param expression An identifier representing expression for the `with` block.
             */
            function beginWithBlock(expression) {
                var startLabel = defineLabel();
                var endLabel = defineLabel();
                markLabel(startLabel);
                beginBlock({
                    kind: 1 /* With */,
                    expression: expression,
                    startLabel: startLabel,
                    endLabel: endLabel
                });
            }
            /**
             * Ends a code block for a generated `with` statement.
             */
            function endWithBlock() {
                ts.Debug.assert(peekBlockKind() === 1 /* With */);
                var block = endBlock();
                markLabel(block.endLabel);
            }
            /**
             * Begins a code block for a generated `try` statement.
             */
            function beginExceptionBlock() {
                var startLabel = defineLabel();
                var endLabel = defineLabel();
                markLabel(startLabel);
                beginBlock({
                    kind: 0 /* Exception */,
                    state: 0 /* Try */,
                    startLabel: startLabel,
                    endLabel: endLabel
                });
                emitNop();
                return endLabel;
            }
            /**
             * Enters the `catch` clause of a generated `try` statement.
             *
             * @param variable The catch variable.
             */
            function beginCatchBlock(variable) {
                ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
                // generated identifiers should already be unique within a file
                var name;
                if (ts.isGeneratedIdentifier(variable.name)) {
                    name = variable.name;
                    hoistVariableDeclaration(variable.name);
                }
                else {
                    var text = ts.idText(variable.name);
                    name = declareLocal(text);
                    if (!renamedCatchVariables) {
                        renamedCatchVariables = ts.createMap();
                        renamedCatchVariableDeclarations = [];
                        context.enableSubstitution(71 /* Identifier */);
                    }
                    renamedCatchVariables.set(text, true);
                    renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
                }
                var exception = peekBlock();
                ts.Debug.assert(exception.state < 1 /* Catch */);
                var endLabel = exception.endLabel;
                emitBreak(endLabel);
                var catchLabel = defineLabel();
                markLabel(catchLabel);
                exception.state = 1 /* Catch */;
                exception.catchVariable = name;
                exception.catchLabel = catchLabel;
                emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
                emitNop();
            }
            /**
             * Enters the `finally` block of a generated `try` statement.
             */
            function beginFinallyBlock() {
                ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
                var exception = peekBlock();
                ts.Debug.assert(exception.state < 2 /* Finally */);
                var endLabel = exception.endLabel;
                emitBreak(endLabel);
                var finallyLabel = defineLabel();
                markLabel(finallyLabel);
                exception.state = 2 /* Finally */;
                exception.finallyLabel = finallyLabel;
            }
            /**
             * Ends the code block for a generated `try` statement.
             */
            function endExceptionBlock() {
                ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
                var exception = endBlock();
                var state = exception.state;
                if (state < 2 /* Finally */) {
                    emitBreak(exception.endLabel);
                }
                else {
                    emitEndfinally();
                }
                markLabel(exception.endLabel);
                emitNop();
                exception.state = 3 /* Done */;
            }
            /**
             * Begins a code block that supports `break` or `continue` statements that are defined in
             * the source tree and not from generated code.
             *
             * @param labelText Names from containing labeled statements.
             */
            function beginScriptLoopBlock() {
                beginBlock({
                    kind: 3 /* Loop */,
                    isScript: true,
                    breakLabel: -1,
                    continueLabel: -1
                });
            }
            /**
             * Begins a code block that supports `break` or `continue` statements that are defined in
             * generated code. Returns a label used to mark the operation to which to jump when a
             * `break` statement targets this block.
             *
             * @param continueLabel A Label used to mark the operation to which to jump when a
             *                      `continue` statement targets this block.
             */
            function beginLoopBlock(continueLabel) {
                var breakLabel = defineLabel();
                beginBlock({
                    kind: 3 /* Loop */,
                    isScript: false,
                    breakLabel: breakLabel,
                    continueLabel: continueLabel,
                });
                return breakLabel;
            }
            /**
             * Ends a code block that supports `break` or `continue` statements that are defined in
             * generated code or in the source tree.
             */
            function endLoopBlock() {
                ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
                var block = endBlock();
                var breakLabel = block.breakLabel;
                if (!block.isScript) {
                    markLabel(breakLabel);
                }
            }
            /**
             * Begins a code block that supports `break` statements that are defined in the source
             * tree and not from generated code.
             *
             */
            function beginScriptSwitchBlock() {
                beginBlock({
                    kind: 2 /* Switch */,
                    isScript: true,
                    breakLabel: -1
                });
            }
            /**
             * Begins a code block that supports `break` statements that are defined in generated code.
             * Returns a label used to mark the operation to which to jump when a `break` statement
             * targets this block.
             */
            function beginSwitchBlock() {
                var breakLabel = defineLabel();
                beginBlock({
                    kind: 2 /* Switch */,
                    isScript: false,
                    breakLabel: breakLabel,
                });
                return breakLabel;
            }
            /**
             * Ends a code block that supports `break` statements that are defined in generated code.
             */
            function endSwitchBlock() {
                ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
                var block = endBlock();
                var breakLabel = block.breakLabel;
                if (!block.isScript) {
                    markLabel(breakLabel);
                }
            }
            function beginScriptLabeledBlock(labelText) {
                beginBlock({
                    kind: 4 /* Labeled */,
                    isScript: true,
                    labelText: labelText,
                    breakLabel: -1
                });
            }
            function beginLabeledBlock(labelText) {
                var breakLabel = defineLabel();
                beginBlock({
                    kind: 4 /* Labeled */,
                    isScript: false,
                    labelText: labelText,
                    breakLabel: breakLabel
                });
            }
            function endLabeledBlock() {
                ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
                var block = endBlock();
                if (!block.isScript) {
                    markLabel(block.breakLabel);
                }
            }
            /**
             * Indicates whether the provided block supports `break` statements.
             *
             * @param block A code block.
             */
            function supportsUnlabeledBreak(block) {
                return block.kind === 2 /* Switch */
                    || block.kind === 3 /* Loop */;
            }
            /**
             * Indicates whether the provided block supports `break` statements with labels.
             *
             * @param block A code block.
             */
            function supportsLabeledBreakOrContinue(block) {
                return block.kind === 4 /* Labeled */;
            }
            /**
             * Indicates whether the provided block supports `continue` statements.
             *
             * @param block A code block.
             */
            function supportsUnlabeledContinue(block) {
                return block.kind === 3 /* Loop */;
            }
            function hasImmediateContainingLabeledBlock(labelText, start) {
                for (var j = start; j >= 0; j--) {
                    var containingBlock = blockStack[j];
                    if (supportsLabeledBreakOrContinue(containingBlock)) {
                        if (containingBlock.labelText === labelText) {
                            return true;
                        }
                    }
                    else {
                        break;
                    }
                }
                return false;
            }
            /**
             * Finds the label that is the target for a `break` statement.
             *
             * @param labelText An optional name of a containing labeled statement.
             */
            function findBreakTarget(labelText) {
                if (blockStack) {
                    if (labelText) {
                        for (var i = blockStack.length - 1; i >= 0; i--) {
                            var block = blockStack[i];
                            if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
                                return block.breakLabel;
                            }
                            else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
                                return block.breakLabel;
                            }
                        }
                    }
                    else {
                        for (var i = blockStack.length - 1; i >= 0; i--) {
                            var block = blockStack[i];
                            if (supportsUnlabeledBreak(block)) {
                                return block.breakLabel;
                            }
                        }
                    }
                }
                return 0;
            }
            /**
             * Finds the label that is the target for a `continue` statement.
             *
             * @param labelText An optional name of a containing labeled statement.
             */
            function findContinueTarget(labelText) {
                if (blockStack) {
                    if (labelText) {
                        for (var i = blockStack.length - 1; i >= 0; i--) {
                            var block = blockStack[i];
                            if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
                                return block.continueLabel;
                            }
                        }
                    }
                    else {
                        for (var i = blockStack.length - 1; i >= 0; i--) {
                            var block = blockStack[i];
                            if (supportsUnlabeledContinue(block)) {
                                return block.continueLabel;
                            }
                        }
                    }
                }
                return 0;
            }
            /**
             * Creates an expression that can be used to indicate the value for a label.
             *
             * @param label A label.
             */
            function createLabel(label) {
                if (label !== undefined && label > 0) {
                    if (labelExpressions === undefined) {
                        labelExpressions = [];
                    }
                    var expression = ts.createLiteral(-1);
                    if (labelExpressions[label] === undefined) {
                        labelExpressions[label] = [expression];
                    }
                    else {
                        labelExpressions[label].push(expression);
                    }
                    return expression;
                }
                return ts.createOmittedExpression();
            }
            /**
             * Creates a numeric literal for the provided instruction.
             */
            function createInstruction(instruction) {
                var literal = ts.createLiteral(instruction);
                ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
                return literal;
            }
            /**
             * Creates a statement that can be used indicate a Break operation to the provided label.
             *
             * @param label A label.
             * @param location An optional source map location for the statement.
             */
            function createInlineBreak(label, location) {
                ts.Debug.assertLessThan(0, label, "Invalid label");
                return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
                    createInstruction(3 /* Break */),
                    createLabel(label)
                ])), location);
            }
            /**
             * Creates a statement that can be used indicate a Return operation.
             *
             * @param expression The expression for the return statement.
             * @param location An optional source map location for the statement.
             */
            function createInlineReturn(expression, location) {
                return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
                    ? [createInstruction(2 /* Return */), expression]
                    : [createInstruction(2 /* Return */)])), location);
            }
            /**
             * Creates an expression that can be used to resume from a Yield operation.
             */
            function createGeneratorResume(location) {
                return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), 
                /*typeArguments*/ undefined, []), location);
            }
            /**
             * Emits an empty instruction.
             */
            function emitNop() {
                emitWorker(0 /* Nop */);
            }
            /**
             * Emits a Statement.
             *
             * @param node A statement.
             */
            function emitStatement(node) {
                if (node) {
                    emitWorker(1 /* Statement */, [node]);
                }
                else {
                    emitNop();
                }
            }
            /**
             * Emits an Assignment operation.
             *
             * @param left The left-hand side of the assignment.
             * @param right The right-hand side of the assignment.
             * @param location An optional source map location for the assignment.
             */
            function emitAssignment(left, right, location) {
                emitWorker(2 /* Assign */, [left, right], location);
            }
            /**
             * Emits a Break operation to the specified label.
             *
             * @param label A label.
             * @param location An optional source map location for the assignment.
             */
            function emitBreak(label, location) {
                emitWorker(3 /* Break */, [label], location);
            }
            /**
             * Emits a Break operation to the specified label when a condition evaluates to a truthy
             * value at runtime.
             *
             * @param label A label.
             * @param condition The condition.
             * @param location An optional source map location for the assignment.
             */
            function emitBreakWhenTrue(label, condition, location) {
                emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
            }
            /**
             * Emits a Break to the specified label when a condition evaluates to a falsey value at
             * runtime.
             *
             * @param label A label.
             * @param condition The condition.
             * @param location An optional source map location for the assignment.
             */
            function emitBreakWhenFalse(label, condition, location) {
                emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
            }
            /**
             * Emits a YieldStar operation for the provided expression.
             *
             * @param expression An optional value for the yield operation.
             * @param location An optional source map location for the assignment.
             */
            function emitYieldStar(expression, location) {
                emitWorker(7 /* YieldStar */, [expression], location);
            }
            /**
             * Emits a Yield operation for the provided expression.
             *
             * @param expression An optional value for the yield operation.
             * @param location An optional source map location for the assignment.
             */
            function emitYield(expression, location) {
                emitWorker(6 /* Yield */, [expression], location);
            }
            /**
             * Emits a Return operation for the provided expression.
             *
             * @param expression An optional value for the operation.
             * @param location An optional source map location for the assignment.
             */
            function emitReturn(expression, location) {
                emitWorker(8 /* Return */, [expression], location);
            }
            /**
             * Emits a Throw operation for the provided expression.
             *
             * @param expression A value for the operation.
             * @param location An optional source map location for the assignment.
             */
            function emitThrow(expression, location) {
                emitWorker(9 /* Throw */, [expression], location);
            }
            /**
             * Emits an Endfinally operation. This is used to handle `finally` block semantics.
             */
            function emitEndfinally() {
                emitWorker(10 /* Endfinally */);
            }
            /**
             * Emits an operation.
             *
             * @param code The OpCode for the operation.
             * @param args The optional arguments for the operation.
             */
            function emitWorker(code, args, location) {
                if (operations === undefined) {
                    operations = [];
                    operationArguments = [];
                    operationLocations = [];
                }
                if (labelOffsets === undefined) {
                    // mark entry point
                    markLabel(defineLabel());
                }
                var operationIndex = operations.length;
                operations[operationIndex] = code;
                operationArguments[operationIndex] = args;
                operationLocations[operationIndex] = location;
            }
            /**
             * Builds the generator function body.
             */
            function build() {
                blockIndex = 0;
                labelNumber = 0;
                labelNumbers = undefined;
                lastOperationWasAbrupt = false;
                lastOperationWasCompletion = false;
                clauses = undefined;
                statements = undefined;
                exceptionBlockStack = undefined;
                currentExceptionBlock = undefined;
                withBlockStack = undefined;
                var buildResult = buildStatements();
                return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
                /*type*/ undefined, ts.createBlock(buildResult, 
                /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
            }
            /**
             * Builds the statements for the generator function body.
             */
            function buildStatements() {
                if (operations) {
                    for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
                        writeOperation(operationIndex);
                    }
                    flushFinalLabel(operations.length);
                }
                else {
                    flushFinalLabel(0);
                }
                if (clauses) {
                    var labelExpression = ts.createPropertyAccess(state, "label");
                    var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
                    return [ts.startOnNewLine(switchStatement)];
                }
                if (statements) {
                    return statements;
                }
                return [];
            }
            /**
             * Flush the current label and advance to a new label.
             */
            function flushLabel() {
                if (!statements) {
                    return;
                }
                appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
                lastOperationWasAbrupt = false;
                lastOperationWasCompletion = false;
                labelNumber++;
            }
            /**
             * Flush the final label of the generator function body.
             */
            function flushFinalLabel(operationIndex) {
                if (isFinalLabelReachable(operationIndex)) {
                    tryEnterLabel(operationIndex);
                    withBlockStack = undefined;
                    writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
                }
                if (statements && clauses) {
                    appendLabel(/*markLabelEnd*/ false);
                }
                updateLabelExpressions();
            }
            /**
             * Tests whether the final label of the generator function body
             * is reachable by user code.
             */
            function isFinalLabelReachable(operationIndex) {
                // if the last operation was *not* a completion (return/throw) then
                // the final label is reachable.
                if (!lastOperationWasCompletion) {
                    return true;
                }
                // if there are no labels defined or referenced, then the final label is
                // not reachable.
                if (!labelOffsets || !labelExpressions) {
                    return false;
                }
                // if the label for this offset is referenced, then the final label
                // is reachable.
                for (var label = 0; label < labelOffsets.length; label++) {
                    if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
                        return true;
                    }
                }
                return false;
            }
            /**
             * Appends a case clause for the last label and sets the new label.
             *
             * @param markLabelEnd Indicates that the transition between labels was a fall-through
             *                     from a previous case clause and the change in labels should be
             *                     reflected on the `state` object.
             */
            function appendLabel(markLabelEnd) {
                if (!clauses) {
                    clauses = [];
                }
                if (statements) {
                    if (withBlockStack) {
                        // The previous label was nested inside one or more `with` blocks, so we
                        // surround the statements in generated `with` blocks to create the same environment.
                        for (var i = withBlockStack.length - 1; i >= 0; i--) {
                            var withBlock = withBlockStack[i];
                            statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
                        }
                    }
                    if (currentExceptionBlock) {
                        // The previous label was nested inside of an exception block, so we must
                        // indicate entry into a protected region by pushing the label numbers
                        // for each block in the protected region.
                        var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
                        statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), 
                        /*typeArguments*/ undefined, [
                            ts.createArrayLiteral([
                                createLabel(startLabel),
                                createLabel(catchLabel),
                                createLabel(finallyLabel),
                                createLabel(endLabel)
                            ])
                        ])));
                        currentExceptionBlock = undefined;
                    }
                    if (markLabelEnd) {
                        // The case clause for the last label falls through to this label, so we
                        // add an assignment statement to reflect the change in labels.
                        statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
                    }
                }
                clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
                statements = undefined;
            }
            /**
             * Tries to enter into a new label at the current operation index.
             */
            function tryEnterLabel(operationIndex) {
                if (!labelOffsets) {
                    return;
                }
                for (var label = 0; label < labelOffsets.length; label++) {
                    if (labelOffsets[label] === operationIndex) {
                        flushLabel();
                        if (labelNumbers === undefined) {
                            labelNumbers = [];
                        }
                        if (labelNumbers[labelNumber] === undefined) {
                            labelNumbers[labelNumber] = [label];
                        }
                        else {
                            labelNumbers[labelNumber].push(label);
                        }
                    }
                }
            }
            /**
             * Updates literal expressions for labels with actual label numbers.
             */
            function updateLabelExpressions() {
                if (labelExpressions !== undefined && labelNumbers !== undefined) {
                    for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
                        var labels = labelNumbers[labelNumber_1];
                        if (labels !== undefined) {
                            for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
                                var label = labels_1[_i];
                                var expressions = labelExpressions[label];
                                if (expressions !== undefined) {
                                    for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
                                        var expression = expressions_1[_a];
                                        expression.text = String(labelNumber_1);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            /**
             * Tries to enter or leave a code block.
             */
            function tryEnterOrLeaveBlock(operationIndex) {
                if (blocks) {
                    for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
                        var block = blocks[blockIndex];
                        var blockAction = blockActions[blockIndex];
                        switch (block.kind) {
                            case 0 /* Exception */:
                                if (blockAction === 0 /* Open */) {
                                    if (!exceptionBlockStack) {
                                        exceptionBlockStack = [];
                                    }
                                    if (!statements) {
                                        statements = [];
                                    }
                                    exceptionBlockStack.push(currentExceptionBlock);
                                    currentExceptionBlock = block;
                                }
                                else if (blockAction === 1 /* Close */) {
                                    currentExceptionBlock = exceptionBlockStack.pop();
                                }
                                break;
                            case 1 /* With */:
                                if (blockAction === 0 /* Open */) {
                                    if (!withBlockStack) {
                                        withBlockStack = [];
                                    }
                                    withBlockStack.push(block);
                                }
                                else if (blockAction === 1 /* Close */) {
                                    withBlockStack.pop();
                                }
                                break;
                            // default: do nothing
                        }
                    }
                }
            }
            /**
             * Writes an operation as a statement to the current label's statement list.
             *
             * @param operation The OpCode of the operation
             */
            function writeOperation(operationIndex) {
                tryEnterLabel(operationIndex);
                tryEnterOrLeaveBlock(operationIndex);
                // early termination, nothing else to process in this label
                if (lastOperationWasAbrupt) {
                    return;
                }
                lastOperationWasAbrupt = false;
                lastOperationWasCompletion = false;
                var opcode = operations[operationIndex];
                if (opcode === 0 /* Nop */) {
                    return;
                }
                else if (opcode === 10 /* Endfinally */) {
                    return writeEndfinally();
                }
                var args = operationArguments[operationIndex];
                if (opcode === 1 /* Statement */) {
                    return writeStatement(args[0]);
                }
                var location = operationLocations[operationIndex];
                switch (opcode) {
                    case 2 /* Assign */:
                        return writeAssign(args[0], args[1], location);
                    case 3 /* Break */:
                        return writeBreak(args[0], location);
                    case 4 /* BreakWhenTrue */:
                        return writeBreakWhenTrue(args[0], args[1], location);
                    case 5 /* BreakWhenFalse */:
                        return writeBreakWhenFalse(args[0], args[1], location);
                    case 6 /* Yield */:
                        return writeYield(args[0], location);
                    case 7 /* YieldStar */:
                        return writeYieldStar(args[0], location);
                    case 8 /* Return */:
                        return writeReturn(args[0], location);
                    case 9 /* Throw */:
                        return writeThrow(args[0], location);
                }
            }
            /**
             * Writes a statement to the current label's statement list.
             *
             * @param statement A statement to write.
             */
            function writeStatement(statement) {
                if (statement) {
                    if (!statements) {
                        statements = [statement];
                    }
                    else {
                        statements.push(statement);
                    }
                }
            }
            /**
             * Writes an Assign operation to the current label's statement list.
             *
             * @param left The left-hand side of the assignment.
             * @param right The right-hand side of the assignment.
             * @param operationLocation The source map location for the operation.
             */
            function writeAssign(left, right, operationLocation) {
                writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
            }
            /**
             * Writes a Throw operation to the current label's statement list.
             *
             * @param expression The value to throw.
             * @param operationLocation The source map location for the operation.
             */
            function writeThrow(expression, operationLocation) {
                lastOperationWasAbrupt = true;
                lastOperationWasCompletion = true;
                writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
            }
            /**
             * Writes a Return operation to the current label's statement list.
             *
             * @param expression The value to return.
             * @param operationLocation The source map location for the operation.
             */
            function writeReturn(expression, operationLocation) {
                lastOperationWasAbrupt = true;
                lastOperationWasCompletion = true;
                writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
                    ? [createInstruction(2 /* Return */), expression]
                    : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
            }
            /**
             * Writes a Break operation to the current label's statement list.
             *
             * @param label The label for the Break.
             * @param operationLocation The source map location for the operation.
             */
            function writeBreak(label, operationLocation) {
                lastOperationWasAbrupt = true;
                writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
                    createInstruction(3 /* Break */),
                    createLabel(label)
                ])), operationLocation), 384 /* NoTokenSourceMaps */));
            }
            /**
             * Writes a BreakWhenTrue operation to the current label's statement list.
             *
             * @param label The label for the Break.
             * @param condition The condition for the Break.
             * @param operationLocation The source map location for the operation.
             */
            function writeBreakWhenTrue(label, condition, operationLocation) {
                writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
                    createInstruction(3 /* Break */),
                    createLabel(label)
                ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
            }
            /**
             * Writes a BreakWhenFalse operation to the current label's statement list.
             *
             * @param label The label for the Break.
             * @param condition The condition for the Break.
             * @param operationLocation The source map location for the operation.
             */
            function writeBreakWhenFalse(label, condition, operationLocation) {
                writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
                    createInstruction(3 /* Break */),
                    createLabel(label)
                ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
            }
            /**
             * Writes a Yield operation to the current label's statement list.
             *
             * @param expression The expression to yield.
             * @param operationLocation The source map location for the operation.
             */
            function writeYield(expression, operationLocation) {
                lastOperationWasAbrupt = true;
                writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
                    ? [createInstruction(4 /* Yield */), expression]
                    : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
            }
            /**
             * Writes a YieldStar instruction to the current label's statement list.
             *
             * @param expression The expression to yield.
             * @param operationLocation The source map location for the operation.
             */
            function writeYieldStar(expression, operationLocation) {
                lastOperationWasAbrupt = true;
                writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
                    createInstruction(5 /* YieldStar */),
                    expression
                ])), operationLocation), 384 /* NoTokenSourceMaps */));
            }
            /**
             * Writes an Endfinally instruction to the current label's statement list.
             */
            function writeEndfinally() {
                lastOperationWasAbrupt = true;
                writeStatement(ts.createReturn(ts.createArrayLiteral([
                    createInstruction(7 /* Endfinally */)
                ])));
            }
        }
        ts.transformGenerators = transformGenerators;
        function createGeneratorHelper(context, body) {
            context.requestEmitHelper(generatorHelper);
            return ts.createCall(ts.getHelperName("__generator"), 
            /*typeArguments*/ undefined, [ts.createThis(), body]);
        }
        // The __generator helper is used by down-level transformations to emulate the runtime
        // semantics of an ES2015 generator function. When called, this helper returns an
        // object that implements the Iterator protocol, in that it has `next`, `return`, and
        // `throw` methods that step through the generator when invoked.
        //
        // parameters:
        //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
        //  @param body     A function that acts as the transformed generator body.
        //
        // variables:
        //  _       Persistent state for the generator that is shared between the helper and the
        //          generator body. The state object has the following members:
        //            sent() - A method that returns or throws the current completion value.
        //            label  - The next point at which to resume evaluation of the generator body.
        //            trys   - A stack of protected regions (try/catch/finally blocks).
        //            ops    - A stack of pending instructions when inside of a finally block.
        //  f       A value indicating whether the generator is executing.
        //  y       An iterator to delegate for a yield*.
        //  t       A temporary variable that holds one of the following values (note that these
        //          cases do not overlap):
        //          - The completion value when resuming from a `yield` or `yield*`.
        //          - The error value for a catch block.
        //          - The current protected region (array of try/catch/finally/end labels).
        //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
        //            of a `yield*`.
        //          - The result of evaluating the verb delegated to the expression of a `yield*`.
        //
        // functions:
        //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
        //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
        //              completed.
        //
        // The __generator helper understands a limited set of instructions:
        //  0: next(value?)     - Start or resume the generator with the specified value.
        //  1: throw(error)     - Resume the generator with an exception. If the generator is
        //                        suspended inside of one or more protected regions, evaluates
        //                        any intervening finally blocks between the current label and
        //                        the nearest catch block or function boundary. If uncaught, the
        //                        exception is thrown to the caller.
        //  2: return(value?)   - Resume the generator as if with a return. If the generator is
        //                        suspended inside of one or more protected regions, evaluates any
        //                        intervening finally blocks.
        //  3: break(label)     - Jump to the specified label. If the label is outside of the
        //                        current protected region, evaluates any intervening finally
        //                        blocks.
        //  4: yield(value?)    - Yield execution to the caller with an optional value. When
        //                        resumed, the generator will continue at the next label.
        //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
        //                        delegation completes, the generator will continue at the next
        //                        label.
        //  6: catch(error)     - Handles an exception thrown from within the generator body. If
        //                        the current label is inside of one or more protected regions,
        //                        evaluates any intervening finally blocks between the current
        //                        label and the nearest catch block or function boundary. If
        //                        uncaught, the exception is thrown to the caller.
        //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
        //                        entering a finally block.
        //
        // For examples of how these are used, see the comments in ./transformers/generators.ts
        var generatorHelper = {
            name: "typescript:generator",
            scoped: false,
            priority: 6,
            text: "\n            var __generator = (this && this.__generator) || function (thisArg, body) {\n                var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n                return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n                function verb(n) { return function (v) { return step([n, v]); }; }\n                function step(op) {\n                    if (f) throw new TypeError(\"Generator is already executing.\");\n                    while (_) try {\n                        if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n                        if (y = 0, t) op = [op[0] & 2, t.value];\n                        switch (op[0]) {\n                            case 0: case 1: t = op; break;\n                            case 4: _.label++; return { value: op[1], done: false };\n                            case 5: _.label++; y = op[1]; op = [0]; continue;\n                            case 7: op = _.ops.pop(); _.trys.pop(); continue;\n                            default:\n                                if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                                if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                                if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                                if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                                if (t[2]) _.ops.pop();\n                                _.trys.pop(); continue;\n                        }\n                        op = body.call(thisArg, _);\n                    } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n                    if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n                }\n            };"
        };
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function transformModule(context) {
            function getTransformModuleDelegate(moduleKind) {
                switch (moduleKind) {
                    case ts.ModuleKind.AMD: return transformAMDModule;
                    case ts.ModuleKind.UMD: return transformUMDModule;
                    default: return transformCommonJSModule;
                }
            }
            var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
            var compilerOptions = context.getCompilerOptions();
            var resolver = context.getEmitResolver();
            var host = context.getEmitHost();
            var languageVersion = ts.getEmitScriptTarget(compilerOptions);
            var moduleKind = ts.getEmitModuleKind(compilerOptions);
            var previousOnSubstituteNode = context.onSubstituteNode;
            var previousOnEmitNode = context.onEmitNode;
            context.onSubstituteNode = onSubstituteNode;
            context.onEmitNode = onEmitNode;
            context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
            context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols.
            context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
            context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
            context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
            context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file.
            var moduleInfoMap = []; // The ExternalModuleInfo for each file.
            var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
            var currentSourceFile; // The current file.
            var currentModuleInfo; // The ExternalModuleInfo for the current file.
            var noSubstitution; // Set of nodes for which substitution rules should be ignored.
            var needUMDDynamicImportHelper;
            return ts.chainBundle(transformSourceFile);
            /**
             * Transforms the module aspects of a SourceFile.
             *
             * @param node The SourceFile node.
             */
            function transformSourceFile(node) {
                if (node.isDeclarationFile ||
                    !(ts.isEffectiveExternalModule(node, compilerOptions) ||
                        node.transformFlags & 67108864 /* ContainsDynamicImport */ ||
                        (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
                    return node;
                }
                currentSourceFile = node;
                currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
                moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
                // Perform the transformation.
                var transformModule = getTransformModuleDelegate(moduleKind);
                var updated = transformModule(node);
                currentSourceFile = undefined;
                currentModuleInfo = undefined;
                needUMDDynamicImportHelper = false;
                return ts.aggregateTransformFlags(updated);
            }
            function shouldEmitUnderscoreUnderscoreESModule() {
                if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
                    return true;
                }
                return false;
            }
            /**
             * Transforms a SourceFile into a CommonJS module.
             *
             * @param node The SourceFile node.
             */
            function transformCommonJSModule(node) {
                startLexicalEnvironment();
                var statements = [];
                var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
                var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
                if (shouldEmitUnderscoreUnderscoreESModule()) {
                    ts.append(statements, createUnderscoreUnderscoreESModule());
                }
                ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
                ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
                addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
                if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
                    // If we have any `export * from ...` declarations
                    // we need to inform the emitter to add the __export helper.
                    ts.addEmitHelper(updated, exportStarHelper);
                }
                ts.addEmitHelpers(updated, context.readEmitHelpers());
                return updated;
            }
            /**
             * Transforms a SourceFile into an AMD module.
             *
             * @param node The SourceFile node.
             */
            function transformAMDModule(node) {
                var define = ts.createIdentifier("define");
                var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
                var jsonSourceFile = ts.isJsonSourceFile(node) && node;
                // An AMD define function has the following shape:
                //
                //     define(id?, dependencies?, factory);
                //
                // This has the shape of the following:
                //
                //     define(name, ["module1", "module2"], function (module1Alias) { ... }
                //
                // The location of the alias in the parameter list in the factory function needs to
                // match the position of the module name in the dependency list.
                //
                // To ensure this is true in cases of modules with no aliases, e.g.:
                //
                //     import "module"
                //
                // or
                //
                //     /// <amd-dependency path= "a.css" />
                //
                // we need to add modules without alias names to the end of the dependencies list
                var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
                // Create an updated SourceFile:
                //
                //     define(moduleName?, ["module1", "module2"], function ...
                var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
                    ts.createExpressionStatement(ts.createCall(define, 
                    /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([
                        // Add the dependency array argument:
                        //
                        //     ["require", "exports", module1", "module2", ...]
                        ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [
                            ts.createLiteral("require"),
                            ts.createLiteral("exports")
                        ].concat(aliasedModuleNames, unaliasedModuleNames)),
                        // Add the module body function argument:
                        //
                        //     function (require, exports, module1, module2) ...
                        jsonSourceFile ?
                            jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
                            ts.createFunctionExpression(
                            /*modifiers*/ undefined, 
                            /*asteriskToken*/ undefined, 
                            /*name*/ undefined, 
                            /*typeParameters*/ undefined, [
                                ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
                                ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
                            ].concat(importAliasNames), 
                            /*type*/ undefined, transformAsynchronousModuleBody(node))
                    ])))
                ]), 
                /*location*/ node.statements));
                ts.addEmitHelpers(updated, context.readEmitHelpers());
                return updated;
            }
            /**
             * Transforms a SourceFile into a UMD module.
             *
             * @param node The SourceFile node.
             */
            function transformUMDModule(node) {
                var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
                var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
                var umdHeader = ts.createFunctionExpression(
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
                /*type*/ undefined, ts.setTextRange(ts.createBlock([
                    ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
                        ts.createVariableStatement(
                        /*modifiers*/ undefined, [
                            ts.createVariableDeclaration("v", 
                            /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), 
                            /*typeArguments*/ undefined, [
                                ts.createIdentifier("require"),
                                ts.createIdentifier("exports")
                            ]))
                        ]),
                        ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */)
                    ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
                        ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), 
                        /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([
                            ts.createArrayLiteral([
                                ts.createLiteral("require"),
                                ts.createLiteral("exports")
                            ].concat(aliasedModuleNames, unaliasedModuleNames)),
                            ts.createIdentifier("factory")
                        ])))
                    ])))
                ], 
                /*multiLine*/ true), 
                /*location*/ undefined));
                // Create an updated SourceFile:
                //
                //  (function (factory) {
                //      if (typeof module === "object" && typeof module.exports === "object") {
                //          var v = factory(require, exports);
                //          if (v !== undefined) module.exports = v;
                //      }
                //      else if (typeof define === 'function' && define.amd) {
                //          define(["require", "exports"], factory);
                //      }
                //  })(function ...)
                var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
                    ts.createExpressionStatement(ts.createCall(umdHeader, 
                    /*typeArguments*/ undefined, [
                        // Add the module body function argument:
                        //
                        //     function (require, exports) ...
                        ts.createFunctionExpression(
                        /*modifiers*/ undefined, 
                        /*asteriskToken*/ undefined, 
                        /*name*/ undefined, 
                        /*typeParameters*/ undefined, [
                            ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
                            ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
                        ].concat(importAliasNames), 
                        /*type*/ undefined, transformAsynchronousModuleBody(node))
                    ]))
                ]), 
                /*location*/ node.statements));
                ts.addEmitHelpers(updated, context.readEmitHelpers());
                return updated;
            }
            /**
             * Collect the additional asynchronous dependencies for the module.
             *
             * @param node The source file.
             * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
             */
            function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
                // names of modules with corresponding parameter in the factory function
                var aliasedModuleNames = [];
                // names of modules with no corresponding parameters in factory function
                var unaliasedModuleNames = [];
                // names of the parameters in the factory function; these
                // parameters need to match the indexes of the corresponding
                // module names in aliasedModuleNames.
                var importAliasNames = [];
                // Fill in amd-dependency tags
                for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
                    var amdDependency = _a[_i];
                    if (amdDependency.name) {
                        aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
                        importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
                    }
                    else {
                        unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
                    }
                }
                for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
                    var importNode = _c[_b];
                    // Find the name of the external module
                    var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
                    // Find the name of the module alias, if there is one
                    var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
                    // It is possible that externalModuleName is undefined if it is not string literal.
                    // This can happen in the invalid import syntax.
                    // E.g : "import * from alias from 'someLib';"
                    if (externalModuleName) {
                        if (includeNonAmdDependencies && importAliasName) {
                            // Set emitFlags on the name of the classDeclaration
                            // This is so that when printer will not substitute the identifier
                            ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
                            aliasedModuleNames.push(externalModuleName);
                            importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
                        }
                        else {
                            unaliasedModuleNames.push(externalModuleName);
                        }
                    }
                }
                return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
            }
            function getAMDImportExpressionForImport(node) {
                if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
                    return undefined;
                }
                var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
                var expr = getHelperExpressionForImport(node, name);
                if (expr === name) {
                    return undefined;
                }
                return ts.createExpressionStatement(ts.createAssignment(name, expr));
            }
            /**
             * Transforms a SourceFile into an AMD or UMD module body.
             *
             * @param node The SourceFile node.
             */
            function transformAsynchronousModuleBody(node) {
                startLexicalEnvironment();
                var statements = [];
                var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
                if (shouldEmitUnderscoreUnderscoreESModule()) {
                    ts.append(statements, createUnderscoreUnderscoreESModule());
                }
                // Visit each statement of the module body.
                ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
                if (moduleKind === ts.ModuleKind.AMD) {
                    ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
                }
                ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
                // Append the 'export =' statement if provided.
                addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
                // End the lexical environment for the module body
                // and merge any new lexical declarations.
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                var body = ts.createBlock(statements, /*multiLine*/ true);
                if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
                    // If we have any `export * from ...` declarations
                    // we need to inform the emitter to add the __export helper.
                    ts.addEmitHelper(body, exportStarHelper);
                }
                if (needUMDDynamicImportHelper) {
                    ts.addEmitHelper(body, dynamicImportUMDHelper);
                }
                return body;
            }
            /**
             * Adds the down-level representation of `export=` to the statement list if one exists
             * in the source file.
             *
             * @param statements The Statement list to modify.
             * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
             * return statement.
             */
            function addExportEqualsIfNeeded(statements, emitAsReturn) {
                if (currentModuleInfo.exportEquals) {
                    var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
                    if (expressionResult) {
                        if (emitAsReturn) {
                            var statement = ts.createReturn(expressionResult);
                            ts.setTextRange(statement, currentModuleInfo.exportEquals);
                            ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
                            statements.push(statement);
                        }
                        else {
                            var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
                            ts.setTextRange(statement, currentModuleInfo.exportEquals);
                            ts.setEmitFlags(statement, 1536 /* NoComments */);
                            statements.push(statement);
                        }
                    }
                }
            }
            //
            // Top-Level Source Element Visitors
            //
            /**
             * Visits a node at the top level of the source file.
             *
             * @param node The node to visit.
             */
            function sourceElementVisitor(node) {
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                        return visitImportDeclaration(node);
                    case 246 /* ImportEqualsDeclaration */:
                        return visitImportEqualsDeclaration(node);
                    case 253 /* ExportDeclaration */:
                        return visitExportDeclaration(node);
                    case 252 /* ExportAssignment */:
                        return visitExportAssignment(node);
                    case 217 /* VariableStatement */:
                        return visitVariableStatement(node);
                    case 237 /* FunctionDeclaration */:
                        return visitFunctionDeclaration(node);
                    case 238 /* ClassDeclaration */:
                        return visitClassDeclaration(node);
                    case 308 /* MergeDeclarationMarker */:
                        return visitMergeDeclarationMarker(node);
                    case 309 /* EndOfDeclarationMarker */:
                        return visitEndOfDeclarationMarker(node);
                    default:
                        return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
                }
            }
            function moduleExpressionElementVisitor(node) {
                // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
                // as export/import statements are only transformed at the top level of a file.
                if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
                    return node;
                }
                if (ts.isImportCall(node)) {
                    return visitImportCallExpression(node);
                }
                else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
                    return visitDestructuringAssignment(node);
                }
                else {
                    return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
                }
            }
            function destructuringNeedsFlattening(node) {
                if (ts.isObjectLiteralExpression(node)) {
                    for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
                        var elem = _a[_i];
                        switch (elem.kind) {
                            case 273 /* PropertyAssignment */:
                                if (destructuringNeedsFlattening(elem.initializer)) {
                                    return true;
                                }
                                break;
                            case 274 /* ShorthandPropertyAssignment */:
                                if (destructuringNeedsFlattening(elem.name)) {
                                    return true;
                                }
                                break;
                            case 275 /* SpreadAssignment */:
                                if (destructuringNeedsFlattening(elem.expression)) {
                                    return true;
                                }
                                break;
                            case 154 /* MethodDeclaration */:
                            case 156 /* GetAccessor */:
                            case 157 /* SetAccessor */:
                                return false;
                            default: ts.Debug.assertNever(elem, "Unhandled object member kind");
                        }
                    }
                }
                else if (ts.isArrayLiteralExpression(node)) {
                    for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
                        var elem = _c[_b];
                        if (ts.isSpreadElement(elem)) {
                            if (destructuringNeedsFlattening(elem.expression)) {
                                return true;
                            }
                        }
                        else if (destructuringNeedsFlattening(elem)) {
                            return true;
                        }
                    }
                }
                else if (ts.isIdentifier(node)) {
                    return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
                }
                return false;
            }
            function visitDestructuringAssignment(node) {
                if (destructuringNeedsFlattening(node.left)) {
                    return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
                }
                return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
            }
            function visitImportCallExpression(node) {
                var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
                var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */);
                switch (compilerOptions.module) {
                    case ts.ModuleKind.AMD:
                        return createImportCallExpressionAMD(argument, containsLexicalThis);
                    case ts.ModuleKind.UMD:
                        return createImportCallExpressionUMD(argument, containsLexicalThis);
                    case ts.ModuleKind.CommonJS:
                    default:
                        return createImportCallExpressionCommonJS(argument, containsLexicalThis);
                }
            }
            function createImportCallExpressionUMD(arg, containsLexicalThis) {
                // (function (factory) {
                //      ... (regular UMD)
                // }
                // })(function (require, exports, useSyncRequire) {
                //      "use strict";
                //      Object.defineProperty(exports, "__esModule", { value: true });
                //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
                //      var __resolved = new Promise(function (resolve) { resolve(); });
                //      .....
                //      __syncRequire
                //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
                //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
                // });
                needUMDDynamicImportHelper = true;
                if (ts.isSimpleCopiableExpression(arg)) {
                    var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
                    return ts.createConditional(
                    /*condition*/ ts.createIdentifier("__syncRequire"), 
                    /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
                    /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
                }
                else {
                    var temp = ts.createTempVariable(hoistVariableDeclaration);
                    return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
                    /*condition*/ ts.createIdentifier("__syncRequire"), 
                    /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
                    /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
                }
            }
            function createImportCallExpressionAMD(arg, containsLexicalThis) {
                // improt("./blah")
                // emit as
                // define(["require", "exports", "blah"], function (require, exports) {
                //     ...
                //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
                // });
                var resolve = ts.createUniqueName("resolve");
                var reject = ts.createUniqueName("reject");
                var parameters = [
                    ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
                    ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
                ];
                var body = ts.createBlock([
                    ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), 
                    /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
                ]);
                var func;
                if (languageVersion >= 2 /* ES2015 */) {
                    func = ts.createArrowFunction(
                    /*modifiers*/ undefined, 
                    /*typeParameters*/ undefined, parameters, 
                    /*type*/ undefined, 
                    /*equalsGreaterThanToken*/ undefined, body);
                }
                else {
                    func = ts.createFunctionExpression(
                    /*modifiers*/ undefined, 
                    /*asteriskToken*/ undefined, 
                    /*name*/ undefined, 
                    /*typeParameters*/ undefined, parameters, 
                    /*type*/ undefined, body);
                    // if there is a lexical 'this' in the import call arguments, ensure we indicate
                    // that this new function expression indicates it captures 'this' so that the
                    // es2015 transformer will properly substitute 'this' with '_this'.
                    if (containsLexicalThis) {
                        ts.setEmitFlags(func, 8 /* CapturesThis */);
                    }
                }
                var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
                if (compilerOptions.esModuleInterop) {
                    context.requestEmitHelper(importStarHelper);
                    return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
                }
                return promise;
            }
            function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
                // import("./blah")
                // emit as
                // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
                // We have to wrap require in then callback so that require is done in asynchronously
                // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
                var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
                var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
                if (compilerOptions.esModuleInterop) {
                    context.requestEmitHelper(importStarHelper);
                    requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
                }
                var func;
                if (languageVersion >= 2 /* ES2015 */) {
                    func = ts.createArrowFunction(
                    /*modifiers*/ undefined, 
                    /*typeParameters*/ undefined, 
                    /*parameters*/ [], 
                    /*type*/ undefined, 
                    /*equalsGreaterThanToken*/ undefined, requireCall);
                }
                else {
                    func = ts.createFunctionExpression(
                    /*modifiers*/ undefined, 
                    /*asteriskToken*/ undefined, 
                    /*name*/ undefined, 
                    /*typeParameters*/ undefined, 
                    /*parameters*/ [], 
                    /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
                    // if there is a lexical 'this' in the import call arguments, ensure we indicate
                    // that this new function expression indicates it captures 'this' so that the
                    // es2015 transformer will properly substitute 'this' with '_this'.
                    if (containsLexicalThis) {
                        ts.setEmitFlags(func, 8 /* CapturesThis */);
                    }
                }
                return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
            }
            function getHelperExpressionForImport(node, innerExpr) {
                if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
                    return innerExpr;
                }
                if (ts.getImportNeedsImportStarHelper(node)) {
                    context.requestEmitHelper(importStarHelper);
                    return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
                }
                if (ts.getImportNeedsImportDefaultHelper(node)) {
                    context.requestEmitHelper(importDefaultHelper);
                    return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
                }
                return innerExpr;
            }
            /**
             * Visits an ImportDeclaration node.
             *
             * @param node The node to visit.
             */
            function visitImportDeclaration(node) {
                var statements;
                var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
                if (moduleKind !== ts.ModuleKind.AMD) {
                    if (!node.importClause) {
                        // import "mod";
                        return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
                    }
                    else {
                        var variables = [];
                        if (namespaceDeclaration && !ts.isDefaultImport(node)) {
                            // import * as n from "mod";
                            variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
                            /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
                        }
                        else {
                            // import d from "mod";
                            // import { x, y } from "mod";
                            // import d, { x, y } from "mod";
                            // import d, * as n from "mod";
                            variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), 
                            /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
                            if (namespaceDeclaration && ts.isDefaultImport(node)) {
                                variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
                                /*type*/ undefined, ts.getGeneratedNameForNode(node)));
                            }
                        }
                        statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
                        /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
                        /*location*/ node), 
                        /*original*/ node));
                    }
                }
                else if (namespaceDeclaration && ts.isDefaultImport(node)) {
                    // import d, * as n from "mod";
                    statements = ts.append(statements, ts.createVariableStatement(
                    /*modifiers*/ undefined, ts.createVariableDeclarationList([
                        ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
                        /*type*/ undefined, ts.getGeneratedNameForNode(node)), 
                        /*location*/ node), 
                        /*original*/ node)
                    ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
                }
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfImportDeclaration(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Creates a `require()` call to import an external module.
             *
             * @param importNode The declararation to import.
             */
            function createRequireCall(importNode) {
                var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
                var args = [];
                if (moduleName) {
                    args.push(moduleName);
                }
                return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
            }
            /**
             * Visits an ImportEqualsDeclaration node.
             *
             * @param node The node to visit.
             */
            function visitImportEqualsDeclaration(node) {
                ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
                var statements;
                if (moduleKind !== ts.ModuleKind.AMD) {
                    if (ts.hasModifier(node, 1 /* Export */)) {
                        statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
                    }
                    else {
                        statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
                        /*modifiers*/ undefined, ts.createVariableDeclarationList([
                            ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), 
                            /*type*/ undefined, createRequireCall(node))
                        ], 
                        /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
                    }
                }
                else {
                    if (ts.hasModifier(node, 1 /* Export */)) {
                        statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
                    }
                }
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfImportEqualsDeclaration(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits an ExportDeclaration node.
             *
             * @param The node to visit.
             */
            function visitExportDeclaration(node) {
                if (!node.moduleSpecifier) {
                    // Elide export declarations with no module specifier as they are handled
                    // elsewhere.
                    return undefined;
                }
                var generatedName = ts.getGeneratedNameForNode(node);
                if (node.exportClause) {
                    var statements = [];
                    // export { x, y } from "mod";
                    if (moduleKind !== ts.ModuleKind.AMD) {
                        statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
                        /*modifiers*/ undefined, ts.createVariableDeclarationList([
                            ts.createVariableDeclaration(generatedName, 
                            /*type*/ undefined, createRequireCall(node))
                        ])), 
                        /*location*/ node), 
                        /* original */ node));
                    }
                    for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
                        var specifier = _a[_i];
                        var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
                        statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier));
                    }
                    return ts.singleOrMany(statements);
                }
                else {
                    // export * from "mod";
                    return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
                }
            }
            /**
             * Visits an ExportAssignment node.
             *
             * @param node The node to visit.
             */
            function visitExportAssignment(node) {
                if (node.isExportEquals) {
                    return undefined;
                }
                var statements;
                var original = node.original;
                if (original && hasAssociatedEndOfDeclarationMarker(original)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
                }
                else {
                    statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits a FunctionDeclaration node.
             *
             * @param node The node to visit.
             */
            function visitFunctionDeclaration(node) {
                var statements;
                if (ts.hasModifier(node, 1 /* Export */)) {
                    statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
                    /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
                    /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
                    /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
                    /*location*/ node), 
                    /*original*/ node));
                }
                else {
                    statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
                }
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfHoistedDeclaration(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits a ClassDeclaration node.
             *
             * @param node The node to visit.
             */
            function visitClassDeclaration(node) {
                var statements;
                if (ts.hasModifier(node, 1 /* Export */)) {
                    statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
                    /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
                    /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
                }
                else {
                    statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
                }
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfHoistedDeclaration(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits a VariableStatement node.
             *
             * @param node The node to visit.
             */
            function visitVariableStatement(node) {
                var statements;
                var variables;
                var expressions;
                if (ts.hasModifier(node, 1 /* Export */)) {
                    var modifiers = void 0;
                    // If we're exporting these variables, then these just become assignments to 'exports.x'.
                    // We only want to emit assignments for variables with initializers.
                    for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                        var variable = _a[_i];
                        if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
                            if (!modifiers) {
                                modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
                            }
                            variables = ts.append(variables, variable);
                        }
                        else if (variable.initializer) {
                            expressions = ts.append(expressions, transformInitializedVariable(variable));
                        }
                    }
                    if (variables) {
                        statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
                    }
                    if (expressions) {
                        statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
                    }
                }
                else {
                    statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
                }
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfVariableStatement(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            function createAllExportExpressions(name, value, location) {
                var exportedNames = getExports(name);
                if (exportedNames) {
                    // For each additional export of the declaration, apply an export assignment.
                    var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
                    for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
                        var exportName = exportedNames_1[_i];
                        // Mark the node to prevent triggering substitution.
                        ts.setEmitFlags(expression, 4 /* NoSubstitution */);
                        expression = createExportExpression(exportName, expression, /*location*/ location);
                    }
                    return expression;
                }
                return ts.createAssignment(name, value);
            }
            /**
             * Transforms an exported variable with an initializer into an expression.
             *
             * @param node The node to transform.
             */
            function transformInitializedVariable(node) {
                if (ts.isBindingPattern(node.name)) {
                    return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
                    /*visitor*/ undefined, context, 0 /* All */, 
                    /*needsValue*/ false, createAllExportExpressions);
                }
                else {
                    return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), 
                    /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor));
                }
            }
            /**
             * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
             * and transformed declaration.
             *
             * @param node The node to visit.
             */
            function visitMergeDeclarationMarker(node) {
                // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
                // declaration we do not emit a leading variable declaration. To preserve the
                // begin/end semantics of the declararation and to properly handle exports
                // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
                //
                // To balance the declaration, add the exports of the elided variable
                // statement.
                if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) {
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
                }
                return node;
            }
            /**
             * Determines whether a node has an associated EndOfDeclarationMarker.
             *
             * @param node The node to test.
             */
            function hasAssociatedEndOfDeclarationMarker(node) {
                return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
            }
            /**
             * Visits a DeclarationMarker used as a placeholder for the end of a transformed
             * declaration.
             *
             * @param node The node to visit.
             */
            function visitEndOfDeclarationMarker(node) {
                // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
                // end of the transformed declaration. We use this marker to emit any deferred exports
                // of the declaration.
                var id = ts.getOriginalNodeId(node);
                var statements = deferredExports[id];
                if (statements) {
                    delete deferredExports[id];
                    return ts.append(statements, node);
                }
                return node;
            }
            /**
             * Appends the exports of an ImportDeclaration to a statement list, returning the
             * statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             */
            function appendExportsOfImportDeclaration(statements, decl) {
                if (currentModuleInfo.exportEquals) {
                    return statements;
                }
                var importClause = decl.importClause;
                if (!importClause) {
                    return statements;
                }
                if (importClause.name) {
                    statements = appendExportsOfDeclaration(statements, importClause);
                }
                var namedBindings = importClause.namedBindings;
                if (namedBindings) {
                    switch (namedBindings.kind) {
                        case 249 /* NamespaceImport */:
                            statements = appendExportsOfDeclaration(statements, namedBindings);
                            break;
                        case 250 /* NamedImports */:
                            for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
                                var importBinding = _a[_i];
                                statements = appendExportsOfDeclaration(statements, importBinding);
                            }
                            break;
                    }
                }
                return statements;
            }
            /**
             * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
             * statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             */
            function appendExportsOfImportEqualsDeclaration(statements, decl) {
                if (currentModuleInfo.exportEquals) {
                    return statements;
                }
                return appendExportsOfDeclaration(statements, decl);
            }
            /**
             * Appends the exports of a VariableStatement to a statement list, returning the statement
             * list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param node The VariableStatement whose exports are to be recorded.
             */
            function appendExportsOfVariableStatement(statements, node) {
                if (currentModuleInfo.exportEquals) {
                    return statements;
                }
                for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                    var decl = _a[_i];
                    statements = appendExportsOfBindingElement(statements, decl);
                }
                return statements;
            }
            /**
             * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
             * returning the statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             */
            function appendExportsOfBindingElement(statements, decl) {
                if (currentModuleInfo.exportEquals) {
                    return statements;
                }
                if (ts.isBindingPattern(decl.name)) {
                    for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
                        var element = _a[_i];
                        if (!ts.isOmittedExpression(element)) {
                            statements = appendExportsOfBindingElement(statements, element);
                        }
                    }
                }
                else if (!ts.isGeneratedIdentifier(decl.name)) {
                    statements = appendExportsOfDeclaration(statements, decl);
                }
                return statements;
            }
            /**
             * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
             * returning the statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             */
            function appendExportsOfHoistedDeclaration(statements, decl) {
                if (currentModuleInfo.exportEquals) {
                    return statements;
                }
                if (ts.hasModifier(decl, 1 /* Export */)) {
                    var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
                    statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
                }
                if (decl.name) {
                    statements = appendExportsOfDeclaration(statements, decl);
                }
                return statements;
            }
            /**
             * Appends the exports of a declaration to a statement list, returning the statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration to export.
             */
            function appendExportsOfDeclaration(statements, decl) {
                var name = ts.getDeclarationName(decl);
                var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
                if (exportSpecifiers) {
                    for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
                        var exportSpecifier = exportSpecifiers_1[_i];
                        statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name);
                    }
                }
                return statements;
            }
            /**
             * Appends the down-level representation of an export to a statement list, returning the
             * statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param exportName The name of the export.
             * @param expression The expression to export.
             * @param location The location to use for source maps and comments for the export.
             * @param allowComments Whether to allow comments on the export.
             */
            function appendExportStatement(statements, exportName, expression, location, allowComments) {
                statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments));
                return statements;
            }
            function createUnderscoreUnderscoreESModule() {
                var statement;
                if (languageVersion === 0 /* ES3 */) {
                    statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
                }
                else {
                    statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
                    /*typeArguments*/ undefined, [
                        ts.createIdentifier("exports"),
                        ts.createLiteral("__esModule"),
                        ts.createObjectLiteral([
                            ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
                        ])
                    ]));
                }
                ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
                return statement;
            }
            /**
             * Creates a call to the current file's export function to export a value.
             *
             * @param name The bound name of the export.
             * @param value The exported value.
             * @param location The location to use for source maps and comments for the export.
             * @param allowComments An optional value indicating whether to emit comments for the statement.
             */
            function createExportStatement(name, value, location, allowComments) {
                var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location);
                ts.startOnNewLine(statement);
                if (!allowComments) {
                    ts.setEmitFlags(statement, 1536 /* NoComments */);
                }
                return statement;
            }
            /**
             * Creates a call to the current file's export function to export a value.
             *
             * @param name The bound name of the export.
             * @param value The exported value.
             * @param location The location to use for source maps and comments for the export.
             */
            function createExportExpression(name, value, location) {
                return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
            }
            //
            // Modifier Visitors
            //
            /**
             * Visit nodes to elide module-specific modifiers.
             *
             * @param node The node to visit.
             */
            function modifierVisitor(node) {
                // Elide module-specific modifiers.
                switch (node.kind) {
                    case 84 /* ExportKeyword */:
                    case 79 /* DefaultKeyword */:
                        return undefined;
                }
                return node;
            }
            //
            // Emit Notification
            //
            /**
             * Hook for node emit notifications.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emit A callback used to emit the node in the printer.
             */
            function onEmitNode(hint, node, emitCallback) {
                if (node.kind === 277 /* SourceFile */) {
                    currentSourceFile = node;
                    currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
                    noSubstitution = [];
                    previousOnEmitNode(hint, node, emitCallback);
                    currentSourceFile = undefined;
                    currentModuleInfo = undefined;
                    noSubstitution = undefined;
                }
                else {
                    previousOnEmitNode(hint, node, emitCallback);
                }
            }
            //
            // Substitutions
            //
            /**
             * Hooks node substitutions.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (node.id && noSubstitution[node.id]) {
                    return node;
                }
                if (hint === 1 /* Expression */) {
                    return substituteExpression(node);
                }
                else if (ts.isShorthandPropertyAssignment(node)) {
                    return substituteShorthandPropertyAssignment(node);
                }
                return node;
            }
            /**
             * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
             * or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteShorthandPropertyAssignment(node) {
                var name = node.name;
                var exportedOrImportedName = substituteExpressionIdentifier(name);
                if (exportedOrImportedName !== name) {
                    // A shorthand property with an assignment initializer is probably part of a
                    // destructuring assignment
                    if (node.objectAssignmentInitializer) {
                        var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
                        return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
                    }
                    return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
                }
                return node;
            }
            /**
             * Substitution for an Expression that may contain an imported or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteExpression(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return substituteExpressionIdentifier(node);
                    case 202 /* BinaryExpression */:
                        return substituteBinaryExpression(node);
                    case 201 /* PostfixUnaryExpression */:
                    case 200 /* PrefixUnaryExpression */:
                        return substituteUnaryExpression(node);
                }
                return node;
            }
            /**
             * Substitution for an Identifier expression that may contain an imported or exported
             * symbol.
             *
             * @param node The node to substitute.
             */
            function substituteExpressionIdentifier(node) {
                if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
                    var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
                    if (externalHelpersModuleName) {
                        return ts.createPropertyAccess(externalHelpersModuleName, node);
                    }
                    return node;
                }
                if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
                    var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
                    if (exportContainer && exportContainer.kind === 277 /* SourceFile */) {
                        return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), 
                        /*location*/ node);
                    }
                    var importDeclaration = resolver.getReferencedImportDeclaration(node);
                    if (importDeclaration) {
                        if (ts.isImportClause(importDeclaration)) {
                            return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
                            /*location*/ node);
                        }
                        else if (ts.isImportSpecifier(importDeclaration)) {
                            var name = importDeclaration.propertyName || importDeclaration.name;
                            return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), 
                            /*location*/ node);
                        }
                    }
                }
                return node;
            }
            /**
             * Substitution for a BinaryExpression that may contain an imported or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteBinaryExpression(node) {
                // When we see an assignment expression whose left-hand side is an exported symbol,
                // we should ensure all exports of that symbol are updated with the correct value.
                //
                // - We do not substitute generated identifiers for any reason.
                // - We do not substitute identifiers tagged with the LocalName flag.
                // - We do not substitute identifiers that were originally the name of an enum or
                //   namespace due to how they are transformed in TypeScript.
                // - We only substitute identifiers that are exported at the top level.
                if (ts.isAssignmentOperator(node.operatorToken.kind)
                    && ts.isIdentifier(node.left)
                    && !ts.isGeneratedIdentifier(node.left)
                    && !ts.isLocalName(node.left)
                    && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
                    var exportedNames = getExports(node.left);
                    if (exportedNames) {
                        // For each additional export of the declaration, apply an export assignment.
                        var expression = node;
                        for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
                            var exportName = exportedNames_2[_i];
                            // Mark the node to prevent triggering this rule again.
                            noSubstitution[ts.getNodeId(expression)] = true;
                            expression = createExportExpression(exportName, expression, /*location*/ node);
                        }
                        return expression;
                    }
                }
                return node;
            }
            /**
             * Substitution for a UnaryExpression that may contain an imported or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteUnaryExpression(node) {
                // When we see a prefix or postfix increment expression whose operand is an exported
                // symbol, we should ensure all exports of that symbol are updated with the correct
                // value.
                //
                // - We do not substitute generated identifiers for any reason.
                // - We do not substitute identifiers tagged with the LocalName flag.
                // - We do not substitute identifiers that were originally the name of an enum or
                //   namespace due to how they are transformed in TypeScript.
                // - We only substitute identifiers that are exported at the top level.
                if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */)
                    && ts.isIdentifier(node.operand)
                    && !ts.isGeneratedIdentifier(node.operand)
                    && !ts.isLocalName(node.operand)
                    && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
                    var exportedNames = getExports(node.operand);
                    if (exportedNames) {
                        var expression = node.kind === 201 /* PostfixUnaryExpression */
                            ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), 
                            /*location*/ node)
                            : node;
                        for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
                            var exportName = exportedNames_3[_i];
                            // Mark the node to prevent triggering this rule again.
                            noSubstitution[ts.getNodeId(expression)] = true;
                            expression = createExportExpression(exportName, expression);
                        }
                        return expression;
                    }
                }
                return node;
            }
            /**
             * Gets the additional exports of a name.
             *
             * @param name The name.
             */
            function getExports(name) {
                if (!ts.isGeneratedIdentifier(name)) {
                    var valueDeclaration = resolver.getReferencedImportDeclaration(name)
                        || resolver.getReferencedValueDeclaration(name);
                    if (valueDeclaration) {
                        return currentModuleInfo
                            && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
                    }
                }
            }
        }
        ts.transformModule = transformModule;
        // emit output for the __export helper function
        var exportStarHelper = {
            name: "typescript:export-star",
            scoped: true,
            text: "\n            function __export(m) {\n                for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n            }"
        };
        function createExportStarHelper(context, module) {
            var compilerOptions = context.getCompilerOptions();
            return compilerOptions.importHelpers
                ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")])
                : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]);
        }
        // emit helper for dynamic import
        var dynamicImportUMDHelper = {
            name: "typescript:dynamicimport-sync-require",
            scoped: true,
            text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
        };
        // emit helper for `import * as Name from "foo"`
        var importStarHelper = {
            name: "typescript:commonjsimportstar",
            scoped: false,
            text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n    if (mod && mod.__esModule) return mod;\n    var result = {};\n    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n    result[\"default\"] = mod;\n    return result;\n};"
        };
        // emit helper for `import Name from "foo"`
        var importDefaultHelper = {
            name: "typescript:commonjsimportdefault",
            scoped: false,
            text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
        };
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function transformSystemModule(context) {
            var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
            var compilerOptions = context.getCompilerOptions();
            var resolver = context.getEmitResolver();
            var host = context.getEmitHost();
            var previousOnSubstituteNode = context.onSubstituteNode;
            var previousOnEmitNode = context.onEmitNode;
            context.onSubstituteNode = onSubstituteNode;
            context.onEmitNode = onEmitNode;
            context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols.
            context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
            context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols.
            context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
            context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
            context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file.
            var moduleInfoMap = []; // The ExternalModuleInfo for each file.
            var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
            var exportFunctionsMap = []; // The export function associated with a source file.
            var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
            var currentSourceFile; // The current file.
            var moduleInfo; // ExternalModuleInfo for the current file.
            var exportFunction; // The export function for the current file.
            var contextObject; // The context object for the current file.
            var hoistedStatements;
            var enclosingBlockScopedContainer;
            var noSubstitution; // Set of nodes for which substitution rules should be ignored.
            return ts.chainBundle(transformSourceFile);
            /**
             * Transforms the module aspects of a SourceFile.
             *
             * @param node The SourceFile node.
             */
            function transformSourceFile(node) {
                if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) {
                    return node;
                }
                var id = ts.getOriginalNodeId(node);
                currentSourceFile = node;
                enclosingBlockScopedContainer = node;
                // System modules have the following shape:
                //
                //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
                //
                // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
                // is used to publish exported values. 'exports' returns its 'value' argument so in
                // most cases expressions that mutate exported values can be rewritten as:
                //
                //     expr -> exports('name', expr)
                //
                // The only exception in this rule is postfix unary operators,
                // see comment to 'substitutePostfixUnaryExpression' for more details
                // Collect information about the external module and dependency groups.
                moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
                // Make sure that the name of the 'exports' function does not conflict with
                // existing identifiers.
                exportFunction = ts.createUniqueName("exports");
                exportFunctionsMap[id] = exportFunction;
                contextObject = ts.createUniqueName("context");
                // Add the body of the module.
                var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
                var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
                var moduleBodyFunction = ts.createFunctionExpression(
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, 
                /*name*/ undefined, 
                /*typeParameters*/ undefined, [
                    ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
                    ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
                ], 
                /*type*/ undefined, moduleBodyBlock);
                // Write the call to `System.register`
                // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
                // So the helper will be emit at the correct position instead of at the top of the source-file
                var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
                var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
                var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
                    ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), 
                    /*typeArguments*/ undefined, moduleName
                        ? [moduleName, dependencies, moduleBodyFunction]
                        : [dependencies, moduleBodyFunction]))
                ]), node.statements)), 1024 /* NoTrailingComments */);
                if (!(compilerOptions.outFile || compilerOptions.out)) {
                    ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
                }
                if (noSubstitution) {
                    noSubstitutionMap[id] = noSubstitution;
                    noSubstitution = undefined;
                }
                currentSourceFile = undefined;
                moduleInfo = undefined;
                exportFunction = undefined;
                contextObject = undefined;
                hoistedStatements = undefined;
                enclosingBlockScopedContainer = undefined;
                return ts.aggregateTransformFlags(updated);
            }
            /**
             * Collects the dependency groups for this files imports.
             *
             * @param externalImports The imports for the file.
             */
            function collectDependencyGroups(externalImports) {
                var groupIndices = ts.createMap();
                var dependencyGroups = [];
                for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
                    var externalImport = externalImports_1[_i];
                    var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
                    if (externalModuleName) {
                        var text = externalModuleName.text;
                        var groupIndex = groupIndices.get(text);
                        if (groupIndex !== undefined) {
                            // deduplicate/group entries in dependency list by the dependency name
                            dependencyGroups[groupIndex].externalImports.push(externalImport);
                        }
                        else {
                            groupIndices.set(text, dependencyGroups.length);
                            dependencyGroups.push({
                                name: externalModuleName,
                                externalImports: [externalImport]
                            });
                        }
                    }
                }
                return dependencyGroups;
            }
            /**
             * Adds the statements for the module body function for the source file.
             *
             * @param node The source file for the module.
             * @param dependencyGroups The grouped dependencies of the module.
             */
            function createSystemModuleBody(node, dependencyGroups) {
                // Shape of the body in system modules:
                //
                //  function (exports) {
                //      <list of local aliases for imports>
                //      <hoisted variable declarations>
                //      <hoisted function declarations>
                //      return {
                //          setters: [
                //              <list of setter function for imports>
                //          ],
                //          execute: function() {
                //              <module statements>
                //          }
                //      }
                //      <temp declarations>
                //  }
                //
                // i.e:
                //
                //   import {x} from 'file1'
                //   var y = 1;
                //   export function foo() { return y + x(); }
                //   console.log(y);
                //
                // Will be transformed to:
                //
                //  function(exports) {
                //      function foo() { return y + file_1.x(); }
                //      exports("foo", foo);
                //      var file_1, y;
                //      return {
                //          setters: [
                //              function(v) { file_1 = v }
                //          ],
                //          execute(): function() {
                //              y = 1;
                //              console.log(y);
                //          }
                //      };
                //  }
                var statements = [];
                // We start a new lexical environment in this function body, but *not* in the
                // body of the execute function. This allows us to emit temporary declarations
                // only in the outer module body and not in the inner one.
                startLexicalEnvironment();
                // Add any prologue directives.
                var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
                var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
                // var __moduleName = context_1 && context_1.id;
                statements.push(ts.createVariableStatement(
                /*modifiers*/ undefined, ts.createVariableDeclarationList([
                    ts.createVariableDeclaration("__moduleName", 
                    /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
                ])));
                // Visit the synthetic external helpers import declaration if present
                ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
                // Visit the statements of the source file, emitting any transformations into
                // the `executeStatements` array. We do this *before* we fill the `setters` array
                // as we both emit transformations as well as aggregate some data used when creating
                // setters. This allows us to reduce the number of times we need to loop through the
                // statements of the source file.
                var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
                // Emit early exports for function declarations.
                ts.addRange(statements, hoistedStatements);
                // We emit hoisted variables early to align roughly with our previous emit output.
                // Two key differences in this approach are:
                // - Temporary variables will appear at the top rather than at the bottom of the file
                ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
                var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
                var moduleObject = ts.createObjectLiteral([
                    ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
                    ts.createPropertyAssignment("execute", ts.createFunctionExpression(
                    /*modifiers*/ undefined, 
                    /*asteriskToken*/ undefined, 
                    /*name*/ undefined, 
                    /*typeParameters*/ undefined, 
                    /*parameters*/ [], 
                    /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
                ]);
                moduleObject.multiLine = true;
                statements.push(ts.createReturn(moduleObject));
                return ts.createBlock(statements, /*multiLine*/ true);
            }
            /**
             * Adds an exportStar function to a statement list if it is needed for the file.
             *
             * @param statements A statement list.
             */
            function addExportStarIfNeeded(statements) {
                if (!moduleInfo.hasExportStarsToExportValues) {
                    return;
                }
                // when resolving exports local exported entries/indirect exported entries in the module
                // should always win over entries with similar names that were added via star exports
                // to support this we store names of local/indirect exported entries in a set.
                // this set is used to filter names brought by star expors.
                // local names set should only be added if we have anything exported
                if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
                    // no exported declarations (export var ...) or export specifiers (export {x})
                    // check if we have any non star export declarations.
                    var hasExportDeclarationWithExportClause = false;
                    for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
                        var externalImport = _a[_i];
                        if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) {
                            hasExportDeclarationWithExportClause = true;
                            break;
                        }
                    }
                    if (!hasExportDeclarationWithExportClause) {
                        // we still need to emit exportStar helper
                        var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
                        statements.push(exportStarFunction_1);
                        return exportStarFunction_1.name;
                    }
                }
                var exportedNames = [];
                if (moduleInfo.exportedNames) {
                    for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
                        var exportedLocalName = _c[_b];
                        if (exportedLocalName.escapedText === "default") {
                            continue;
                        }
                        // write name of exported declaration, i.e 'export var x...'
                        exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
                    }
                }
                for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
                    var externalImport = _e[_d];
                    if (externalImport.kind !== 253 /* ExportDeclaration */) {
                        continue;
                    }
                    if (!externalImport.exportClause) {
                        // export * from ...
                        continue;
                    }
                    for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
                        var element = _g[_f];
                        // write name of indirectly exported entry, i.e. 'export {x} from ...'
                        exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
                    }
                }
                var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
                statements.push(ts.createVariableStatement(
                /*modifiers*/ undefined, ts.createVariableDeclarationList([
                    ts.createVariableDeclaration(exportedNamesStorageRef, 
                    /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
                ])));
                var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
                statements.push(exportStarFunction);
                return exportStarFunction.name;
            }
            /**
             * Creates an exportStar function for the file, with an optional set of excluded local
             * names.
             *
             * @param localNames An optional reference to an object containing a set of excluded local
             * names.
             */
            function createExportStarFunction(localNames) {
                var exportStarFunction = ts.createUniqueName("exportStar");
                var m = ts.createIdentifier("m");
                var n = ts.createIdentifier("n");
                var exports = ts.createIdentifier("exports");
                var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
                if (localNames) {
                    condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), 
                    /*typeArguments*/ undefined, [n])));
                }
                return ts.createFunctionDeclaration(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, 
                /*asteriskToken*/ undefined, exportStarFunction, 
                /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
                /*type*/ undefined, ts.createBlock([
                    ts.createVariableStatement(
                    /*modifiers*/ undefined, ts.createVariableDeclarationList([
                        ts.createVariableDeclaration(exports, 
                        /*type*/ undefined, ts.createObjectLiteral([]))
                    ])),
                    ts.createForIn(ts.createVariableDeclarationList([
                        ts.createVariableDeclaration(n, /*type*/ undefined)
                    ]), m, ts.createBlock([
                        ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
                    ])),
                    ts.createExpressionStatement(ts.createCall(exportFunction, 
                    /*typeArguments*/ undefined, [exports]))
                ], /*multiline*/ true));
            }
            /**
             * Creates an array setter callbacks for each dependency group.
             *
             * @param exportStarFunction A reference to an exportStarFunction for the file.
             * @param dependencyGroups An array of grouped dependencies.
             */
            function createSettersArray(exportStarFunction, dependencyGroups) {
                var setters = [];
                for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
                    var group_1 = dependencyGroups_1[_i];
                    // derive a unique name for parameter from the first named entry in the group
                    var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
                    var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
                    var statements = [];
                    for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) {
                        var entry = _b[_a];
                        var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
                        switch (entry.kind) {
                            case 247 /* ImportDeclaration */:
                                if (!entry.importClause) {
                                    // 'import "..."' case
                                    // module is imported only for side-effects, no emit required
                                    break;
                                }
                            // falls through
                            case 246 /* ImportEqualsDeclaration */:
                                ts.Debug.assert(importVariableName !== undefined);
                                // save import into the local
                                statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
                                break;
                            case 253 /* ExportDeclaration */:
                                ts.Debug.assert(importVariableName !== undefined);
                                if (entry.exportClause) {
                                    //  export {a, b as c} from 'foo'
                                    //
                                    // emit as:
                                    //
                                    //  exports_({
                                    //     "a": _["a"],
                                    //     "c": _["b"]
                                    //  });
                                    var properties = [];
                                    for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
                                        var e = _d[_c];
                                        properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
                                    }
                                    statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
                                    /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
                                }
                                else {
                                    //  export * from 'foo'
                                    //
                                    // emit as:
                                    //
                                    //  exportStar(foo_1_1);
                                    statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, 
                                    /*typeArguments*/ undefined, [parameterName])));
                                }
                                break;
                        }
                    }
                    setters.push(ts.createFunctionExpression(
                    /*modifiers*/ undefined, 
                    /*asteriskToken*/ undefined, 
                    /*name*/ undefined, 
                    /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
                    /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
                }
                return ts.createArrayLiteral(setters, /*multiLine*/ true);
            }
            //
            // Top-level Source Element Visitors
            //
            /**
             * Visit source elements at the top-level of a module.
             *
             * @param node The node to visit.
             */
            function sourceElementVisitor(node) {
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                        return visitImportDeclaration(node);
                    case 246 /* ImportEqualsDeclaration */:
                        return visitImportEqualsDeclaration(node);
                    case 253 /* ExportDeclaration */:
                        // ExportDeclarations are elided as they are handled via
                        // `appendExportsOfDeclaration`.
                        return undefined;
                    case 252 /* ExportAssignment */:
                        return visitExportAssignment(node);
                    default:
                        return nestedElementVisitor(node);
                }
            }
            /**
             * Visits an ImportDeclaration node.
             *
             * @param node The node to visit.
             */
            function visitImportDeclaration(node) {
                var statements;
                if (node.importClause) {
                    hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
                }
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfImportDeclaration(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits an ImportEqualsDeclaration node.
             *
             * @param node The node to visit.
             */
            function visitImportEqualsDeclaration(node) {
                ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
                var statements;
                hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfImportEqualsDeclaration(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits an ExportAssignment node.
             *
             * @param node The node to visit.
             */
            function visitExportAssignment(node) {
                if (node.isExportEquals) {
                    // Elide `export=` as it is illegal in a SystemJS module.
                    return undefined;
                }
                var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
                var original = node.original;
                if (original && hasAssociatedEndOfDeclarationMarker(original)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
                }
                else {
                    return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
                }
            }
            /**
             * Visits a FunctionDeclaration, hoisting it to the outer module body function.
             *
             * @param node The node to visit.
             */
            function visitFunctionDeclaration(node) {
                if (ts.hasModifier(node, 1 /* Export */)) {
                    hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
                    /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
                    /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
                }
                else {
                    hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
                }
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
                }
                else {
                    hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
                }
                return undefined;
            }
            /**
             * Visits a ClassDeclaration, hoisting its name to the outer module body function.
             *
             * @param node The node to visit.
             */
            function visitClassDeclaration(node) {
                var statements;
                // Hoist the name of the class declaration to the outer module body function.
                var name = ts.getLocalName(node);
                hoistVariableDeclaration(name);
                // Rewrite the class declaration into an assignment of a class expression.
                statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
                /*modifiers*/ undefined, node.name, 
                /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
                if (hasAssociatedEndOfDeclarationMarker(node)) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
                }
                else {
                    statements = appendExportsOfHoistedDeclaration(statements, node);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Visits a variable statement, hoisting declared names to the top-level module body.
             * Each declaration is rewritten into an assignment expression.
             *
             * @param node The node to visit.
             */
            function visitVariableStatement(node) {
                if (!shouldHoistVariableDeclarationList(node.declarationList)) {
                    return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
                }
                var expressions;
                var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
                var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
                for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                    var variable = _a[_i];
                    if (variable.initializer) {
                        expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
                    }
                    else {
                        hoistBindingElement(variable);
                    }
                }
                var statements;
                if (expressions) {
                    statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
                }
                if (isMarkedDeclaration) {
                    // Defer exports until we encounter an EndOfDeclarationMarker node
                    var id = ts.getOriginalNodeId(node);
                    deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
                }
                else {
                    statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
                }
                return ts.singleOrMany(statements);
            }
            /**
             * Hoists the declared names of a VariableDeclaration or BindingElement.
             *
             * @param node The declaration to hoist.
             */
            function hoistBindingElement(node) {
                if (ts.isBindingPattern(node.name)) {
                    for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
                        var element = _a[_i];
                        if (!ts.isOmittedExpression(element)) {
                            hoistBindingElement(element);
                        }
                    }
                }
                else {
                    hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
                }
            }
            /**
             * Determines whether a VariableDeclarationList should be hoisted.
             *
             * @param node The node to test.
             */
            function shouldHoistVariableDeclarationList(node) {
                // hoist only non-block scoped declarations or block scoped declarations parented by source file
                return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
                    && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */
                        || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
            }
            /**
             * Transform an initialized variable declaration into an expression.
             *
             * @param node The node to transform.
             * @param isExportedDeclaration A value indicating whether the variable is exported.
             */
            function transformInitializedVariable(node, isExportedDeclaration) {
                var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
                return ts.isBindingPattern(node.name)
                    ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
                    /*needsValue*/ false, createAssignment)
                    : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
            }
            /**
             * Creates an assignment expression for an exported variable declaration.
             *
             * @param name The name of the variable.
             * @param value The value of the variable's initializer.
             * @param location The source map location for the assignment.
             */
            function createExportedVariableAssignment(name, value, location) {
                return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
            }
            /**
             * Creates an assignment expression for a non-exported variable declaration.
             *
             * @param name The name of the variable.
             * @param value The value of the variable's initializer.
             * @param location The source map location for the assignment.
             */
            function createNonExportedVariableAssignment(name, value, location) {
                return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
            }
            /**
             * Creates an assignment expression for a variable declaration.
             *
             * @param name The name of the variable.
             * @param value The value of the variable's initializer.
             * @param location The source map location for the assignment.
             * @param isExportedDeclaration A value indicating whether the variable is exported.
             */
            function createVariableAssignment(name, value, location, isExportedDeclaration) {
                hoistVariableDeclaration(ts.getSynthesizedClone(name));
                return isExportedDeclaration
                    ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
                    : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
            }
            /**
             * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
             * and transformed declaration.
             *
             * @param node The node to visit.
             */
            function visitMergeDeclarationMarker(node) {
                // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
                // declaration we do not emit a leading variable declaration. To preserve the
                // begin/end semantics of the declararation and to properly handle exports
                // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
                //
                // To balance the declaration, we defer the exports of the elided variable
                // statement until we visit this declaration's `EndOfDeclarationMarker`.
                if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) {
                    var id = ts.getOriginalNodeId(node);
                    var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
                    deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
                }
                return node;
            }
            /**
             * Determines whether a node has an associated EndOfDeclarationMarker.
             *
             * @param node The node to test.
             */
            function hasAssociatedEndOfDeclarationMarker(node) {
                return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
            }
            /**
             * Visits a DeclarationMarker used as a placeholder for the end of a transformed
             * declaration.
             *
             * @param node The node to visit.
             */
            function visitEndOfDeclarationMarker(node) {
                // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
                // end of the transformed declaration. We use this marker to emit any deferred exports
                // of the declaration.
                var id = ts.getOriginalNodeId(node);
                var statements = deferredExports[id];
                if (statements) {
                    delete deferredExports[id];
                    return ts.append(statements, node);
                }
                else {
                    var original = ts.getOriginalNode(node);
                    if (ts.isModuleOrEnumDeclaration(original)) {
                        return ts.append(appendExportsOfDeclaration(statements, original), node);
                    }
                }
                return node;
            }
            /**
             * Appends the exports of an ImportDeclaration to a statement list, returning the
             * statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             */
            function appendExportsOfImportDeclaration(statements, decl) {
                if (moduleInfo.exportEquals) {
                    return statements;
                }
                var importClause = decl.importClause;
                if (!importClause) {
                    return statements;
                }
                if (importClause.name) {
                    statements = appendExportsOfDeclaration(statements, importClause);
                }
                var namedBindings = importClause.namedBindings;
                if (namedBindings) {
                    switch (namedBindings.kind) {
                        case 249 /* NamespaceImport */:
                            statements = appendExportsOfDeclaration(statements, namedBindings);
                            break;
                        case 250 /* NamedImports */:
                            for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
                                var importBinding = _a[_i];
                                statements = appendExportsOfDeclaration(statements, importBinding);
                            }
                            break;
                    }
                }
                return statements;
            }
            /**
             * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
             * statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             */
            function appendExportsOfImportEqualsDeclaration(statements, decl) {
                if (moduleInfo.exportEquals) {
                    return statements;
                }
                return appendExportsOfDeclaration(statements, decl);
            }
            /**
             * Appends the exports of a VariableStatement to a statement list, returning the statement
             * list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param node The VariableStatement whose exports are to be recorded.
             * @param exportSelf A value indicating whether to also export each VariableDeclaration of
             * `nodes` declaration list.
             */
            function appendExportsOfVariableStatement(statements, node, exportSelf) {
                if (moduleInfo.exportEquals) {
                    return statements;
                }
                for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                    var decl = _a[_i];
                    if (decl.initializer || exportSelf) {
                        statements = appendExportsOfBindingElement(statements, decl, exportSelf);
                    }
                }
                return statements;
            }
            /**
             * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
             * returning the statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             * @param exportSelf A value indicating whether to also export the declaration itself.
             */
            function appendExportsOfBindingElement(statements, decl, exportSelf) {
                if (moduleInfo.exportEquals) {
                    return statements;
                }
                if (ts.isBindingPattern(decl.name)) {
                    for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
                        var element = _a[_i];
                        if (!ts.isOmittedExpression(element)) {
                            statements = appendExportsOfBindingElement(statements, element, exportSelf);
                        }
                    }
                }
                else if (!ts.isGeneratedIdentifier(decl.name)) {
                    var excludeName = void 0;
                    if (exportSelf) {
                        statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
                        excludeName = ts.idText(decl.name);
                    }
                    statements = appendExportsOfDeclaration(statements, decl, excludeName);
                }
                return statements;
            }
            /**
             * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
             * returning the statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration whose exports are to be recorded.
             */
            function appendExportsOfHoistedDeclaration(statements, decl) {
                if (moduleInfo.exportEquals) {
                    return statements;
                }
                var excludeName;
                if (ts.hasModifier(decl, 1 /* Export */)) {
                    var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
                    statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
                    excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
                }
                if (decl.name) {
                    statements = appendExportsOfDeclaration(statements, decl, excludeName);
                }
                return statements;
            }
            /**
             * Appends the exports of a declaration to a statement list, returning the statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param decl The declaration to export.
             * @param excludeName An optional name to exclude from exports.
             */
            function appendExportsOfDeclaration(statements, decl, excludeName) {
                if (moduleInfo.exportEquals) {
                    return statements;
                }
                var name = ts.getDeclarationName(decl);
                var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
                if (exportSpecifiers) {
                    for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
                        var exportSpecifier = exportSpecifiers_2[_i];
                        if (exportSpecifier.name.escapedText !== excludeName) {
                            statements = appendExportStatement(statements, exportSpecifier.name, name);
                        }
                    }
                }
                return statements;
            }
            /**
             * Appends the down-level representation of an export to a statement list, returning the
             * statement list.
             *
             * @param statements A statement list to which the down-level export statements are to be
             * appended. If `statements` is `undefined`, a new array is allocated if statements are
             * appended.
             * @param exportName The name of the export.
             * @param expression The expression to export.
             * @param allowComments Whether to allow comments on the export.
             */
            function appendExportStatement(statements, exportName, expression, allowComments) {
                statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
                return statements;
            }
            /**
             * Creates a call to the current file's export function to export a value.
             *
             * @param name The bound name of the export.
             * @param value The exported value.
             * @param allowComments An optional value indicating whether to emit comments for the statement.
             */
            function createExportStatement(name, value, allowComments) {
                var statement = ts.createExpressionStatement(createExportExpression(name, value));
                ts.startOnNewLine(statement);
                if (!allowComments) {
                    ts.setEmitFlags(statement, 1536 /* NoComments */);
                }
                return statement;
            }
            /**
             * Creates a call to the current file's export function to export a value.
             *
             * @param name The bound name of the export.
             * @param value The exported value.
             */
            function createExportExpression(name, value) {
                var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
                ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
                return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
            }
            //
            // Top-Level or Nested Source Element Visitors
            //
            /**
             * Visit nested elements at the top-level of a module.
             *
             * @param node The node to visit.
             */
            function nestedElementVisitor(node) {
                switch (node.kind) {
                    case 217 /* VariableStatement */:
                        return visitVariableStatement(node);
                    case 237 /* FunctionDeclaration */:
                        return visitFunctionDeclaration(node);
                    case 238 /* ClassDeclaration */:
                        return visitClassDeclaration(node);
                    case 223 /* ForStatement */:
                        return visitForStatement(node);
                    case 224 /* ForInStatement */:
                        return visitForInStatement(node);
                    case 225 /* ForOfStatement */:
                        return visitForOfStatement(node);
                    case 221 /* DoStatement */:
                        return visitDoStatement(node);
                    case 222 /* WhileStatement */:
                        return visitWhileStatement(node);
                    case 231 /* LabeledStatement */:
                        return visitLabeledStatement(node);
                    case 229 /* WithStatement */:
                        return visitWithStatement(node);
                    case 230 /* SwitchStatement */:
                        return visitSwitchStatement(node);
                    case 244 /* CaseBlock */:
                        return visitCaseBlock(node);
                    case 269 /* CaseClause */:
                        return visitCaseClause(node);
                    case 270 /* DefaultClause */:
                        return visitDefaultClause(node);
                    case 233 /* TryStatement */:
                        return visitTryStatement(node);
                    case 272 /* CatchClause */:
                        return visitCatchClause(node);
                    case 216 /* Block */:
                        return visitBlock(node);
                    case 308 /* MergeDeclarationMarker */:
                        return visitMergeDeclarationMarker(node);
                    case 309 /* EndOfDeclarationMarker */:
                        return visitEndOfDeclarationMarker(node);
                    default:
                        return destructuringAndImportCallVisitor(node);
                }
            }
            /**
             * Visits the body of a ForStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitForStatement(node) {
                var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
                enclosingBlockScopedContainer = node;
                node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
                enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
                return node;
            }
            /**
             * Visits the body of a ForInStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitForInStatement(node) {
                var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
                enclosingBlockScopedContainer = node;
                node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
                enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
                return node;
            }
            /**
             * Visits the body of a ForOfStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitForOfStatement(node) {
                var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
                enclosingBlockScopedContainer = node;
                node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
                enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
                return node;
            }
            /**
             * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
             * ForOfStatement.
             *
             * @param node The node to test.
             */
            function shouldHoistForInitializer(node) {
                return ts.isVariableDeclarationList(node)
                    && shouldHoistVariableDeclarationList(node);
            }
            /**
             * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
             *
             * @param node The node to visit.
             */
            function visitForInitializer(node) {
                if (shouldHoistForInitializer(node)) {
                    var expressions = void 0;
                    for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
                        var variable = _a[_i];
                        expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
                        if (!variable.initializer) {
                            hoistBindingElement(variable);
                        }
                    }
                    return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
                }
                else {
                    return ts.visitEachChild(node, nestedElementVisitor, context);
                }
            }
            /**
             * Visits the body of a DoStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitDoStatement(node) {
                return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
            }
            /**
             * Visits the body of a WhileStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitWhileStatement(node) {
                return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
            }
            /**
             * Visits the body of a LabeledStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitLabeledStatement(node) {
                return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
            }
            /**
             * Visits the body of a WithStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitWithStatement(node) {
                return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
            }
            /**
             * Visits the body of a SwitchStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitSwitchStatement(node) {
                return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
            }
            /**
             * Visits the body of a CaseBlock to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitCaseBlock(node) {
                var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
                enclosingBlockScopedContainer = node;
                node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
                enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
                return node;
            }
            /**
             * Visits the body of a CaseClause to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitCaseClause(node) {
                return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
            }
            /**
             * Visits the body of a DefaultClause to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitDefaultClause(node) {
                return ts.visitEachChild(node, nestedElementVisitor, context);
            }
            /**
             * Visits the body of a TryStatement to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitTryStatement(node) {
                return ts.visitEachChild(node, nestedElementVisitor, context);
            }
            /**
             * Visits the body of a CatchClause to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitCatchClause(node) {
                var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
                enclosingBlockScopedContainer = node;
                node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
                enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
                return node;
            }
            /**
             * Visits the body of a Block to hoist declarations.
             *
             * @param node The node to visit.
             */
            function visitBlock(node) {
                var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
                enclosingBlockScopedContainer = node;
                node = ts.visitEachChild(node, nestedElementVisitor, context);
                enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
                return node;
            }
            //
            // Destructuring Assignment Visitors
            //
            /**
             * Visit nodes to flatten destructuring assignments to exported symbols.
             *
             * @param node The node to visit.
             */
            function destructuringAndImportCallVisitor(node) {
                if (node.transformFlags & 1024 /* DestructuringAssignment */
                    && node.kind === 202 /* BinaryExpression */) {
                    return visitDestructuringAssignment(node);
                }
                else if (ts.isImportCall(node)) {
                    return visitImportCallExpression(node);
                }
                else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) {
                    return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
                }
                else {
                    return node;
                }
            }
            function visitImportCallExpression(node) {
                // import("./blah")
                // emit as
                // System.register([], function (_export, _context) {
                //     return {
                //         setters: [],
                //         execute: () => {
                //             _context.import('./blah');
                //         }
                //     };
                // });
                return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), 
                /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
            }
            /**
             * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
             *
             * @param node The node to visit.
             */
            function visitDestructuringAssignment(node) {
                if (hasExportedReferenceInDestructuringTarget(node.left)) {
                    return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
                    /*needsValue*/ true);
                }
                return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
            }
            /**
             * Determines whether the target of a destructuring assigment refers to an exported symbol.
             *
             * @param node The destructuring target.
             */
            function hasExportedReferenceInDestructuringTarget(node) {
                if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
                    return hasExportedReferenceInDestructuringTarget(node.left);
                }
                else if (ts.isSpreadElement(node)) {
                    return hasExportedReferenceInDestructuringTarget(node.expression);
                }
                else if (ts.isObjectLiteralExpression(node)) {
                    return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
                }
                else if (ts.isArrayLiteralExpression(node)) {
                    return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
                }
                else if (ts.isShorthandPropertyAssignment(node)) {
                    return hasExportedReferenceInDestructuringTarget(node.name);
                }
                else if (ts.isPropertyAssignment(node)) {
                    return hasExportedReferenceInDestructuringTarget(node.initializer);
                }
                else if (ts.isIdentifier(node)) {
                    var container = resolver.getReferencedExportContainer(node);
                    return container !== undefined && container.kind === 277 /* SourceFile */;
                }
                else {
                    return false;
                }
            }
            //
            // Modifier Visitors
            //
            /**
             * Visit nodes to elide module-specific modifiers.
             *
             * @param node The node to visit.
             */
            function modifierVisitor(node) {
                switch (node.kind) {
                    case 84 /* ExportKeyword */:
                    case 79 /* DefaultKeyword */:
                        return undefined;
                }
                return node;
            }
            //
            // Emit Notification
            //
            /**
             * Hook for node emit notifications.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emitCallback A callback used to emit the node in the printer.
             */
            function onEmitNode(hint, node, emitCallback) {
                if (node.kind === 277 /* SourceFile */) {
                    var id = ts.getOriginalNodeId(node);
                    currentSourceFile = node;
                    moduleInfo = moduleInfoMap[id];
                    exportFunction = exportFunctionsMap[id];
                    noSubstitution = noSubstitutionMap[id];
                    if (noSubstitution) {
                        delete noSubstitutionMap[id];
                    }
                    previousOnEmitNode(hint, node, emitCallback);
                    currentSourceFile = undefined;
                    moduleInfo = undefined;
                    exportFunction = undefined;
                    noSubstitution = undefined;
                }
                else {
                    previousOnEmitNode(hint, node, emitCallback);
                }
            }
            //
            // Substitutions
            //
            /**
             * Hooks node substitutions.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (isSubstitutionPrevented(node)) {
                    return node;
                }
                if (hint === 1 /* Expression */) {
                    return substituteExpression(node);
                }
                else if (hint === 4 /* Unspecified */) {
                    return substituteUnspecified(node);
                }
                return node;
            }
            /**
             * Substitute the node, if necessary.
             *
             * @param node The node to substitute.
             */
            function substituteUnspecified(node) {
                switch (node.kind) {
                    case 274 /* ShorthandPropertyAssignment */:
                        return substituteShorthandPropertyAssignment(node);
                }
                return node;
            }
            /**
             * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteShorthandPropertyAssignment(node) {
                var name = node.name;
                if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
                    var importDeclaration = resolver.getReferencedImportDeclaration(name);
                    if (importDeclaration) {
                        if (ts.isImportClause(importDeclaration)) {
                            return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), 
                            /*location*/ node);
                        }
                        else if (ts.isImportSpecifier(importDeclaration)) {
                            return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), 
                            /*location*/ node);
                        }
                    }
                }
                return node;
            }
            /**
             * Substitute the expression, if necessary.
             *
             * @param node The node to substitute.
             */
            function substituteExpression(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return substituteExpressionIdentifier(node);
                    case 202 /* BinaryExpression */:
                        return substituteBinaryExpression(node);
                    case 200 /* PrefixUnaryExpression */:
                    case 201 /* PostfixUnaryExpression */:
                        return substituteUnaryExpression(node);
                }
                return node;
            }
            /**
             * Substitution for an Identifier expression that may contain an imported or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteExpressionIdentifier(node) {
                if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
                    var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
                    if (externalHelpersModuleName) {
                        return ts.createPropertyAccess(externalHelpersModuleName, node);
                    }
                    return node;
                }
                // When we see an identifier in an expression position that
                // points to an imported symbol, we should substitute a qualified
                // reference to the imported symbol if one is needed.
                //
                // - We do not substitute generated identifiers for any reason.
                // - We do not substitute identifiers tagged with the LocalName flag.
                if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
                    var importDeclaration = resolver.getReferencedImportDeclaration(node);
                    if (importDeclaration) {
                        if (ts.isImportClause(importDeclaration)) {
                            return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
                            /*location*/ node);
                        }
                        else if (ts.isImportSpecifier(importDeclaration)) {
                            return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), 
                            /*location*/ node);
                        }
                    }
                }
                return node;
            }
            /**
             * Substitution for a BinaryExpression that may contain an imported or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteBinaryExpression(node) {
                // When we see an assignment expression whose left-hand side is an exported symbol,
                // we should ensure all exports of that symbol are updated with the correct value.
                //
                // - We do not substitute generated identifiers for any reason.
                // - We do not substitute identifiers tagged with the LocalName flag.
                // - We do not substitute identifiers that were originally the name of an enum or
                //   namespace due to how they are transformed in TypeScript.
                // - We only substitute identifiers that are exported at the top level.
                if (ts.isAssignmentOperator(node.operatorToken.kind)
                    && ts.isIdentifier(node.left)
                    && !ts.isGeneratedIdentifier(node.left)
                    && !ts.isLocalName(node.left)
                    && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
                    var exportedNames = getExports(node.left);
                    if (exportedNames) {
                        // For each additional export of the declaration, apply an export assignment.
                        var expression = node;
                        for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
                            var exportName = exportedNames_4[_i];
                            expression = createExportExpression(exportName, preventSubstitution(expression));
                        }
                        return expression;
                    }
                }
                return node;
            }
            /**
             * Substitution for a UnaryExpression that may contain an imported or exported symbol.
             *
             * @param node The node to substitute.
             */
            function substituteUnaryExpression(node) {
                // When we see a prefix or postfix increment expression whose operand is an exported
                // symbol, we should ensure all exports of that symbol are updated with the correct
                // value.
                //
                // - We do not substitute generated identifiers for any reason.
                // - We do not substitute identifiers tagged with the LocalName flag.
                // - We do not substitute identifiers that were originally the name of an enum or
                //   namespace due to how they are transformed in TypeScript.
                // - We only substitute identifiers that are exported at the top level.
                if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */)
                    && ts.isIdentifier(node.operand)
                    && !ts.isGeneratedIdentifier(node.operand)
                    && !ts.isLocalName(node.operand)
                    && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
                    var exportedNames = getExports(node.operand);
                    if (exportedNames) {
                        var expression = node.kind === 201 /* PostfixUnaryExpression */
                            ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
                            : node;
                        for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
                            var exportName = exportedNames_5[_i];
                            expression = createExportExpression(exportName, preventSubstitution(expression));
                        }
                        if (node.kind === 201 /* PostfixUnaryExpression */) {
                            expression = node.operator === 43 /* PlusPlusToken */
                                ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
                                : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
                        }
                        return expression;
                    }
                }
                return node;
            }
            /**
             * Gets the exports of a name.
             *
             * @param name The name.
             */
            function getExports(name) {
                var exportedNames;
                if (!ts.isGeneratedIdentifier(name)) {
                    var valueDeclaration = resolver.getReferencedImportDeclaration(name)
                        || resolver.getReferencedValueDeclaration(name);
                    if (valueDeclaration) {
                        var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
                        if (exportContainer && exportContainer.kind === 277 /* SourceFile */) {
                            exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
                        }
                        exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
                    }
                }
                return exportedNames;
            }
            /**
             * Prevent substitution of a node for this transformer.
             *
             * @param node The node which should not be substituted.
             */
            function preventSubstitution(node) {
                if (noSubstitution === undefined)
                    noSubstitution = [];
                noSubstitution[ts.getNodeId(node)] = true;
                return node;
            }
            /**
             * Determines whether a node should not be substituted.
             *
             * @param node The node to test.
             */
            function isSubstitutionPrevented(node) {
                return noSubstitution && node.id && noSubstitution[node.id];
            }
        }
        ts.transformSystemModule = transformSystemModule;
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function transformES2015Module(context) {
            var compilerOptions = context.getCompilerOptions();
            var previousOnEmitNode = context.onEmitNode;
            var previousOnSubstituteNode = context.onSubstituteNode;
            context.onEmitNode = onEmitNode;
            context.onSubstituteNode = onSubstituteNode;
            context.enableEmitNotification(277 /* SourceFile */);
            context.enableSubstitution(71 /* Identifier */);
            var currentSourceFile;
            return ts.chainBundle(transformSourceFile);
            function transformSourceFile(node) {
                if (node.isDeclarationFile) {
                    return node;
                }
                if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
                    var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions);
                    if (externalHelpersModuleName) {
                        var statements = [];
                        var statementOffset = ts.addPrologue(statements, node.statements);
                        var tslibImport = ts.createImportDeclaration(
                        /*decorators*/ undefined, 
                        /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText));
                        ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */);
                        ts.append(statements, tslibImport);
                        ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
                        return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
                    }
                    else {
                        return ts.visitEachChild(node, visitor, context);
                    }
                }
                return node;
            }
            function visitor(node) {
                switch (node.kind) {
                    case 246 /* ImportEqualsDeclaration */:
                        // Elide `import=` as it is not legal with --module ES6
                        return undefined;
                    case 252 /* ExportAssignment */:
                        return visitExportAssignment(node);
                }
                return node;
            }
            function visitExportAssignment(node) {
                // Elide `export=` as it is not legal with --module ES6
                return node.isExportEquals ? undefined : node;
            }
            //
            // Emit Notification
            //
            /**
             * Hook for node emit.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emit A callback used to emit the node in the printer.
             */
            function onEmitNode(hint, node, emitCallback) {
                if (ts.isSourceFile(node)) {
                    currentSourceFile = node;
                    previousOnEmitNode(hint, node, emitCallback);
                    currentSourceFile = undefined;
                }
                else {
                    previousOnEmitNode(hint, node, emitCallback);
                }
            }
            //
            // Substitutions
            //
            /**
             * Hooks node substitutions.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to substitute.
             */
            function onSubstituteNode(hint, node) {
                node = previousOnSubstituteNode(hint, node);
                if (ts.isIdentifier(node) && hint === 1 /* Expression */) {
                    return substituteExpressionIdentifier(node);
                }
                return node;
            }
            function substituteExpressionIdentifier(node) {
                if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
                    var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
                    if (externalHelpersModuleName) {
                        return ts.createPropertyAccess(externalHelpersModuleName, node);
                    }
                }
                return node;
            }
        }
        ts.transformES2015Module = transformES2015Module;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function canProduceDiagnostics(node) {
            return ts.isVariableDeclaration(node) ||
                ts.isPropertyDeclaration(node) ||
                ts.isPropertySignature(node) ||
                ts.isBindingElement(node) ||
                ts.isSetAccessor(node) ||
                ts.isGetAccessor(node) ||
                ts.isConstructSignatureDeclaration(node) ||
                ts.isCallSignatureDeclaration(node) ||
                ts.isMethodDeclaration(node) ||
                ts.isMethodSignature(node) ||
                ts.isFunctionDeclaration(node) ||
                ts.isParameter(node) ||
                ts.isTypeParameterDeclaration(node) ||
                ts.isExpressionWithTypeArguments(node) ||
                ts.isImportEqualsDeclaration(node) ||
                ts.isTypeAliasDeclaration(node) ||
                ts.isConstructorDeclaration(node) ||
                ts.isIndexSignatureDeclaration(node);
        }
        ts.canProduceDiagnostics = canProduceDiagnostics;
        function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
            if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
                return getAccessorNameVisibilityError;
            }
            else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
                return getMethodNameVisibilityError;
            }
            else {
                return createGetSymbolAccessibilityDiagnosticForNode(node);
            }
            function getAccessorNameVisibilityError(symbolAccessibilityResult) {
                var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
                return diagnosticMessage !== undefined ? {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node,
                    typeName: node.name
                } : undefined;
            }
            function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
                if (ts.hasModifier(node, 32 /* Static */)) {
                    return symbolAccessibilityResult.errorModuleName ?
                        symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                            ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                            ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
                        ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
                }
                else if (node.parent.kind === 238 /* ClassDeclaration */) {
                    return symbolAccessibilityResult.errorModuleName ?
                        symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                            ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                            ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
                        ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
                }
                else {
                    return symbolAccessibilityResult.errorModuleName ?
                        ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
                        ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
                }
            }
            function getMethodNameVisibilityError(symbolAccessibilityResult) {
                var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
                return diagnosticMessage !== undefined ? {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node,
                    typeName: node.name
                } : undefined;
            }
            function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
                if (ts.hasModifier(node, 32 /* Static */)) {
                    return symbolAccessibilityResult.errorModuleName ?
                        symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                            ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                            ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
                        ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
                }
                else if (node.parent.kind === 238 /* ClassDeclaration */) {
                    return symbolAccessibilityResult.errorModuleName ?
                        symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                            ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                            ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
                        ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
                }
                else {
                    return symbolAccessibilityResult.errorModuleName ?
                        ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
                        ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
                }
            }
        }
        ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
        function createGetSymbolAccessibilityDiagnosticForNode(node) {
            if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
                return getVariableDeclarationTypeVisibilityError;
            }
            else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
                return getAccessorDeclarationTypeVisibilityError;
            }
            else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
                return getReturnTypeVisibilityError;
            }
            else if (ts.isParameter(node)) {
                if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) {
                    return getVariableDeclarationTypeVisibilityError;
                }
                return getParameterDeclarationTypeVisibilityError;
            }
            else if (ts.isTypeParameterDeclaration(node)) {
                return getTypeParameterConstraintVisibilityError;
            }
            else if (ts.isExpressionWithTypeArguments(node)) {
                return getHeritageClauseVisibilityError;
            }
            else if (ts.isImportEqualsDeclaration(node)) {
                return getImportEntityNameVisibilityError;
            }
            else if (ts.isTypeAliasDeclaration(node)) {
                return getTypeAliasDeclarationVisibilityError;
            }
            else {
                return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
            }
            function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
                if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) {
                    return symbolAccessibilityResult.errorModuleName ?
                        symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                            ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                            ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
                        ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
                }
                // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
                // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
                else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ ||
                    (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
                    // TODO(jfreeman): Deal with computed properties in error reporting.
                    if (ts.hasModifier(node, 32 /* Static */)) {
                        return symbolAccessibilityResult.errorModuleName ?
                            symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
                    }
                    else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) {
                        return symbolAccessibilityResult.errorModuleName ?
                            symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
                    }
                    else {
                        // Interfaces cannot have types that cannot be named
                        return symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
                    }
                }
            }
            function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
                var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
                return diagnosticMessage !== undefined ? {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node,
                    typeName: node.name
                } : undefined;
            }
            function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
                var diagnosticMessage;
                if (node.kind === 157 /* SetAccessor */) {
                    // Getters can infer the return type from the returned expression, but setters cannot, so the
                    // "_from_external_module_1_but_cannot_be_named" case cannot occur.
                    if (ts.hasModifier(node, 32 /* Static */)) {
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
                    }
                    else {
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
                    }
                }
                else {
                    if (ts.hasModifier(node, 32 /* Static */)) {
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
                    }
                    else {
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
                    }
                }
                return {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node.name,
                    typeName: node.name
                };
            }
            function getReturnTypeVisibilityError(symbolAccessibilityResult) {
                var diagnosticMessage;
                switch (node.kind) {
                    case 159 /* ConstructSignature */:
                        // Interfaces cannot have return types that cannot be named
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
                            ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
                        break;
                    case 158 /* CallSignature */:
                        // Interfaces cannot have return types that cannot be named
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
                            ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
                        break;
                    case 160 /* IndexSignature */:
                        // Interfaces cannot have return types that cannot be named
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
                            ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
                        break;
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                        if (ts.hasModifier(node, 32 /* Static */)) {
                            diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                                symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                    ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
                                    ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
                                ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
                        }
                        else if (node.parent.kind === 238 /* ClassDeclaration */) {
                            diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                                symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                    ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
                                    ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
                                ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
                        }
                        else {
                            // Interfaces cannot have return types that cannot be named
                            diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                                ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
                                ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
                        }
                        break;
                    case 237 /* FunctionDeclaration */:
                        diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
                            symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
                                ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
                            ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
                        break;
                    default:
                        return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
                }
                return {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node.name || node
                };
            }
            function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
                var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
                return diagnosticMessage !== undefined ? {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node,
                    typeName: node.name
                } : undefined;
            }
            function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
                switch (node.parent.kind) {
                    case 155 /* Constructor */:
                        return symbolAccessibilityResult.errorModuleName ?
                            symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
                    case 159 /* ConstructSignature */:
                    case 164 /* ConstructorType */:
                        // Interfaces cannot have parameter types that cannot be named
                        return symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
                    case 158 /* CallSignature */:
                        // Interfaces cannot have parameter types that cannot be named
                        return symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
                    case 160 /* IndexSignature */:
                        // Interfaces cannot have parameter types that cannot be named
                        return symbolAccessibilityResult.errorModuleName ?
                            ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                        if (ts.hasModifier(node.parent, 32 /* Static */)) {
                            return symbolAccessibilityResult.errorModuleName ?
                                symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                    ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                    ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
                                ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
                        }
                        else if (node.parent.parent.kind === 238 /* ClassDeclaration */) {
                            return symbolAccessibilityResult.errorModuleName ?
                                symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                    ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                    ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
                                ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
                        }
                        else {
                            // Interfaces cannot have parameter types that cannot be named
                            return symbolAccessibilityResult.errorModuleName ?
                                ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
                                ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
                        }
                    case 237 /* FunctionDeclaration */:
                    case 163 /* FunctionType */:
                        return symbolAccessibilityResult.errorModuleName ?
                            symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
                                ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
                                ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
                            ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
                    default:
                        return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
                }
            }
            function getTypeParameterConstraintVisibilityError() {
                // Type parameter constraints are named by user so we should always be able to name it
                var diagnosticMessage;
                switch (node.parent.kind) {
                    case 238 /* ClassDeclaration */:
                        diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
                        break;
                    case 239 /* InterfaceDeclaration */:
                        diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
                        break;
                    case 159 /* ConstructSignature */:
                        diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
                        break;
                    case 158 /* CallSignature */:
                        diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
                        break;
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                        if (ts.hasModifier(node.parent, 32 /* Static */)) {
                            diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
                        }
                        else if (node.parent.parent.kind === 238 /* ClassDeclaration */) {
                            diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
                        }
                        else {
                            diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
                        }
                        break;
                    case 237 /* FunctionDeclaration */:
                        diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
                        break;
                    case 240 /* TypeAliasDeclaration */:
                        diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
                        break;
                    default:
                        return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
                }
                return {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node,
                    typeName: node.name
                };
            }
            function getHeritageClauseVisibilityError() {
                var diagnosticMessage;
                // Heritage clause is written by user so it can always be named
                if (node.parent.parent.kind === 238 /* ClassDeclaration */) {
                    // Class or Interface implemented/extended is inaccessible
                    diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ?
                        ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
                        ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
                }
                else {
                    // interface is inaccessible
                    diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
                }
                return {
                    diagnosticMessage: diagnosticMessage,
                    errorNode: node,
                    typeName: ts.getNameOfDeclaration(node.parent.parent)
                };
            }
            function getImportEntityNameVisibilityError() {
                return {
                    diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
                    errorNode: node,
                    typeName: node.name
                };
            }
            function getTypeAliasDeclarationVisibilityError() {
                return {
                    diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
                    errorNode: node.type,
                    typeName: node.name
                };
            }
        }
        ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function getDeclarationDiagnostics(host, resolver, file) {
            if (file && ts.isSourceFileJS(file)) {
                return []; // No declaration diagnostics for js for now
            }
            var compilerOptions = host.getCompilerOptions();
            var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false);
            return result.diagnostics;
        }
        ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
        var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
            2048 /* WriteClassExpressionAsTypeLiteral */ |
            4096 /* UseTypeOfFunction */ |
            8 /* UseStructuralFallback */ |
            524288 /* AllowEmptyTuple */ |
            4 /* GenerateNamesForShadowedTypeParams */ |
            1 /* NoTruncation */;
        /**
         * Transforms a ts file into a .d.ts file
         * This process requires type information, which is retrieved through the emit resolver. Because of this,
         * in many places this transformer assumes it will be operating on parse tree nodes directly.
         * This means that _no transforms should be allowed to occur before this one_.
         */
        function transformDeclarations(context) {
            var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
            var getSymbolAccessibilityDiagnostic = throwDiagnostic;
            var needsDeclare = true;
            var isBundledEmit = false;
            var resultHasExternalModuleIndicator = false;
            var needsScopeFixMarker = false;
            var resultHasScopeMarker = false;
            var enclosingDeclaration;
            var necessaryTypeReferences;
            var lateMarkedStatements;
            var lateStatementReplacementMap;
            var suppressNewDiagnosticContexts;
            var exportedModulesFromDeclarationEmit;
            var host = context.getEmitHost();
            var symbolTracker = {
                trackSymbol: trackSymbol,
                reportInaccessibleThisError: reportInaccessibleThisError,
                reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
                reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
                moduleResolverHost: host,
                trackReferencedAmbientModule: trackReferencedAmbientModule,
                trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode
            };
            var errorNameNode;
            var currentSourceFile;
            var refs;
            var libs;
            var resolver = context.getEmitResolver();
            var options = context.getCompilerOptions();
            var newLine = ts.getNewLineCharacter(options);
            var noResolve = options.noResolve, stripInternal = options.stripInternal;
            return transformRoot;
            function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
                if (!typeReferenceDirectives) {
                    return;
                }
                necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
                for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
                    var ref = typeReferenceDirectives_2[_i];
                    necessaryTypeReferences.set(ref, true);
                }
            }
            function trackReferencedAmbientModule(node, symbol) {
                // If it is visible via `// <reference types="..."/>`, then we should just use that
                var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
                if (ts.length(directives)) {
                    return recordTypeReferenceDirectivesIfNecessary(directives);
                }
                // Otherwise we should emit a path-based reference
                var container = ts.getSourceFileOfNode(node);
                refs.set("" + ts.getOriginalNodeId(container), container);
            }
            function handleSymbolAccessibilityError(symbolAccessibilityResult) {
                if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
                    // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
                    if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
                        if (!lateMarkedStatements) {
                            lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
                        }
                        else {
                            for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
                                var ref = _a[_i];
                                ts.pushIfUnique(lateMarkedStatements, ref);
                            }
                        }
                    }
                    // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
                }
                else {
                    // Report error
                    var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
                    if (errorInfo) {
                        if (errorInfo.typeName) {
                            context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
                        }
                        else {
                            context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
                        }
                    }
                }
            }
            function trackExternalModuleSymbolOfImportTypeNode(symbol) {
                if (!isBundledEmit) {
                    (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
                }
            }
            function trackSymbol(symbol, enclosingDeclaration, meaning) {
                if (symbol.flags & 262144 /* TypeParameter */)
                    return;
                handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
                recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
            }
            function reportPrivateInBaseOfClassExpression(propertyName) {
                if (errorNameNode) {
                    context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
                }
            }
            function reportInaccessibleUniqueSymbolError() {
                if (errorNameNode) {
                    context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol"));
                }
            }
            function reportInaccessibleThisError() {
                if (errorNameNode) {
                    context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
                }
            }
            function transformRoot(node) {
                if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
                    return node;
                }
                if (node.kind === 278 /* Bundle */) {
                    isBundledEmit = true;
                    refs = ts.createMap();
                    libs = ts.createMap();
                    var hasNoDefaultLib_1 = false;
                    var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
                        if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile))
                            return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
                        hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
                        currentSourceFile = sourceFile;
                        enclosingDeclaration = sourceFile;
                        lateMarkedStatements = undefined;
                        suppressNewDiagnosticContexts = false;
                        lateStatementReplacementMap = ts.createMap();
                        getSymbolAccessibilityDiagnostic = throwDiagnostic;
                        needsScopeFixMarker = false;
                        resultHasScopeMarker = false;
                        collectReferences(sourceFile, refs);
                        collectLibs(sourceFile, libs);
                        if (ts.isExternalModule(sourceFile)) {
                            resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
                            needsDeclare = false;
                            var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
                            var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
                            return newFile;
                        }
                        needsDeclare = true;
                        var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
                        return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
                    }), ts.mapDefined(node.prepends, function (prepend) {
                        if (prepend.kind === 280 /* InputFiles */) {
                            return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText);
                        }
                    }));
                    bundle.syntheticFileReferences = [];
                    bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
                    bundle.syntheticLibReferences = getLibReferences();
                    bundle.hasNoDefaultLib = hasNoDefaultLib_1;
                    var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
                    var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
                    refs.forEach(referenceVisitor_1);
                    return bundle;
                }
                // Single source file
                needsDeclare = true;
                needsScopeFixMarker = false;
                resultHasScopeMarker = false;
                enclosingDeclaration = node;
                currentSourceFile = node;
                getSymbolAccessibilityDiagnostic = throwDiagnostic;
                isBundledEmit = false;
                resultHasExternalModuleIndicator = false;
                suppressNewDiagnosticContexts = false;
                lateMarkedStatements = undefined;
                lateStatementReplacementMap = ts.createMap();
                necessaryTypeReferences = undefined;
                refs = collectReferences(currentSourceFile, ts.createMap());
                libs = collectLibs(currentSourceFile, ts.createMap());
                var references = [];
                var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
                var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
                var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
                var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
                refs.forEach(referenceVisitor);
                var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
                if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
                    combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements);
                }
                var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
                updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
                return updated;
                function getLibReferences() {
                    return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
                }
                function getFileReferencesForUsedTypeReferences() {
                    return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
                }
                function getFileReferenceForTypeName(typeName) {
                    // Elide type references for which we have imports
                    if (emittedImports) {
                        for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
                            var importStatement = emittedImports_1[_i];
                            if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
                                var expr = importStatement.moduleReference.expression;
                                if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
                                    return undefined;
                                }
                            }
                            else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
                                return undefined;
                            }
                        }
                    }
                    return { fileName: typeName, pos: -1, end: -1 };
                }
                function mapReferencesIntoArray(references, outputFilePath) {
                    return function (file) {
                        var declFileName;
                        if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
                            declFileName = file.fileName;
                        }
                        else {
                            if (isBundledEmit && ts.contains(node.sourceFiles, file))
                                return; // Omit references to files which are being merged
                            var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
                            declFileName = paths.declarationFilePath || paths.jsFilePath;
                        }
                        if (declFileName) {
                            var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
                            /*isAbsolutePathAnUrl*/ false);
                            if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
                                fileName = fileName.substring(2);
                            }
                            // omit references to files from node_modules (npm may disambiguate module
                            // references when installing this package, making the path is unreliable).
                            if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) {
                                return;
                            }
                            references.push({ pos: -1, end: -1, fileName: fileName });
                        }
                    };
                }
            }
            function collectReferences(sourceFile, ret) {
                if (noResolve || ts.isSourceFileJS(sourceFile))
                    return ret;
                ts.forEach(sourceFile.referencedFiles, function (f) {
                    var elem = ts.tryResolveScriptReference(host, sourceFile, f);
                    if (elem) {
                        ret.set("" + ts.getOriginalNodeId(elem), elem);
                    }
                });
                return ret;
            }
            function collectLibs(sourceFile, ret) {
                ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
                    var lib = host.getLibFileFromReference(ref);
                    if (lib) {
                        ret.set(ref.fileName.toLocaleLowerCase(), true);
                    }
                });
                return ret;
            }
            function filterBindingPatternInitializers(name) {
                if (name.kind === 71 /* Identifier */) {
                    return name;
                }
                else {
                    if (name.kind === 183 /* ArrayBindingPattern */) {
                        return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
                    }
                    else {
                        return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
                    }
                }
                function visitBindingElement(elem) {
                    if (elem.kind === 208 /* OmittedExpression */) {
                        return elem;
                    }
                    return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
                }
            }
            function ensureParameter(p, modifierMask) {
                var oldDiag;
                if (!suppressNewDiagnosticContexts) {
                    oldDiag = getSymbolAccessibilityDiagnostic;
                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
                }
                var newParam = ts.updateParameter(p, 
                /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param
                ensureNoInitializer(p));
                if (!suppressNewDiagnosticContexts) {
                    getSymbolAccessibilityDiagnostic = oldDiag;
                }
                return newParam;
            }
            function shouldPrintWithInitializer(node) {
                return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
            }
            function ensureNoInitializer(node) {
                if (shouldPrintWithInitializer(node)) {
                    return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe
                }
                return undefined;
            }
            function ensureType(node, type, ignorePrivate) {
                if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
                    // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
                    return;
                }
                if (shouldPrintWithInitializer(node)) {
                    // Literal const declarations will have an initializer ensured rather than a type
                    return;
                }
                var shouldUseResolverType = node.kind === 149 /* Parameter */ &&
                    (resolver.isRequiredInitializedParameter(node) ||
                        resolver.isOptionalUninitializedParameterProperty(node));
                if (type && !shouldUseResolverType) {
                    return ts.visitNode(type, visitDeclarationSubtree);
                }
                if (!ts.getParseTreeNode(node)) {
                    return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */);
                }
                if (node.kind === 157 /* SetAccessor */) {
                    // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now
                    // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
                    return ts.createKeywordTypeNode(119 /* AnyKeyword */);
                }
                errorNameNode = node.name;
                var oldDiag;
                if (!suppressNewDiagnosticContexts) {
                    oldDiag = getSymbolAccessibilityDiagnostic;
                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
                }
                if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) {
                    return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
                }
                if (node.kind === 149 /* Parameter */
                    || node.kind === 152 /* PropertyDeclaration */
                    || node.kind === 151 /* PropertySignature */) {
                    if (!node.initializer)
                        return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
                    return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
                }
                return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
                function cleanup(returnValue) {
                    errorNameNode = undefined;
                    if (!suppressNewDiagnosticContexts) {
                        getSymbolAccessibilityDiagnostic = oldDiag;
                    }
                    return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */);
                }
            }
            function isDeclarationAndNotVisible(node) {
                node = ts.getParseTreeNode(node);
                switch (node.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 242 /* ModuleDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 241 /* EnumDeclaration */:
                        return !resolver.isDeclarationVisible(node);
                    // The following should be doing their own visibility checks based on filtering their members
                    case 235 /* VariableDeclaration */:
                        return !getBindingNameVisible(node);
                    case 246 /* ImportEqualsDeclaration */:
                    case 247 /* ImportDeclaration */:
                    case 253 /* ExportDeclaration */:
                    case 252 /* ExportAssignment */:
                        return false;
                }
                return false;
            }
            function getBindingNameVisible(elem) {
                if (ts.isOmittedExpression(elem)) {
                    return false;
                }
                if (ts.isBindingPattern(elem.name)) {
                    // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
                    return ts.some(elem.name.elements, getBindingNameVisible);
                }
                else {
                    return resolver.isDeclarationVisible(elem);
                }
            }
            function updateParamsList(node, params, modifierMask) {
                if (ts.hasModifier(node, 8 /* Private */)) {
                    return undefined; // TODO: GH#18217
                }
                var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
                if (!newParams) {
                    return undefined; // TODO: GH#18217
                }
                return ts.createNodeArray(newParams, params.hasTrailingComma);
            }
            function ensureTypeParams(node, params) {
                return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
            }
            function isEnclosingDeclaration(node) {
                return ts.isSourceFile(node)
                    || ts.isTypeAliasDeclaration(node)
                    || ts.isModuleDeclaration(node)
                    || ts.isClassDeclaration(node)
                    || ts.isInterfaceDeclaration(node)
                    || ts.isFunctionLike(node)
                    || ts.isIndexSignatureDeclaration(node)
                    || ts.isMappedTypeNode(node);
            }
            function checkEntityNameVisibility(entityName, enclosingDeclaration) {
                var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
                handleSymbolAccessibilityError(visibilityResult);
                recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
            }
            function preserveJsDoc(updated, original) {
                if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
                    updated.jsDoc = original.jsDoc;
                }
                return ts.setCommentRange(updated, ts.getCommentRange(original));
            }
            function rewriteModuleSpecifier(parent, input) {
                if (!input)
                    return undefined; // TODO: GH#18217
                resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */);
                if (ts.isStringLiteralLike(input)) {
                    if (isBundledEmit) {
                        var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
                        if (newName) {
                            return ts.createLiteral(newName);
                        }
                    }
                    else {
                        var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
                        if (symbol) {
                            (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
                        }
                    }
                }
                return input;
            }
            function transformImportEqualsDeclaration(decl) {
                if (!resolver.isDeclarationVisible(decl))
                    return;
                if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) {
                    // Rewrite external module names if necessary
                    var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
                    return ts.updateImportEqualsDeclaration(decl, 
                    /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
                }
                else {
                    var oldDiag = getSymbolAccessibilityDiagnostic;
                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
                    checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
                    getSymbolAccessibilityDiagnostic = oldDiag;
                    return decl;
                }
            }
            function transformImportDeclaration(decl) {
                if (!decl.importClause) {
                    // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
                    return ts.updateImportDeclaration(decl, 
                    /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
                }
                // The `importClause` visibility corresponds to the default's visibility.
                var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
                if (!decl.importClause.namedBindings) {
                    // No named bindings (either namespace or list), meaning the import is just default or should be elided
                    return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, 
                    /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
                }
                if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) {
                    // Namespace import (optionally with visible default)
                    var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
                    return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
                }
                // Named imports (optionally with visible default)
                var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
                if ((bindingList && bindingList.length) || visibleDefaultBinding) {
                    return ts.updateImportDeclaration(decl, 
                    /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
                }
                // Nothing visible
            }
            function transformAndReplaceLatePaintedStatements(statements) {
                // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
                // error handling which must now be included in the output and themselves checked for errors.
                // For example:
                // ```
                // module A {
                //   export module Q {}
                //   import B = Q;
                //   import C = B;
                //   export import D = C;
                // }
                // ```
                // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
                // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
                // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
                while (ts.length(lateMarkedStatements)) {
                    var i = lateMarkedStatements.shift();
                    if (!ts.isLateVisibilityPaintedStatement(i)) {
                        return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
                    }
                    var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true);
                    lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
                }
                // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
                // (and remove them from the set to examine for outter declarations)
                return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
                function visitLateVisibilityMarkedStatements(statement) {
                    if (ts.isLateVisibilityPaintedStatement(statement)) {
                        var key = "" + ts.getOriginalNodeId(statement);
                        if (lateStatementReplacementMap.has(key)) {
                            var result = lateStatementReplacementMap.get(key);
                            lateStatementReplacementMap.delete(key);
                            if (result && ts.isSourceFile(statement.parent)) {
                                if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) {
                                    // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
                                    needsScopeFixMarker = true;
                                }
                                if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) {
                                    resultHasExternalModuleIndicator = true;
                                }
                            }
                            return result;
                        }
                    }
                    return statement;
                }
            }
            function isExternalModuleIndicator(result) {
                // Exported top-level member indicates moduleness
                return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
            }
            function needsScopeMarker(result) {
                return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
            }
            function visitDeclarationSubtree(input) {
                if (shouldStripInternal(input))
                    return;
                if (ts.isDeclaration(input)) {
                    if (isDeclarationAndNotVisible(input))
                        return;
                    if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
                        return;
                    }
                }
                // Elide implementation signatures from overload sets
                if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
                    return;
                // Elide semicolon class statements
                if (ts.isSemicolonClassElement(input))
                    return;
                var previousEnclosingDeclaration;
                if (isEnclosingDeclaration(input)) {
                    previousEnclosingDeclaration = enclosingDeclaration;
                    enclosingDeclaration = input;
                }
                var oldDiag = getSymbolAccessibilityDiagnostic;
                // Emit methods which are private as properties with no type information
                if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
                    if (ts.hasModifier(input, 8 /* Private */)) {
                        if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
                            return; // Elide all but the first overload
                        return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
                    }
                }
                var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
                if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) {
                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
                }
                if (ts.isTypeQueryNode(input)) {
                    checkEntityNameVisibility(input.exprName, enclosingDeclaration);
                }
                var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
                var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */);
                if (shouldEnterSuppressNewDiagnosticsContextContext) {
                    // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do.
                    suppressNewDiagnosticContexts = true;
                }
                if (isProcessedComponent(input)) {
                    switch (input.kind) {
                        case 209 /* ExpressionWithTypeArguments */: {
                            if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
                                checkEntityNameVisibility(input.expression, enclosingDeclaration);
                            }
                            var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
                            return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
                        }
                        case 162 /* TypeReference */: {
                            checkEntityNameVisibility(input.typeName, enclosingDeclaration);
                            var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
                            return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
                        }
                        case 159 /* ConstructSignature */:
                            return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
                        case 155 /* Constructor */: {
                            var isPrivate = ts.hasModifier(input, 8 /* Private */);
                            // A constructor declaration may not have a type annotation
                            var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), 
                            // TODO: GH#18217
                            isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), 
                            /*type*/ undefined);
                            ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
                            return cleanup(ctor);
                        }
                        case 154 /* MethodDeclaration */: {
                            var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
                            sig.name = input.name;
                            sig.modifiers = ts.createNodeArray(ensureModifiers(input));
                            sig.questionToken = input.questionToken;
                            return cleanup(sig);
                        }
                        case 156 /* GetAccessor */: {
                            var newNode = ensureAccessor(input);
                            return cleanup(newNode);
                        }
                        case 157 /* SetAccessor */: {
                            var newNode = ensureAccessor(input);
                            return cleanup(newNode);
                        }
                        case 152 /* PropertyDeclaration */:
                            return cleanup(ts.updateProperty(input, 
                            /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input)));
                        case 151 /* PropertySignature */:
                            return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input)));
                        case 153 /* MethodSignature */: {
                            return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
                        }
                        case 158 /* CallSignature */: {
                            return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
                        }
                        case 160 /* IndexSignature */: {
                            return cleanup(ts.updateIndexSignature(input, 
                            /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */)));
                        }
                        case 235 /* VariableDeclaration */: {
                            if (ts.isBindingPattern(input.name)) {
                                return recreateBindingPattern(input.name);
                            }
                            shouldEnterSuppressNewDiagnosticsContextContext = true;
                            suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
                            return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input)));
                        }
                        case 148 /* TypeParameter */: {
                            if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
                                return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
                            }
                            return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
                        }
                        case 173 /* ConditionalType */: {
                            // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
                            // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
                            var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
                            var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
                            var oldEnclosingDecl = enclosingDeclaration;
                            enclosingDeclaration = input.trueType;
                            var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
                            enclosingDeclaration = oldEnclosingDecl;
                            var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
                            return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
                        }
                        case 163 /* FunctionType */: {
                            return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
                        }
                        case 164 /* ConstructorType */: {
                            return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
                        }
                        case 181 /* ImportType */: {
                            if (!ts.isLiteralImportTypeNode(input))
                                return cleanup(input);
                            return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf));
                        }
                        default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
                    }
                }
                return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
                function cleanup(returnValue) {
                    if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) {
                        checkName(input);
                    }
                    if (isEnclosingDeclaration(input)) {
                        enclosingDeclaration = previousEnclosingDeclaration;
                    }
                    if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) {
                        getSymbolAccessibilityDiagnostic = oldDiag;
                    }
                    if (shouldEnterSuppressNewDiagnosticsContextContext) {
                        suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
                    }
                    if (returnValue === input) {
                        return returnValue;
                    }
                    return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
                }
            }
            function isPrivateMethodTypeParameter(node) {
                return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
            }
            function visitDeclarationStatements(input) {
                if (!isPreservedDeclarationStatement(input)) {
                    // return undefined for unmatched kinds to omit them from the tree
                    return;
                }
                if (shouldStripInternal(input))
                    return;
                switch (input.kind) {
                    case 253 /* ExportDeclaration */: {
                        if (ts.isSourceFile(input.parent)) {
                            resultHasExternalModuleIndicator = true;
                            resultHasScopeMarker = true;
                        }
                        // Always visible if the parent node isn't dropped for being not visible
                        // Rewrite external module names if necessary
                        return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier));
                    }
                    case 252 /* ExportAssignment */: {
                        // Always visible if the parent node isn't dropped for being not visible
                        if (ts.isSourceFile(input.parent)) {
                            resultHasExternalModuleIndicator = true;
                            resultHasScopeMarker = true;
                        }
                        if (input.expression.kind === 71 /* Identifier */) {
                            return input;
                        }
                        else {
                            var newId = ts.createOptimisticUniqueName("_default");
                            getSymbolAccessibilityDiagnostic = function () {
                                return ({
                                    diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
                                    errorNode: input
                                });
                            };
                            var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
                            var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
                            return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
                        }
                    }
                }
                var result = transformTopLevelDeclaration(input);
                // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
                lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
                return input;
            }
            function transformTopLevelDeclaration(input, isPrivate) {
                if (shouldStripInternal(input))
                    return;
                switch (input.kind) {
                    case 246 /* ImportEqualsDeclaration */: {
                        return transformImportEqualsDeclaration(input);
                    }
                    case 247 /* ImportDeclaration */: {
                        return transformImportDeclaration(input);
                    }
                }
                if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
                    return;
                // Elide implementation signatures from overload sets
                if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
                    return;
                var previousEnclosingDeclaration;
                if (isEnclosingDeclaration(input)) {
                    previousEnclosingDeclaration = enclosingDeclaration;
                    enclosingDeclaration = input;
                }
                var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
                var oldDiag = getSymbolAccessibilityDiagnostic;
                if (canProdiceDiagnostic) {
                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
                }
                var previousNeedsDeclare = needsDeclare;
                switch (input.kind) {
                    case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
                        return cleanup(ts.updateTypeAliasDeclaration(input, 
                        /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
                    case 239 /* InterfaceDeclaration */: {
                        return cleanup(ts.updateInterfaceDeclaration(input, 
                        /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
                    }
                    case 237 /* FunctionDeclaration */: {
                        // Generators lose their generator-ness, excepting their return type
                        var clean = cleanup(ts.updateFunctionDeclaration(input, 
                        /*decorators*/ undefined, ensureModifiers(input, isPrivate), 
                        /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
                        /*body*/ undefined));
                        if (clean && resolver.isExpandoFunctionDeclaration(input)) {
                            var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) {
                                if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
                                    return undefined;
                                }
                                var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
                                var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
                                return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
                            });
                            var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
                            return [clean, namespaceDecl];
                        }
                        else {
                            return clean;
                        }
                    }
                    case 242 /* ModuleDeclaration */: {
                        needsDeclare = false;
                        var inner = input.body;
                        if (inner && inner.kind === 243 /* ModuleBlock */) {
                            var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
                            var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements));
                            needsDeclare = previousNeedsDeclare;
                            var mods = ensureModifiers(input, isPrivate);
                            return cleanup(ts.updateModuleDeclaration(input, 
                            /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
                        }
                        else {
                            needsDeclare = previousNeedsDeclare;
                            var mods = ensureModifiers(input, isPrivate);
                            needsDeclare = false;
                            ts.visitNode(inner, visitDeclarationStatements);
                            // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
                            var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
                            var body = lateStatementReplacementMap.get(id);
                            lateStatementReplacementMap.delete(id);
                            return cleanup(ts.updateModuleDeclaration(input, 
                            /*decorators*/ undefined, mods, input.name, body));
                        }
                    }
                    case 238 /* ClassDeclaration */: {
                        var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate));
                        var typeParameters = ensureTypeParams(input, input.typeParameters);
                        var ctor = ts.getFirstConstructorWithBody(input);
                        var parameterProperties = void 0;
                        if (ctor) {
                            var oldDiag_1 = getSymbolAccessibilityDiagnostic;
                            parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
                                if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */))
                                    return;
                                getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
                                if (param.name.kind === 71 /* Identifier */) {
                                    return preserveJsDoc(ts.createProperty(
                                    /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
                                }
                                else {
                                    // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
                                    return walkBindingPattern(param.name);
                                }
                                function walkBindingPattern(pattern) {
                                    var elems;
                                    for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
                                        var elem = _a[_i];
                                        if (ts.isOmittedExpression(elem))
                                            continue;
                                        if (ts.isBindingPattern(elem.name)) {
                                            elems = ts.concatenate(elems, walkBindingPattern(elem.name));
                                        }
                                        elems = elems || [];
                                        elems.push(ts.createProperty(
                                        /*decorators*/ undefined, ensureModifiers(param), elem.name, 
                                        /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
                                        /*initializer*/ undefined));
                                    }
                                    return elems;
                                }
                            }));
                            getSymbolAccessibilityDiagnostic = oldDiag_1;
                        }
                        var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree)));
                        var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
                        if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) {
                            // We must add a temporary declaration for the extends clause expression
                            var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217
                            getSymbolAccessibilityDiagnostic = function () {
                                return ({
                                    diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
                                    errorNode: extendsClause_1,
                                    typeName: input.name
                                });
                            };
                            var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
                            var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
                            var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
                                if (clause.token === 85 /* ExtendsKeyword */) {
                                    var oldDiag_2 = getSymbolAccessibilityDiagnostic;
                                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
                                    var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
                                    getSymbolAccessibilityDiagnostic = oldDiag_2;
                                    return newClause;
                                }
                                return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree));
                            }));
                            return [statement, cleanup(ts.updateClassDeclaration(input, 
                                /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
                        }
                        else {
                            var heritageClauses = transformHeritageClauses(input.heritageClauses);
                            return cleanup(ts.updateClassDeclaration(input, 
                            /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
                        }
                    }
                    case 217 /* VariableStatement */: {
                        return cleanup(transformVariableStatement(input, isPrivate));
                    }
                    case 241 /* EnumDeclaration */: {
                        return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
                            if (shouldStripInternal(m))
                                return;
                            // Rewrite enum values to their constants, if available
                            var constValue = resolver.getConstantValue(m);
                            return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
                        }))));
                    }
                }
                // Anything left unhandled is an error, so this should be unreachable
                return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
                function cleanup(node) {
                    if (isEnclosingDeclaration(input)) {
                        enclosingDeclaration = previousEnclosingDeclaration;
                    }
                    if (canProdiceDiagnostic) {
                        getSymbolAccessibilityDiagnostic = oldDiag;
                    }
                    if (input.kind === 242 /* ModuleDeclaration */) {
                        needsDeclare = previousNeedsDeclare;
                    }
                    if (node === input) {
                        return node;
                    }
                    return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
                }
            }
            function transformVariableStatement(input, privateDeclaration) {
                if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
                    return;
                var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
                if (!ts.length(nodes))
                    return;
                return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes));
            }
            function recreateBindingPattern(d) {
                return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
            }
            function recreateBindingElement(e) {
                if (e.kind === 208 /* OmittedExpression */) {
                    return;
                }
                if (e.name) {
                    if (!getBindingNameVisible(e))
                        return;
                    if (ts.isBindingPattern(e.name)) {
                        return recreateBindingPattern(e.name);
                    }
                    else {
                        return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
                    }
                }
            }
            function checkName(node) {
                var oldDiag;
                if (!suppressNewDiagnosticContexts) {
                    oldDiag = getSymbolAccessibilityDiagnostic;
                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
                }
                errorNameNode = node.name;
                ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
                var decl = node;
                var entityName = decl.name.expression;
                checkEntityNameVisibility(entityName, enclosingDeclaration);
                if (!suppressNewDiagnosticContexts) {
                    getSymbolAccessibilityDiagnostic = oldDiag;
                }
                errorNameNode = undefined;
            }
            function hasInternalAnnotation(range) {
                var comment = currentSourceFile.text.substring(range.pos, range.end);
                return ts.stringContains(comment, "@internal");
            }
            function shouldStripInternal(node) {
                if (stripInternal && node) {
                    var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
                    if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
                        return true;
                    }
                }
                return false;
            }
            function isScopeMarker(node) {
                return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
            }
            function hasScopeMarker(node) {
                if (ts.isModuleBlock(node)) {
                    return ts.some(node.statements, isScopeMarker);
                }
                return false;
            }
            function ensureModifiers(node, privateDeclaration) {
                var currentFlags = ts.getModifierFlags(node);
                var newFlags = ensureModifierFlags(node, privateDeclaration);
                if (currentFlags === newFlags) {
                    return node.modifiers;
                }
                return ts.createModifiersFromModifierFlags(newFlags);
            }
            function ensureModifierFlags(node, privateDeclaration) {
                var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
                var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
                var parentIsFile = node.parent.kind === 277 /* SourceFile */;
                if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
                    mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
                    additions = 0 /* None */;
                }
                return maskModifierFlags(node, mask, additions);
            }
            function ensureAccessor(node) {
                var accessors = resolver.getAllAccessorDeclarations(node);
                if (node.kind !== accessors.firstAccessor.kind) {
                    return;
                }
                var accessorType = getTypeAnnotationFromAccessor(node);
                if (!accessorType && accessors.secondAccessor) {
                    accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
                    // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message
                    getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
                }
                var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined);
                var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile);
                if (leadingsSyntheticCommentRanges) {
                    var _loop_8 = function (range) {
                        if (range.kind === 3 /* MultiLineCommentTrivia */) {
                            var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2);
                            var lines = text.split(/\r\n?|\n/g);
                            if (lines.length > 1) {
                                var lastLines = lines.slice(1);
                                var indentation_1 = ts.guessIndentation(lastLines);
                                text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine);
                            }
                            ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine);
                        }
                    };
                    for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) {
                        var range = leadingsSyntheticCommentRanges_1[_i];
                        _loop_8(range);
                    }
                }
                return prop;
            }
            function transformHeritageClauses(nodes) {
                return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) {
                    return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
                        return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */);
                    })), visitDeclarationSubtree));
                }), function (clause) { return clause.types && !!clause.types.length; }));
            }
        }
        ts.transformDeclarations = transformDeclarations;
        function isAlwaysType(node) {
            if (node.kind === 239 /* InterfaceDeclaration */) {
                return true;
            }
            return false;
        }
        // Elide "public" modifier, as it is the default
        function maskModifiers(node, modifierMask, modifierAdditions) {
            return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
        }
        function maskModifierFlags(node, modifierMask, modifierAdditions) {
            if (modifierMask === void 0) {
                modifierMask = 3071 /* All */ ^ 4 /* Public */;
            }
            if (modifierAdditions === void 0) {
                modifierAdditions = 0 /* None */;
            }
            var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
            if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
                // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
                // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
                flags ^= 1 /* Export */;
            }
            if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
                flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
            }
            return flags;
        }
        function getTypeAnnotationFromAccessor(accessor) {
            if (accessor) {
                return accessor.kind === 156 /* GetAccessor */
                    ? accessor.type // Getter - return type
                    : accessor.parameters.length > 0
                        ? accessor.parameters[0].type // Setter parameter type
                        : undefined;
            }
        }
        function canHaveLiteralInitializer(node) {
            switch (node.kind) {
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                    return !ts.hasModifier(node, 8 /* Private */);
                case 149 /* Parameter */:
                case 235 /* VariableDeclaration */:
                    return true;
            }
            return false;
        }
        function isPreservedDeclarationStatement(node) {
            switch (node.kind) {
                case 237 /* FunctionDeclaration */:
                case 242 /* ModuleDeclaration */:
                case 246 /* ImportEqualsDeclaration */:
                case 239 /* InterfaceDeclaration */:
                case 238 /* ClassDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                case 241 /* EnumDeclaration */:
                case 217 /* VariableStatement */:
                case 247 /* ImportDeclaration */:
                case 253 /* ExportDeclaration */:
                case 252 /* ExportAssignment */:
                    return true;
            }
            return false;
        }
        function isProcessedComponent(node) {
            switch (node.kind) {
                case 159 /* ConstructSignature */:
                case 155 /* Constructor */:
                case 154 /* MethodDeclaration */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                case 153 /* MethodSignature */:
                case 158 /* CallSignature */:
                case 160 /* IndexSignature */:
                case 235 /* VariableDeclaration */:
                case 148 /* TypeParameter */:
                case 209 /* ExpressionWithTypeArguments */:
                case 162 /* TypeReference */:
                case 173 /* ConditionalType */:
                case 163 /* FunctionType */:
                case 164 /* ConstructorType */:
                case 181 /* ImportType */:
                    return true;
            }
            return false;
        }
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function getModuleTransformer(moduleKind) {
            switch (moduleKind) {
                case ts.ModuleKind.ESNext:
                case ts.ModuleKind.ES2015:
                    return ts.transformES2015Module;
                case ts.ModuleKind.System:
                    return ts.transformSystemModule;
                default:
                    return ts.transformModule;
            }
        }
        var TransformationState;
        (function (TransformationState) {
            TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
            TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
            TransformationState[TransformationState["Completed"] = 2] = "Completed";
            TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
        })(TransformationState || (TransformationState = {}));
        var SyntaxKindFeatureFlags;
        (function (SyntaxKindFeatureFlags) {
            SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
            SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
        })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
        function getTransformers(compilerOptions, customTransformers) {
            var jsx = compilerOptions.jsx;
            var languageVersion = ts.getEmitScriptTarget(compilerOptions);
            var moduleKind = ts.getEmitModuleKind(compilerOptions);
            var transformers = [];
            ts.addRange(transformers, customTransformers && customTransformers.before);
            transformers.push(ts.transformTypeScript);
            if (jsx === 2 /* React */) {
                transformers.push(ts.transformJsx);
            }
            if (languageVersion < 6 /* ESNext */) {
                transformers.push(ts.transformESNext);
            }
            if (languageVersion < 4 /* ES2017 */) {
                transformers.push(ts.transformES2017);
            }
            if (languageVersion < 3 /* ES2016 */) {
                transformers.push(ts.transformES2016);
            }
            if (languageVersion < 2 /* ES2015 */) {
                transformers.push(ts.transformES2015);
                transformers.push(ts.transformGenerators);
            }
            transformers.push(getModuleTransformer(moduleKind));
            // The ES5 transformer is last so that it can substitute expressions like `exports.default`
            // for ES3.
            if (languageVersion < 1 /* ES5 */) {
                transformers.push(ts.transformES5);
            }
            ts.addRange(transformers, customTransformers && customTransformers.after);
            return transformers;
        }
        ts.getTransformers = getTransformers;
        /**
         * Transforms an array of SourceFiles by passing them through each transformer.
         *
         * @param resolver The emit resolver provided by the checker.
         * @param host The emit host object used to interact with the file system.
         * @param options Compiler options to surface in the `TransformationContext`.
         * @param nodes An array of nodes to transform.
         * @param transforms An array of `TransformerFactory` callbacks.
         * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
         */
        function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
            var enabledSyntaxKindFeatures = new Array(310 /* Count */);
            var lexicalEnvironmentVariableDeclarations;
            var lexicalEnvironmentFunctionDeclarations;
            var lexicalEnvironmentVariableDeclarationsStack = [];
            var lexicalEnvironmentFunctionDeclarationsStack = [];
            var lexicalEnvironmentStackOffset = 0;
            var lexicalEnvironmentSuspended = false;
            var emitHelpers;
            var onSubstituteNode = function (_, node) { return node; };
            var onEmitNode = function (hint, node, callback) { return callback(hint, node); };
            var state = 0 /* Uninitialized */;
            var diagnostics = [];
            // The transformation context is provided to each transformer as part of transformer
            // initialization.
            var context = {
                getCompilerOptions: function () { return options; },
                getEmitResolver: function () { return resolver; },
                getEmitHost: function () { return host; },
                startLexicalEnvironment: startLexicalEnvironment,
                suspendLexicalEnvironment: suspendLexicalEnvironment,
                resumeLexicalEnvironment: resumeLexicalEnvironment,
                endLexicalEnvironment: endLexicalEnvironment,
                hoistVariableDeclaration: hoistVariableDeclaration,
                hoistFunctionDeclaration: hoistFunctionDeclaration,
                requestEmitHelper: requestEmitHelper,
                readEmitHelpers: readEmitHelpers,
                enableSubstitution: enableSubstitution,
                enableEmitNotification: enableEmitNotification,
                isSubstitutionEnabled: isSubstitutionEnabled,
                isEmitNotificationEnabled: isEmitNotificationEnabled,
                get onSubstituteNode() { return onSubstituteNode; },
                set onSubstituteNode(value) {
                    ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
                    ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
                    onSubstituteNode = value;
                },
                get onEmitNode() { return onEmitNode; },
                set onEmitNode(value) {
                    ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
                    ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
                    onEmitNode = value;
                },
                addDiagnostic: function (diag) {
                    diagnostics.push(diag);
                }
            };
            // Ensure the parse tree is clean before applying transformations
            for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
                var node = nodes_4[_i];
                ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
            }
            ts.performance.mark("beforeTransform");
            // Chain together and initialize each transformer.
            var transformation = ts.chain.apply(void 0, transformers)(context);
            // prevent modification of transformation hooks.
            state = 1 /* Initialized */;
            // Transform each node.
            var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
            // prevent modification of the lexical environment.
            state = 2 /* Completed */;
            ts.performance.mark("afterTransform");
            ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
            return {
                transformed: transformed,
                substituteNode: substituteNode,
                emitNodeWithNotification: emitNodeWithNotification,
                dispose: dispose,
                diagnostics: diagnostics
            };
            function transformRoot(node) {
                return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
            }
            /**
             * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
             */
            function enableSubstitution(kind) {
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
                enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
            }
            /**
             * Determines whether expression substitutions are enabled for the provided node.
             */
            function isSubstitutionEnabled(node) {
                return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
                    && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
            }
            /**
             * Emits a node with possible substitution.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emitCallback The callback used to emit the node or its substitute.
             */
            function substituteNode(hint, node) {
                ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
                return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
            }
            /**
             * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
             */
            function enableEmitNotification(kind) {
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
                enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
            }
            /**
             * Determines whether before/after emit notifications should be raised in the pretty
             * printer when it emits a node.
             */
            function isEmitNotificationEnabled(node) {
                return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
                    || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
            }
            /**
             * Emits a node with possible emit notification.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emitCallback The callback used to emit the node.
             */
            function emitNodeWithNotification(hint, node, emitCallback) {
                ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
                if (node) {
                    if (isEmitNotificationEnabled(node)) {
                        onEmitNode(hint, node, emitCallback);
                    }
                    else {
                        emitCallback(hint, node);
                    }
                }
            }
            /**
             * Records a hoisted variable declaration for the provided name within a lexical environment.
             */
            function hoistVariableDeclaration(name) {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
                var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
                if (!lexicalEnvironmentVariableDeclarations) {
                    lexicalEnvironmentVariableDeclarations = [decl];
                }
                else {
                    lexicalEnvironmentVariableDeclarations.push(decl);
                }
            }
            /**
             * Records a hoisted function declaration within a lexical environment.
             */
            function hoistFunctionDeclaration(func) {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
                if (!lexicalEnvironmentFunctionDeclarations) {
                    lexicalEnvironmentFunctionDeclarations = [func];
                }
                else {
                    lexicalEnvironmentFunctionDeclarations.push(func);
                }
            }
            /**
             * Starts a new lexical environment. Any existing hoisted variable or function declarations
             * are pushed onto a stack, and the related storage variables are reset.
             */
            function startLexicalEnvironment() {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
                ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
                // Save the current lexical environment. Rather than resizing the array we adjust the
                // stack size variable. This allows us to reuse existing array slots we've
                // already allocated between transformations to avoid allocation and GC overhead during
                // transformation.
                lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
                lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
                lexicalEnvironmentStackOffset++;
                lexicalEnvironmentVariableDeclarations = undefined;
                lexicalEnvironmentFunctionDeclarations = undefined;
            }
            /** Suspends the current lexical environment, usually after visiting a parameter list. */
            function suspendLexicalEnvironment() {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
                ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
                lexicalEnvironmentSuspended = true;
            }
            /** Resumes a suspended lexical environment, usually before visiting a function body. */
            function resumeLexicalEnvironment() {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
                ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
                lexicalEnvironmentSuspended = false;
            }
            /**
             * Ends a lexical environment. The previous set of hoisted declarations are restored and
             * any hoisted declarations added in this environment are returned.
             */
            function endLexicalEnvironment() {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
                ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
                var statements;
                if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) {
                    if (lexicalEnvironmentFunctionDeclarations) {
                        statements = lexicalEnvironmentFunctionDeclarations.slice();
                    }
                    if (lexicalEnvironmentVariableDeclarations) {
                        var statement = ts.createVariableStatement(
                        /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
                        if (!statements) {
                            statements = [statement];
                        }
                        else {
                            statements.push(statement);
                        }
                    }
                }
                // Restore the previous lexical environment.
                lexicalEnvironmentStackOffset--;
                lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
                lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
                if (lexicalEnvironmentStackOffset === 0) {
                    lexicalEnvironmentVariableDeclarationsStack = [];
                    lexicalEnvironmentFunctionDeclarationsStack = [];
                }
                return statements;
            }
            function requestEmitHelper(helper) {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
                ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
                emitHelpers = ts.append(emitHelpers, helper);
            }
            function readEmitHelpers() {
                ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
                ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
                var helpers = emitHelpers;
                emitHelpers = undefined;
                return helpers;
            }
            function dispose() {
                if (state < 3 /* Disposed */) {
                    // Clean up emit nodes on parse tree
                    for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
                        var node = nodes_5[_i];
                        ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
                    }
                    // Release references to external entries for GC purposes.
                    lexicalEnvironmentVariableDeclarations = undefined;
                    lexicalEnvironmentVariableDeclarationsStack = undefined;
                    lexicalEnvironmentFunctionDeclarations = undefined;
                    lexicalEnvironmentFunctionDeclarationsStack = undefined;
                    onSubstituteNode = undefined;
                    onEmitNode = undefined;
                    emitHelpers = undefined;
                    // Prevent further use of the transformation result.
                    state = 3 /* Disposed */;
                }
            }
        }
        ts.transformNodes = transformNodes;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans
        var defaultLastEncodedSourceMapSpan = {
            emittedLine: 0,
            emittedColumn: 0,
            sourceLine: 0,
            sourceColumn: 0,
            sourceIndex: 0
        };
        function createSourceMapWriter(host, writer, compilerOptions) {
            if (compilerOptions === void 0) {
                compilerOptions = host.getCompilerOptions();
            }
            var extendedDiagnostics = compilerOptions.extendedDiagnostics;
            var currentSource;
            var currentSourceText;
            var sourceMapDir; // The directory in which sourcemap will be
            // Current source map file and its index in the sources list
            var sourceMapSourceIndex;
            // Last recorded and encoded spans
            var lastRecordedSourceMapSpan;
            var lastEncodedSourceMapSpan;
            var lastEncodedNameIndex;
            // Source map data
            var sourceMapData;
            var sourceMapDataList;
            var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap);
            return {
                initialize: initialize,
                reset: reset,
                setSourceFile: setSourceFile,
                emitPos: emitPos,
                emitNodeWithSourceMap: emitNodeWithSourceMap,
                emitTokenWithSourceMap: emitTokenWithSourceMap,
                getText: getText,
                getSourceMappingURL: getSourceMappingURL,
            };
            /**
             * Skips trivia such as comments and white-space that can optionally overriden by the source map source
             */
            function skipSourceTrivia(pos) {
                return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos);
            }
            /**
             * Initialize the SourceMapWriter for a new output file.
             *
             * @param filePath The path to the generated output file.
             * @param sourceMapFilePath The path to the output source map file.
             * @param sourceFileOrBundle The input source file or bundle for the program.
             */
            function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) {
                if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) {
                    return;
                }
                if (sourceMapData) {
                    reset();
                }
                sourceMapDataList = outputSourceMapDataList;
                currentSource = undefined;
                currentSourceText = undefined;
                // Current source map file and its index in the sources list
                sourceMapSourceIndex = -1;
                // Last recorded and encoded spans
                lastRecordedSourceMapSpan = undefined;
                lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan;
                lastEncodedNameIndex = 0;
                // Initialize source map data
                sourceMapData = {
                    sourceMapFilePath: sourceMapFilePath,
                    jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined,
                    sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)),
                    sourceMapSourceRoot: compilerOptions.sourceRoot || "",
                    sourceMapSources: [],
                    inputSourceFileNames: [],
                    sourceMapNames: [],
                    sourceMapMappings: "",
                    sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined,
                };
                // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
                // relative paths of the sources list in the sourcemap
                sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);
                if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) {
                    sourceMapData.sourceMapSourceRoot += ts.directorySeparator;
                }
                if (compilerOptions.mapRoot) {
                    sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);
                    if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file
                        // For modules or multiple emit files the mapRoot will have directory structure like the sources
                        // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
                        sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir));
                    }
                    if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) {
                        // The relative paths are relative to the common directory
                        sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
                        sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
                        ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap
                        host.getCurrentDirectory(), host.getCanonicalFileName, 
                        /*isAbsolutePathAnUrl*/ true);
                    }
                    else {
                        sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);
                    }
                }
                else {
                    sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath));
                }
            }
            /**
             * Reset the SourceMapWriter to an empty state.
             */
            function reset() {
                if (disabled) {
                    return;
                }
                // Record source map data for the test harness.
                if (sourceMapDataList) {
                    sourceMapDataList.push(sourceMapData);
                }
                currentSource = undefined;
                sourceMapDir = undefined;
                sourceMapSourceIndex = undefined;
                lastRecordedSourceMapSpan = undefined;
                lastEncodedSourceMapSpan = undefined;
                lastEncodedNameIndex = undefined;
                sourceMapData = undefined;
                sourceMapDataList = undefined;
            }
            function captureSection() {
                return {
                    version: 3,
                    file: sourceMapData.sourceMapFile,
                    sourceRoot: sourceMapData.sourceMapSourceRoot,
                    sources: sourceMapData.sourceMapSources,
                    names: sourceMapData.sourceMapNames,
                    mappings: sourceMapData.sourceMapMappings,
                    sourcesContent: sourceMapData.sourceMapSourcesContent,
                };
            }
            // Encoding for sourcemap span
            function encodeLastRecordedSourceMapSpan() {
                if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {
                    return;
                }
                ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative");
                ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative");
                ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative");
                ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative");
                var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;
                // Line/Comma delimiters
                if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
                    // Emit comma to separate the entry
                    if (sourceMapData.sourceMapMappings) {
                        sourceMapData.sourceMapMappings += ",";
                    }
                }
                else {
                    // Emit line delimiters
                    for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {
                        sourceMapData.sourceMapMappings += ";";
                    }
                    prevEncodedEmittedColumn = 0;
                }
                // 1. Relative Column 0 based
                sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);
                // 2. Relative sourceIndex
                sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);
                // 3. Relative sourceLine 0 based
                sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);
                // 4. Relative sourceColumn 0 based
                sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);
                // 5. Relative namePosition 0 based
                if (lastRecordedSourceMapSpan.nameIndex >= 0) {
                    ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this");
                    sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);
                    lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;
                }
                lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;
            }
            /**
             * Emits a mapping.
             *
             * If the position is synthetic (undefined or a negative value), no mapping will be
             * created.
             *
             * @param pos The position.
             */
            function emitPos(pos) {
                if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) {
                    return;
                }
                if (extendedDiagnostics) {
                    ts.performance.mark("beforeSourcemap");
                }
                var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos);
                var emittedLine = writer.getLine();
                var emittedColumn = writer.getColumn();
                // If this location wasn't recorded or the location in source is going backwards, record the span
                if (!lastRecordedSourceMapSpan ||
                    lastRecordedSourceMapSpan.emittedLine !== emittedLine ||
                    lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||
                    (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&
                        (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||
                            (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {
                    // Encode the last recordedSpan before assigning new
                    encodeLastRecordedSourceMapSpan();
                    // New span
                    lastRecordedSourceMapSpan = {
                        emittedLine: emittedLine,
                        emittedColumn: emittedColumn,
                        sourceLine: sourceLinePos.line,
                        sourceColumn: sourceLinePos.character,
                        sourceIndex: sourceMapSourceIndex
                    };
                }
                else {
                    // Take the new pos instead since there is no change in emittedLine and column since last location
                    lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line;
                    lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character;
                    lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex;
                }
                if (extendedDiagnostics) {
                    ts.performance.mark("afterSourcemap");
                    ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap");
                }
            }
            function isPossiblySourceMap(x) {
                return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources;
            }
            /**
             * Emits a node with possible leading and trailing source maps.
             *
             * @param hint A hint as to the intended usage of the node.
             * @param node The node to emit.
             * @param emitCallback The callback used to emit the node.
             */
            function emitNodeWithSourceMap(hint, node, emitCallback) {
                var _a;
                if (disabled || ts.isInJsonFile(node)) {
                    return emitCallback(hint, node);
                }
                if (node) {
                    if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
                        var text = node.sourceMapText;
                        var parsed = void 0;
                        try {
                            parsed = JSON.parse(text);
                        }
                        catch (_b) {
                            // empty
                        }
                        if (!parsed || !isPossiblySourceMap(parsed)) {
                            return emitCallback(hint, node);
                        }
                        var offsetLine = writer.getLine();
                        var firstLineColumnOffset = writer.getColumn();
                        // First, decode the old component sourcemap
                        var originalMap = parsed;
                        var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
                        var resolvedPathCache = ts.createMap();
                        var absolutePathCache = ts.createMap();
                        var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap);
                        for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) {
                            var pathCacheKey = "" + raw.sourceIndex;
                            // Apply offsets to each position and fixup source entries
                            if (!resolvedPathCache.has(pathCacheKey)) {
                                var rawPath = originalMap.sources[raw.sourceIndex];
                                var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath;
                                var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath);
                                var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, 
                                /*isAbsolutePathAnUrl*/ true);
                                resolvedPathCache.set(pathCacheKey, resolvedPath_1);
                                absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath));
                            }
                            var resolvedPath = resolvedPathCache.get(pathCacheKey);
                            var absolutePath = absolutePathCache.get(pathCacheKey);
                            // tslint:disable-next-line:no-null-keyword
                            setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining?
                            var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath);
                            // Then reencode all the updated spans into the overall map
                            encodeLastRecordedSourceMapSpan();
                            lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex });
                        }
                        // And actually emit the text these sourcemaps are for
                        return emitCallback(hint, node);
                    }
                    var emitNode = node.emitNode;
                    var emitFlags = emitNode && emitNode.flags || 0 /* None */;
                    var range = emitNode && emitNode.sourceMapRange;
                    var _d = range || node, pos = _d.pos, end = _d.end;
                    var source = range && range.source;
                    var oldSource = currentSource;
                    if (source === oldSource)
                        source = undefined;
                    if (source)
                        setSourceFile(source);
                    if (node.kind !== 305 /* NotEmittedStatement */
                        && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
                        && pos >= 0) {
                        emitPos(skipSourceTrivia(pos));
                    }
                    if (source)
                        setSourceFile(oldSource);
                    if (emitFlags & 64 /* NoNestedSourceMaps */) {
                        disabled = true;
                        emitCallback(hint, node);
                        disabled = false;
                    }
                    else {
                        emitCallback(hint, node);
                    }
                    if (source)
                        setSourceFile(source);
                    if (node.kind !== 305 /* NotEmittedStatement */
                        && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
                        && end >= 0) {
                        emitPos(end);
                    }
                    if (source)
                        setSourceFile(oldSource);
                }
            }
            /**
             * Emits a token of a node with possible leading and trailing source maps.
             *
             * @param node The node containing the token.
             * @param token The token to emit.
             * @param tokenStartPos The start pos of the token.
             * @param emitCallback The callback used to emit the token.
             */
            function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
                if (disabled || ts.isInJsonFile(node)) {
                    return emitCallback(token, writer, tokenPos);
                }
                var emitNode = node && node.emitNode;
                var emitFlags = emitNode && emitNode.flags || 0 /* None */;
                var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
                tokenPos = skipSourceTrivia(range ? range.pos : tokenPos);
                if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
                    emitPos(tokenPos);
                }
                tokenPos = emitCallback(token, writer, tokenPos);
                if (range)
                    tokenPos = range.end;
                if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
                    emitPos(tokenPos);
                }
                return tokenPos;
            }
            function isJsonSourceMapSource(sourceFile) {
                return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
            }
            /**
             * Set the current source file.
             *
             * @param sourceFile The source file.
             */
            function setSourceFile(sourceFile) {
                if (disabled) {
                    return;
                }
                currentSource = sourceFile;
                currentSourceText = currentSource.text;
                if (isJsonSourceMapSource(sourceFile)) {
                    return;
                }
                setupSourceEntry(sourceFile.fileName, sourceFile.text);
            }
            function setupSourceEntry(fileName, content, source) {
                if (!source) {
                    // Add the file to tsFilePaths
                    // If sourceroot option: Use the relative path corresponding to the common directory path
                    // otherwise source locations relative to map file location
                    var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
                    source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
                    /*isAbsolutePathAnUrl*/ true);
                }
                sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source);
                if (sourceMapSourceIndex === -1) {
                    sourceMapSourceIndex = sourceMapData.sourceMapSources.length;
                    sourceMapData.sourceMapSources.push(source);
                    // The one that can be used from program to get the actual source file
                    sourceMapData.inputSourceFileNames.push(fileName);
                    if (compilerOptions.inlineSources) {
                        sourceMapData.sourceMapSourcesContent.push(content);
                    }
                }
            }
            /**
             * Gets the text for the source map.
             */
            function getText() {
                if (disabled || isJsonSourceMapSource(currentSource)) {
                    return undefined; // TODO: GH#18217
                }
                encodeLastRecordedSourceMapSpan();
                return JSON.stringify(captureSection());
            }
            /**
             * Gets the SourceMappingURL for the source map.
             */
            function getSourceMappingURL() {
                if (disabled || isJsonSourceMapSource(currentSource)) {
                    return undefined; // TODO: GH#18217
                }
                if (compilerOptions.inlineSourceMap) {
                    // Encode the sourceMap into the sourceMap url
                    var base64SourceMapText = ts.base64encode(ts.sys, getText());
                    return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText;
                }
                else {
                    return sourceMapData.jsSourceMappingURL;
                }
            }
        }
        ts.createSourceMapWriter = createSourceMapWriter;
        var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        function base64FormatEncode(inValue) {
            if (inValue < 64) {
                return base64Chars.charAt(inValue);
            }
            throw TypeError(inValue + ": not a 64 based value");
        }
        function base64VLQFormatEncode(inValue) {
            // Add a new least significant bit that has the sign of the value.
            // if negative number the least significant bit that gets added to the number has value 1
            // else least significant bit value that gets added is 0
            // eg. -1 changes to binary : 01 [1] => 3
            //     +1 changes to binary : 01 [0] => 2
            if (inValue < 0) {
                inValue = ((-inValue) << 1) + 1;
            }
            else {
                inValue = inValue << 1;
            }
            // Encode 5 bits at a time starting from least significant bits
            var encodedStr = "";
            do {
                var currentDigit = inValue & 31; // 11111
                inValue = inValue >> 5;
                if (inValue > 0) {
                    // There are still more digits to decode, set the msb (6th bit)
                    currentDigit = currentDigit | 32;
                }
                encodedStr = encodedStr + base64FormatEncode(currentDigit);
            } while (inValue > 0);
            return encodedStr;
        }
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function createCommentWriter(printerOptions, emitPos) {
            var extendedDiagnostics = printerOptions.extendedDiagnostics;
            var newLine = ts.getNewLineCharacter(printerOptions);
            var writer;
            var containerPos = -1;
            var containerEnd = -1;
            var declarationListContainerEnd = -1;
            var currentSourceFile;
            var currentText;
            var currentLineMap;
            var detachedCommentsInfo;
            var hasWrittenComment = false;
            var disabled = !!printerOptions.removeComments;
            return {
                reset: reset,
                setWriter: setWriter,
                setSourceFile: setSourceFile,
                emitNodeWithComments: emitNodeWithComments,
                emitBodyWithDetachedComments: emitBodyWithDetachedComments,
                emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition,
                emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition,
            };
            function emitNodeWithComments(hint, node, emitCallback) {
                if (disabled) {
                    emitCallback(hint, node);
                    return;
                }
                if (node) {
                    hasWrittenComment = false;
                    var emitNode = node.emitNode;
                    var emitFlags = emitNode && emitNode.flags || 0;
                    var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end;
                    if ((pos < 0 && end < 0) || (pos === end)) {
                        // Both pos and end are synthesized, so just emit the node without comments.
                        emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback);
                    }
                    else {
                        if (extendedDiagnostics) {
                            ts.performance.mark("preEmitNodeWithComment");
                        }
                        var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */;
                        // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
                        // It is expensive to walk entire tree just to set one kind of node to have no comments.
                        var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */;
                        var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */;
                        // Emit leading comments if the position is not synthesized and the node
                        // has not opted out from emitting leading comments.
                        if (!skipLeadingComments) {
                            emitLeadingComments(pos, isEmittedNode);
                        }
                        // Save current container state on the stack.
                        var savedContainerPos = containerPos;
                        var savedContainerEnd = containerEnd;
                        var savedDeclarationListContainerEnd = declarationListContainerEnd;
                        if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
                            // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments.
                            containerPos = pos;
                        }
                        if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
                            // As above.
                            containerEnd = end;
                            // To avoid invalid comment emit in a down-level binding pattern, we
                            // keep track of the last declaration list container's end
                            if (node.kind === 236 /* VariableDeclarationList */) {
                                declarationListContainerEnd = end;
                            }
                        }
                        if (extendedDiagnostics) {
                            ts.performance.measure("commentTime", "preEmitNodeWithComment");
                        }
                        emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback);
                        if (extendedDiagnostics) {
                            ts.performance.mark("postEmitNodeWithComment");
                        }
                        // Restore previous container state.
                        containerPos = savedContainerPos;
                        containerEnd = savedContainerEnd;
                        declarationListContainerEnd = savedDeclarationListContainerEnd;
                        // Emit trailing comments if the position is not synthesized and the node
                        // has not opted out from emitting leading comments and is an emitted node.
                        if (!skipTrailingComments && isEmittedNode) {
                            emitTrailingComments(end);
                        }
                        if (extendedDiagnostics) {
                            ts.performance.measure("commentTime", "postEmitNodeWithComment");
                        }
                    }
                }
            }
            function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) {
                var leadingComments = emitNode && emitNode.leadingComments;
                if (ts.some(leadingComments)) {
                    if (extendedDiagnostics) {
                        ts.performance.mark("preEmitNodeWithSynthesizedComments");
                    }
                    ts.forEach(leadingComments, emitLeadingSynthesizedComment);
                    if (extendedDiagnostics) {
                        ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments");
                    }
                }
                emitNodeWithNestedComments(hint, node, emitFlags, emitCallback);
                var trailingComments = emitNode && emitNode.trailingComments;
                if (ts.some(trailingComments)) {
                    if (extendedDiagnostics) {
                        ts.performance.mark("postEmitNodeWithSynthesizedComments");
                    }
                    ts.forEach(trailingComments, emitTrailingSynthesizedComment);
                    if (extendedDiagnostics) {
                        ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments");
                    }
                }
            }
            function emitLeadingSynthesizedComment(comment) {
                if (comment.kind === 2 /* SingleLineCommentTrivia */) {
                    writer.writeLine();
                }
                writeSynthesizedComment(comment);
                if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
                    writer.writeLine();
                }
                else {
                    writer.write(" ");
                }
            }
            function emitTrailingSynthesizedComment(comment) {
                if (!writer.isAtStartOfLine()) {
                    writer.write(" ");
                }
                writeSynthesizedComment(comment);
                if (comment.hasTrailingNewLine) {
                    writer.writeLine();
                }
            }
            function writeSynthesizedComment(comment) {
                var text = formatSynthesizedComment(comment);
                var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
                ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
            }
            function formatSynthesizedComment(comment) {
                return comment.kind === 3 /* MultiLineCommentTrivia */
                    ? "/*" + comment.text + "*/"
                    : "//" + comment.text;
            }
            function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) {
                if (emitFlags & 2048 /* NoNestedComments */) {
                    disabled = true;
                    emitCallback(hint, node);
                    disabled = false;
                }
                else {
                    emitCallback(hint, node);
                }
            }
            function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
                if (extendedDiagnostics) {
                    ts.performance.mark("preEmitBodyWithDetachedComments");
                }
                var pos = detachedRange.pos, end = detachedRange.end;
                var emitFlags = ts.getEmitFlags(node);
                var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
                var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
                if (!skipLeadingComments) {
                    emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
                }
                if (extendedDiagnostics) {
                    ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments");
                }
                if (emitFlags & 2048 /* NoNestedComments */ && !disabled) {
                    disabled = true;
                    emitCallback(node);
                    disabled = false;
                }
                else {
                    emitCallback(node);
                }
                if (extendedDiagnostics) {
                    ts.performance.mark("beginEmitBodyWithDetachedCommetns");
                }
                if (!skipTrailingComments) {
                    emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
                    if (hasWrittenComment && !writer.isAtStartOfLine()) {
                        writer.writeLine();
                    }
                }
                if (extendedDiagnostics) {
                    ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns");
                }
            }
            function emitLeadingComments(pos, isEmittedNode) {
                hasWrittenComment = false;
                if (isEmittedNode) {
                    forEachLeadingCommentToEmit(pos, emitLeadingComment);
                }
                else if (pos === 0) {
                    // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
                    // unless it is a triple slash comment at the top of the file.
                    // For Example:
                    //      /// <reference-path ...>
                    //      declare var x;
                    //      /// <reference-path ...>
                    //      interface F {}
                    //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
                    forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
                }
            }
            function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
                if (isTripleSlashComment(commentPos, commentEnd)) {
                    emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
                }
            }
            function shouldWriteComment(text, pos) {
                if (printerOptions.onlyPrintJsDocStyle) {
                    return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
                }
                return true;
            }
            function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
                if (!shouldWriteComment(currentText, commentPos))
                    return;
                if (!hasWrittenComment) {
                    ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos);
                    hasWrittenComment = true;
                }
                // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
                if (emitPos)
                    emitPos(commentPos);
                ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
                if (emitPos)
                    emitPos(commentEnd);
                if (hasTrailingNewLine) {
                    writer.writeLine();
                }
                else if (kind === 3 /* MultiLineCommentTrivia */) {
                    writer.write(" ");
                }
            }
            function emitLeadingCommentsOfPosition(pos) {
                if (disabled || pos === -1) {
                    return;
                }
                emitLeadingComments(pos, /*isEmittedNode*/ true);
            }
            function emitTrailingComments(pos) {
                forEachTrailingCommentToEmit(pos, emitTrailingComment);
            }
            function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
                if (!shouldWriteComment(currentText, commentPos))
                    return;
                // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
                if (!writer.isAtStartOfLine()) {
                    writer.write(" ");
                }
                if (emitPos)
                    emitPos(commentPos);
                ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
                if (emitPos)
                    emitPos(commentEnd);
                if (hasTrailingNewLine) {
                    writer.writeLine();
                }
            }
            function emitTrailingCommentsOfPosition(pos, prefixSpace) {
                if (disabled) {
                    return;
                }
                if (extendedDiagnostics) {
                    ts.performance.mark("beforeEmitTrailingCommentsOfPosition");
                }
                forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
                if (extendedDiagnostics) {
                    ts.performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition");
                }
            }
            function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
                // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
                if (emitPos)
                    emitPos(commentPos);
                ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
                if (emitPos)
                    emitPos(commentEnd);
                if (hasTrailingNewLine) {
                    writer.writeLine();
                }
                else {
                    writer.write(" ");
                }
            }
            function forEachLeadingCommentToEmit(pos, cb) {
                // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
                if (containerPos === -1 || pos !== containerPos) {
                    if (hasDetachedComments(pos)) {
                        forEachLeadingCommentWithoutDetachedComments(cb);
                    }
                    else {
                        ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos);
                    }
                }
            }
            function forEachTrailingCommentToEmit(end, cb) {
                // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
                if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) {
                    ts.forEachTrailingCommentRange(currentText, end, cb);
                }
            }
            function reset() {
                currentSourceFile = undefined;
                currentText = undefined;
                currentLineMap = undefined;
                detachedCommentsInfo = undefined;
            }
            function setWriter(output) {
                writer = output;
            }
            function setSourceFile(sourceFile) {
                currentSourceFile = sourceFile;
                currentText = currentSourceFile.text;
                currentLineMap = ts.getLineStarts(currentSourceFile);
                detachedCommentsInfo = undefined;
            }
            function hasDetachedComments(pos) {
                return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
            }
            function forEachLeadingCommentWithoutDetachedComments(cb) {
                // get the leading comments from detachedPos
                var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
                if (detachedCommentsInfo.length - 1) {
                    detachedCommentsInfo.pop();
                }
                else {
                    detachedCommentsInfo = undefined;
                }
                ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos);
            }
            function emitDetachedCommentsAndUpdateCommentsInfo(range) {
                var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled);
                if (currentDetachedCommentInfo) {
                    if (detachedCommentsInfo) {
                        detachedCommentsInfo.push(currentDetachedCommentInfo);
                    }
                    else {
                        detachedCommentsInfo = [currentDetachedCommentInfo];
                    }
                }
            }
            function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
                if (!shouldWriteComment(currentText, commentPos))
                    return;
                if (emitPos)
                    emitPos(commentPos);
                ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
                if (emitPos)
                    emitPos(commentEnd);
            }
            /**
             * Determine if the given comment is a triple-slash
             *
             * @return true if the comment is a triple-slash comment else false
             */
            function isTripleSlashComment(commentPos, commentEnd) {
                return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd);
            }
        }
        ts.createCommentWriter = createCommentWriter;
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        var infoExtension = ".tsbundleinfo";
        var brackets = createBracketsMap();
        /*@internal*/
        /**
         * Iterates over the source files that are expected to have an emit output.
         *
         * @param host An EmitHost.
         * @param action The action to execute.
         * @param sourceFilesOrTargetSourceFile
         *   If an array, the full list of source files to emit.
         *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
         */
        function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
            if (emitOnlyDtsFiles === void 0) {
                emitOnlyDtsFiles = false;
            }
            var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
            var options = host.getCompilerOptions();
            if (options.outFile || options.out) {
                if (sourceFiles.length) {
                    var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
                    var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
                    if (result) {
                        return result;
                    }
                }
            }
            else {
                for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
                    var sourceFile = sourceFiles_1[_a];
                    var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
                    if (result) {
                        return result;
                    }
                }
            }
        }
        ts.forEachEmittedFile = forEachEmittedFile;
        /*@internal*/
        function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
            var options = host.getCompilerOptions();
            if (sourceFile.kind === 278 /* Bundle */) {
                var jsFilePath = options.outFile || options.out;
                var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
                var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined;
                var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
                var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
                return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
            }
            else {
                var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
                var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
                // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error
                var isJs = ts.isSourceFileJS(sourceFile);
                var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
                var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
                return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
            }
        }
        ts.getOutputPathsFor = getOutputPathsFor;
        function getSourceMapFilePath(jsFilePath, options) {
            return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
        }
        function createDefaultBundleInfo() {
            return {
                originalOffset: -1,
                totalLength: -1
            };
        }
        // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
        // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
        // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
        /* @internal */
        function getOutputExtension(sourceFile, options) {
            if (ts.isJsonSourceFile(sourceFile)) {
                return ".json" /* Json */;
            }
            if (options.jsx === 1 /* Preserve */) {
                if (ts.isSourceFileJS(sourceFile)) {
                    if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
                        return ".jsx" /* Jsx */;
                    }
                }
                else if (sourceFile.languageVariant === 1 /* JSX */) {
                    // TypeScript source file preserving JSX syntax
                    return ".jsx" /* Jsx */;
                }
            }
            return ".js" /* Js */;
        }
        ts.getOutputExtension = getOutputExtension;
        /*@internal*/
        // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
        function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
            var compilerOptions = host.getCompilerOptions();
            var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
            var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
            var emitterDiagnostics = ts.createDiagnosticCollection();
            var newLine = host.getNewLine();
            var writer = ts.createTextWriter(newLine);
            var sourceMap = ts.createSourceMapWriter(host, writer);
            var declarationSourceMap = ts.createSourceMapWriter(host, writer, {
                sourceMap: compilerOptions.declarationMap,
                sourceRoot: compilerOptions.sourceRoot,
                mapRoot: compilerOptions.mapRoot,
                extendedDiagnostics: compilerOptions.extendedDiagnostics,
            });
            var bundleInfo = createDefaultBundleInfo();
            var emitSkipped = false;
            var exportedModulesFromDeclarationEmit;
            // Emit each output file
            ts.performance.mark("beforePrint");
            forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
            ts.performance.measure("printTime", "beforePrint");
            return {
                emitSkipped: emitSkipped,
                diagnostics: emitterDiagnostics.getDiagnostics(),
                emittedFiles: emittedFilesList,
                sourceMaps: sourceMapDataList,
                exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
            };
            function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
                var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
                emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
                emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
                if (!emitSkipped && emittedFilesList) {
                    if (!emitOnlyDtsFiles) {
                        emittedFilesList.push(jsFilePath);
                    }
                    if (sourceMapFilePath) {
                        emittedFilesList.push(sourceMapFilePath);
                    }
                    if (declarationFilePath) {
                        emittedFilesList.push(declarationFilePath);
                    }
                    if (bundleInfoPath) {
                        emittedFilesList.push(bundleInfoPath);
                    }
                }
            }
            function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
                // Make sure not to write js file and source map file if any of them cannot be written
                if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) {
                    emitSkipped = true;
                    return;
                }
                if (emitOnlyDtsFiles) {
                    return;
                }
                // Transform the source files
                var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false);
                // Create a printer to print the nodes
                var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), {
                    // resolver hooks
                    hasGlobalName: resolver.hasGlobalName,
                    // transform hooks
                    onEmitNode: transform.emitNodeWithNotification,
                    substituteNode: transform.substituteNode,
                    // sourcemap hooks
                    onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap,
                    onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap,
                    onEmitSourceMapOfPosition: sourceMap.emitPos,
                    // emitter hooks
                    onSetSourceFile: setSourceFile,
                });
                ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
                printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap);
                // Clean up emit nodes on parse tree
                transform.dispose();
            }
            function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
                if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
                    return;
                }
                var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
                // Setup and perform the transformation to retrieve declarations from the input files
                var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS);
                var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
                if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
                    // Checker wont collect the linked aliases since thats only done when declaration is enabled.
                    // Do that here when emitting only dts files
                    nonJsFiles.forEach(collectLinkedAliases);
                }
                var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false);
                if (ts.length(declarationTransform.diagnostics)) {
                    for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
                        var diagnostic = _b[_a];
                        emitterDiagnostics.add(diagnostic);
                    }
                }
                var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), {
                    // resolver hooks
                    hasGlobalName: resolver.hasGlobalName,
                    // sourcemap hooks
                    onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap,
                    onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap,
                    onEmitSourceMapOfPosition: declarationSourceMap.emitPos,
                    onSetSourceFile: setSourceFileForDeclarationSourceMaps,
                    // transform hooks
                    onEmitNode: declarationTransform.emitNodeWithNotification,
                    substituteNode: declarationTransform.substituteNode,
                });
                var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
                emitSkipped = emitSkipped || declBlocked;
                if (!declBlocked || emitOnlyDtsFiles) {
                    ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
                    printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap);
                    if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) {
                        var sourceFile = declarationTransform.transformed[0];
                        exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
                    }
                }
                declarationTransform.dispose();
            }
            function collectLinkedAliases(node) {
                if (ts.isExportAssignment(node)) {
                    if (node.expression.kind === 71 /* Identifier */) {
                        resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
                    }
                    return;
                }
                else if (ts.isExportSpecifier(node)) {
                    resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
                    return;
                }
                ts.forEachChild(node, collectLinkedAliases);
            }
            function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) {
                var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined;
                var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined;
                var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
                mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList);
                if (bundle) {
                    printer.writeBundle(bundle, writer, bundleInfo);
                }
                else {
                    printer.writeFile(sourceFile, writer);
                }
                writer.writeLine();
                var sourceMappingURL = mapRecorder.getSourceMappingURL();
                if (sourceMappingURL) {
                    writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
                }
                // Write the source map
                if (sourceMapFilePath) {
                    ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles);
                }
                // Write the output file
                ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
                // Write bundled offset information if applicable
                if (bundleInfoPath) {
                    bundleInfo.totalLength = writer.getTextPos();
                    ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
                }
                // Reset state
                mapRecorder.reset();
                writer.clear();
                bundleInfo = createDefaultBundleInfo();
            }
            function setSourceFile(node) {
                sourceMap.setSourceFile(node);
            }
            function setSourceFileForDeclarationSourceMaps(node) {
                declarationSourceMap.setSourceFile(node);
            }
        }
        ts.emitFiles = emitFiles;
        var PipelinePhase;
        (function (PipelinePhase) {
            PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
            PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments";
            PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps";
            PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit";
        })(PipelinePhase || (PipelinePhase = {}));
        function createPrinter(printerOptions, handlers) {
            if (printerOptions === void 0) {
                printerOptions = {};
            }
            if (handlers === void 0) {
                handlers = {};
            }
            var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken;
            var newLine = ts.getNewLineCharacter(printerOptions);
            var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition);
            var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition;
            var currentSourceFile;
            var nodeIdToGeneratedName; // Map of generated names for specific nodes.
            var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
            var generatedNames; // Set of names generated by the NameGenerator.
            var tempFlagsStack; // Stack of enclosing name generation scopes.
            var tempFlags; // TempFlags for the current name generation scope.
            var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
            var reservedNames; // TempFlags to reserve in nested name generation scopes.
            var writer;
            var ownWriter;
            var write = writeBase;
            var commitPendingSemicolon = ts.noop;
            var writeSemicolon = writeSemicolonInternal;
            var pendingSemicolon = false;
            if (printerOptions.omitTrailingSemicolon) {
                commitPendingSemicolon = commitPendingSemicolonInternal;
                writeSemicolon = deferWriteSemicolon;
            }
            var syntheticParent = { pos: -1, end: -1 };
            var moduleKind = ts.getEmitModuleKind(printerOptions);
            var bundledHelpers = ts.createMap();
            var isOwnFileEmit;
            reset();
            return {
                // public API
                printNode: printNode,
                printList: printList,
                printFile: printFile,
                printBundle: printBundle,
                // internal API
                writeNode: writeNode,
                writeList: writeList,
                writeFile: writeFile,
                writeBundle: writeBundle
            };
            function printNode(hint, node, sourceFile) {
                switch (hint) {
                    case 0 /* SourceFile */:
                        ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
                        break;
                    case 2 /* IdentifierName */:
                        ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
                        break;
                    case 1 /* Expression */:
                        ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
                        break;
                }
                switch (node.kind) {
                    case 277 /* SourceFile */: return printFile(node);
                    case 278 /* Bundle */: return printBundle(node);
                    case 279 /* UnparsedSource */: return printUnparsedSource(node);
                }
                writeNode(hint, node, sourceFile, beginPrint());
                return endPrint();
            }
            function printList(format, nodes, sourceFile) {
                writeList(format, nodes, sourceFile, beginPrint());
                return endPrint();
            }
            function printBundle(bundle) {
                writeBundle(bundle, beginPrint());
                return endPrint();
            }
            function printFile(sourceFile) {
                writeFile(sourceFile, beginPrint());
                return endPrint();
            }
            function printUnparsedSource(unparsed) {
                writeUnparsedSource(unparsed, beginPrint());
                return endPrint();
            }
            function writeNode(hint, node, sourceFile, output) {
                var previousWriter = writer;
                setWriter(output);
                print(hint, node, sourceFile);
                reset();
                writer = previousWriter;
            }
            function writeList(format, nodes, sourceFile, output) {
                var previousWriter = writer;
                setWriter(output);
                if (sourceFile) {
                    setSourceFile(sourceFile);
                }
                emitList(syntheticParent, nodes, format);
                reset();
                writer = previousWriter;
            }
            function writeBundle(bundle, output, bundleInfo) {
                isOwnFileEmit = false;
                var previousWriter = writer;
                setWriter(output);
                emitShebangIfNeeded(bundle);
                emitPrologueDirectivesIfNeeded(bundle);
                emitHelpers(bundle);
                emitSyntheticTripleSlashReferencesIfNeeded(bundle);
                for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
                    var prepend = _b[_a];
                    print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
                    writeLine();
                }
                if (bundleInfo) {
                    bundleInfo.originalOffset = writer.getTextPos();
                }
                for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
                    var sourceFile = _d[_c];
                    print(0 /* SourceFile */, sourceFile, sourceFile);
                }
                reset();
                writer = previousWriter;
            }
            function writeUnparsedSource(unparsed, output) {
                var previousWriter = writer;
                setWriter(output);
                print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
                reset();
                writer = previousWriter;
            }
            function writeFile(sourceFile, output) {
                isOwnFileEmit = true;
                var previousWriter = writer;
                setWriter(output);
                emitShebangIfNeeded(sourceFile);
                emitPrologueDirectivesIfNeeded(sourceFile);
                print(0 /* SourceFile */, sourceFile, sourceFile);
                reset();
                writer = previousWriter;
            }
            function beginPrint() {
                return ownWriter || (ownWriter = ts.createTextWriter(newLine));
            }
            function endPrint() {
                var text = ownWriter.getText();
                ownWriter.clear();
                return text;
            }
            function print(hint, node, sourceFile) {
                if (sourceFile) {
                    setSourceFile(sourceFile);
                }
                var pipelinePhase = getPipelinePhase(0 /* Notification */, hint);
                pipelinePhase(hint, node);
            }
            function setSourceFile(sourceFile) {
                currentSourceFile = sourceFile;
                comments.setSourceFile(sourceFile);
                if (onSetSourceFile) {
                    onSetSourceFile(sourceFile);
                }
            }
            function setWriter(output) {
                writer = output; // TODO: GH#18217
                comments.setWriter(output);
            }
            function reset() {
                nodeIdToGeneratedName = [];
                autoGeneratedIdToGeneratedName = [];
                generatedNames = ts.createMap();
                tempFlagsStack = [];
                tempFlags = 0 /* Auto */;
                reservedNamesStack = [];
                comments.reset();
                setWriter(/*output*/ undefined);
            }
            function emit(node) {
                if (!node)
                    return;
                var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */);
                pipelinePhase(4 /* Unspecified */, node);
            }
            function emitIdentifierName(node) {
                if (!node)
                    return;
                var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */);
                pipelinePhase(2 /* IdentifierName */, node);
            }
            function emitExpression(node) {
                if (!node)
                    return;
                var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */);
                pipelinePhase(1 /* Expression */, node);
            }
            function getPipelinePhase(phase, hint) {
                switch (phase) {
                    case 0 /* Notification */:
                        if (onEmitNode) {
                            return pipelineEmitWithNotification;
                        }
                    // falls through
                    case 1 /* Comments */:
                        if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
                            return pipelineEmitWithComments;
                        }
                        return pipelineEmitWithoutComments;
                    case 2 /* SourceMaps */:
                        if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) {
                            return pipelineEmitWithSourceMap;
                        }
                    // falls through
                    case 3 /* Emit */:
                        return pipelineEmitWithHint;
                    default:
                        return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase);
                }
            }
            function getNextPipelinePhase(currentPhase, hint) {
                return getPipelinePhase(currentPhase + 1, hint);
            }
            function pipelineEmitWithNotification(hint, node) {
                ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint));
            }
            function pipelineEmitWithComments(hint, node) {
                ts.Debug.assertDefined(emitNodeWithComments);
                ts.Debug.assert(hint !== 0 /* SourceFile */);
                emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint));
            }
            function pipelineEmitWithoutComments(hint, node) {
                var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint);
                pipelinePhase(hint, trySubstituteNode(hint, node));
            }
            function pipelineEmitWithSourceMap(hint, node) {
                ts.Debug.assert(hint !== 0 /* SourceFile */);
                ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint);
            }
            function pipelineEmitWithHint(hint, node) {
                if (hint === 0 /* SourceFile */)
                    return emitSourceFile(ts.cast(node, ts.isSourceFile));
                if (hint === 2 /* IdentifierName */)
                    return emitIdentifier(ts.cast(node, ts.isIdentifier));
                if (hint === 3 /* MappedTypeParameter */)
                    return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
                if (hint === 4 /* Unspecified */) {
                    if (ts.isKeyword(node.kind))
                        return writeTokenNode(node, writeKeyword);
                    switch (node.kind) {
                        // Pseudo-literals
                        case 14 /* TemplateHead */:
                        case 15 /* TemplateMiddle */:
                        case 16 /* TemplateTail */:
                            return emitLiteral(node);
                        case 279 /* UnparsedSource */:
                            return emitUnparsedSource(node);
                        // Identifiers
                        case 71 /* Identifier */:
                            return emitIdentifier(node);
                        // Parse tree nodes
                        // Names
                        case 146 /* QualifiedName */:
                            return emitQualifiedName(node);
                        case 147 /* ComputedPropertyName */:
                            return emitComputedPropertyName(node);
                        // Signature elements
                        case 148 /* TypeParameter */:
                            return emitTypeParameter(node);
                        case 149 /* Parameter */:
                            return emitParameter(node);
                        case 150 /* Decorator */:
                            return emitDecorator(node);
                        // Type members
                        case 151 /* PropertySignature */:
                            return emitPropertySignature(node);
                        case 152 /* PropertyDeclaration */:
                            return emitPropertyDeclaration(node);
                        case 153 /* MethodSignature */:
                            return emitMethodSignature(node);
                        case 154 /* MethodDeclaration */:
                            return emitMethodDeclaration(node);
                        case 155 /* Constructor */:
                            return emitConstructor(node);
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            return emitAccessorDeclaration(node);
                        case 158 /* CallSignature */:
                            return emitCallSignature(node);
                        case 159 /* ConstructSignature */:
                            return emitConstructSignature(node);
                        case 160 /* IndexSignature */:
                            return emitIndexSignature(node);
                        // Types
                        case 161 /* TypePredicate */:
                            return emitTypePredicate(node);
                        case 162 /* TypeReference */:
                            return emitTypeReference(node);
                        case 163 /* FunctionType */:
                            return emitFunctionType(node);
                        case 287 /* JSDocFunctionType */:
                            return emitJSDocFunctionType(node);
                        case 164 /* ConstructorType */:
                            return emitConstructorType(node);
                        case 165 /* TypeQuery */:
                            return emitTypeQuery(node);
                        case 166 /* TypeLiteral */:
                            return emitTypeLiteral(node);
                        case 167 /* ArrayType */:
                            return emitArrayType(node);
                        case 168 /* TupleType */:
                            return emitTupleType(node);
                        case 169 /* OptionalType */:
                            return emitOptionalType(node);
                        case 171 /* UnionType */:
                            return emitUnionType(node);
                        case 172 /* IntersectionType */:
                            return emitIntersectionType(node);
                        case 173 /* ConditionalType */:
                            return emitConditionalType(node);
                        case 174 /* InferType */:
                            return emitInferType(node);
                        case 175 /* ParenthesizedType */:
                            return emitParenthesizedType(node);
                        case 209 /* ExpressionWithTypeArguments */:
                            return emitExpressionWithTypeArguments(node);
                        case 176 /* ThisType */:
                            return emitThisType();
                        case 177 /* TypeOperator */:
                            return emitTypeOperator(node);
                        case 178 /* IndexedAccessType */:
                            return emitIndexedAccessType(node);
                        case 179 /* MappedType */:
                            return emitMappedType(node);
                        case 180 /* LiteralType */:
                            return emitLiteralType(node);
                        case 181 /* ImportType */:
                            return emitImportTypeNode(node);
                        case 282 /* JSDocAllType */:
                            write("*");
                            return;
                        case 283 /* JSDocUnknownType */:
                            write("?");
                            return;
                        case 284 /* JSDocNullableType */:
                            return emitJSDocNullableType(node);
                        case 285 /* JSDocNonNullableType */:
                            return emitJSDocNonNullableType(node);
                        case 286 /* JSDocOptionalType */:
                            return emitJSDocOptionalType(node);
                        case 170 /* RestType */:
                        case 288 /* JSDocVariadicType */:
                            return emitRestOrJSDocVariadicType(node);
                        // Binding patterns
                        case 182 /* ObjectBindingPattern */:
                            return emitObjectBindingPattern(node);
                        case 183 /* ArrayBindingPattern */:
                            return emitArrayBindingPattern(node);
                        case 184 /* BindingElement */:
                            return emitBindingElement(node);
                        // Misc
                        case 214 /* TemplateSpan */:
                            return emitTemplateSpan(node);
                        case 215 /* SemicolonClassElement */:
                            return emitSemicolonClassElement();
                        // Statements
                        case 216 /* Block */:
                            return emitBlock(node);
                        case 217 /* VariableStatement */:
                            return emitVariableStatement(node);
                        case 218 /* EmptyStatement */:
                            return emitEmptyStatement();
                        case 219 /* ExpressionStatement */:
                            return emitExpressionStatement(node);
                        case 220 /* IfStatement */:
                            return emitIfStatement(node);
                        case 221 /* DoStatement */:
                            return emitDoStatement(node);
                        case 222 /* WhileStatement */:
                            return emitWhileStatement(node);
                        case 223 /* ForStatement */:
                            return emitForStatement(node);
                        case 224 /* ForInStatement */:
                            return emitForInStatement(node);
                        case 225 /* ForOfStatement */:
                            return emitForOfStatement(node);
                        case 226 /* ContinueStatement */:
                            return emitContinueStatement(node);
                        case 227 /* BreakStatement */:
                            return emitBreakStatement(node);
                        case 228 /* ReturnStatement */:
                            return emitReturnStatement(node);
                        case 229 /* WithStatement */:
                            return emitWithStatement(node);
                        case 230 /* SwitchStatement */:
                            return emitSwitchStatement(node);
                        case 231 /* LabeledStatement */:
                            return emitLabeledStatement(node);
                        case 232 /* ThrowStatement */:
                            return emitThrowStatement(node);
                        case 233 /* TryStatement */:
                            return emitTryStatement(node);
                        case 234 /* DebuggerStatement */:
                            return emitDebuggerStatement(node);
                        // Declarations
                        case 235 /* VariableDeclaration */:
                            return emitVariableDeclaration(node);
                        case 236 /* VariableDeclarationList */:
                            return emitVariableDeclarationList(node);
                        case 237 /* FunctionDeclaration */:
                            return emitFunctionDeclaration(node);
                        case 238 /* ClassDeclaration */:
                            return emitClassDeclaration(node);
                        case 239 /* InterfaceDeclaration */:
                            return emitInterfaceDeclaration(node);
                        case 240 /* TypeAliasDeclaration */:
                            return emitTypeAliasDeclaration(node);
                        case 241 /* EnumDeclaration */:
                            return emitEnumDeclaration(node);
                        case 242 /* ModuleDeclaration */:
                            return emitModuleDeclaration(node);
                        case 243 /* ModuleBlock */:
                            return emitModuleBlock(node);
                        case 244 /* CaseBlock */:
                            return emitCaseBlock(node);
                        case 245 /* NamespaceExportDeclaration */:
                            return emitNamespaceExportDeclaration(node);
                        case 246 /* ImportEqualsDeclaration */:
                            return emitImportEqualsDeclaration(node);
                        case 247 /* ImportDeclaration */:
                            return emitImportDeclaration(node);
                        case 248 /* ImportClause */:
                            return emitImportClause(node);
                        case 249 /* NamespaceImport */:
                            return emitNamespaceImport(node);
                        case 250 /* NamedImports */:
                            return emitNamedImports(node);
                        case 251 /* ImportSpecifier */:
                            return emitImportSpecifier(node);
                        case 252 /* ExportAssignment */:
                            return emitExportAssignment(node);
                        case 253 /* ExportDeclaration */:
                            return emitExportDeclaration(node);
                        case 254 /* NamedExports */:
                            return emitNamedExports(node);
                        case 255 /* ExportSpecifier */:
                            return emitExportSpecifier(node);
                        case 256 /* MissingDeclaration */:
                            return;
                        // Module references
                        case 257 /* ExternalModuleReference */:
                            return emitExternalModuleReference(node);
                        // JSX (non-expression)
                        case 10 /* JsxText */:
                            return emitJsxText(node);
                        case 260 /* JsxOpeningElement */:
                        case 263 /* JsxOpeningFragment */:
                            return emitJsxOpeningElementOrFragment(node);
                        case 261 /* JsxClosingElement */:
                        case 264 /* JsxClosingFragment */:
                            return emitJsxClosingElementOrFragment(node);
                        case 265 /* JsxAttribute */:
                            return emitJsxAttribute(node);
                        case 266 /* JsxAttributes */:
                            return emitJsxAttributes(node);
                        case 267 /* JsxSpreadAttribute */:
                            return emitJsxSpreadAttribute(node);
                        case 268 /* JsxExpression */:
                            return emitJsxExpression(node);
                        // Clauses
                        case 269 /* CaseClause */:
                            return emitCaseClause(node);
                        case 270 /* DefaultClause */:
                            return emitDefaultClause(node);
                        case 271 /* HeritageClause */:
                            return emitHeritageClause(node);
                        case 272 /* CatchClause */:
                            return emitCatchClause(node);
                        // Property assignments
                        case 273 /* PropertyAssignment */:
                            return emitPropertyAssignment(node);
                        case 274 /* ShorthandPropertyAssignment */:
                            return emitShorthandPropertyAssignment(node);
                        case 275 /* SpreadAssignment */:
                            return emitSpreadAssignment(node);
                        // Enum
                        case 276 /* EnumMember */:
                            return emitEnumMember(node);
                        // JSDoc nodes (ignored)
                        // Transformation nodes (ignored)
                    }
                    if (ts.isExpression(node)) {
                        hint = 1 /* Expression */;
                        node = trySubstituteNode(1 /* Expression */, node);
                    }
                    else if (ts.isToken(node)) {
                        return writeTokenNode(node, writePunctuation);
                    }
                }
                if (hint === 1 /* Expression */) {
                    switch (node.kind) {
                        // Literals
                        case 8 /* NumericLiteral */:
                            return emitNumericLiteral(node);
                        case 9 /* StringLiteral */:
                        case 12 /* RegularExpressionLiteral */:
                        case 13 /* NoSubstitutionTemplateLiteral */:
                            return emitLiteral(node);
                        // Identifiers
                        case 71 /* Identifier */:
                            return emitIdentifier(node);
                        // Reserved words
                        case 86 /* FalseKeyword */:
                        case 95 /* NullKeyword */:
                        case 97 /* SuperKeyword */:
                        case 101 /* TrueKeyword */:
                        case 99 /* ThisKeyword */:
                        case 91 /* ImportKeyword */:
                            writeTokenNode(node, writeKeyword);
                            return;
                        // Expressions
                        case 185 /* ArrayLiteralExpression */:
                            return emitArrayLiteralExpression(node);
                        case 186 /* ObjectLiteralExpression */:
                            return emitObjectLiteralExpression(node);
                        case 187 /* PropertyAccessExpression */:
                            return emitPropertyAccessExpression(node);
                        case 188 /* ElementAccessExpression */:
                            return emitElementAccessExpression(node);
                        case 189 /* CallExpression */:
                            return emitCallExpression(node);
                        case 190 /* NewExpression */:
                            return emitNewExpression(node);
                        case 191 /* TaggedTemplateExpression */:
                            return emitTaggedTemplateExpression(node);
                        case 192 /* TypeAssertionExpression */:
                            return emitTypeAssertionExpression(node);
                        case 193 /* ParenthesizedExpression */:
                            return emitParenthesizedExpression(node);
                        case 194 /* FunctionExpression */:
                            return emitFunctionExpression(node);
                        case 195 /* ArrowFunction */:
                            return emitArrowFunction(node);
                        case 196 /* DeleteExpression */:
                            return emitDeleteExpression(node);
                        case 197 /* TypeOfExpression */:
                            return emitTypeOfExpression(node);
                        case 198 /* VoidExpression */:
                            return emitVoidExpression(node);
                        case 199 /* AwaitExpression */:
                            return emitAwaitExpression(node);
                        case 200 /* PrefixUnaryExpression */:
                            return emitPrefixUnaryExpression(node);
                        case 201 /* PostfixUnaryExpression */:
                            return emitPostfixUnaryExpression(node);
                        case 202 /* BinaryExpression */:
                            return emitBinaryExpression(node);
                        case 203 /* ConditionalExpression */:
                            return emitConditionalExpression(node);
                        case 204 /* TemplateExpression */:
                            return emitTemplateExpression(node);
                        case 205 /* YieldExpression */:
                            return emitYieldExpression(node);
                        case 206 /* SpreadElement */:
                            return emitSpreadExpression(node);
                        case 207 /* ClassExpression */:
                            return emitClassExpression(node);
                        case 208 /* OmittedExpression */:
                            return;
                        case 210 /* AsExpression */:
                            return emitAsExpression(node);
                        case 211 /* NonNullExpression */:
                            return emitNonNullExpression(node);
                        case 212 /* MetaProperty */:
                            return emitMetaProperty(node);
                        // JSX
                        case 258 /* JsxElement */:
                            return emitJsxElement(node);
                        case 259 /* JsxSelfClosingElement */:
                            return emitJsxSelfClosingElement(node);
                        case 262 /* JsxFragment */:
                            return emitJsxFragment(node);
                        // Transformation nodes
                        case 306 /* PartiallyEmittedExpression */:
                            return emitPartiallyEmittedExpression(node);
                        case 307 /* CommaListExpression */:
                            return emitCommaList(node);
                    }
                }
            }
            function emitMappedTypeParameter(node) {
                emit(node.name);
                writeSpace();
                writeKeyword("in");
                writeSpace();
                emit(node.constraint);
            }
            function trySubstituteNode(hint, node) {
                return node && substituteNode && substituteNode(hint, node) || node;
            }
            function emitHelpers(node) {
                var helpersEmitted = false;
                var bundle = node.kind === 278 /* Bundle */ ? node : undefined;
                if (bundle && moduleKind === ts.ModuleKind.None) {
                    return;
                }
                var numNodes = bundle ? bundle.sourceFiles.length : 1;
                for (var i = 0; i < numNodes; i++) {
                    var currentNode = bundle ? bundle.sourceFiles[i] : node;
                    var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
                    var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
                    var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
                    var helpers = ts.getEmitHelpers(currentNode);
                    if (helpers) {
                        for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
                            var helper = _b[_a];
                            if (!helper.scoped) {
                                // Skip the helper if it can be skipped and the noEmitHelpers compiler
                                // option is set, or if it can be imported and the importHelpers compiler
                                // option is set.
                                if (shouldSkip)
                                    continue;
                                // Skip the helper if it can be bundled but hasn't already been emitted and we
                                // are emitting a bundled module.
                                if (shouldBundle) {
                                    if (bundledHelpers.get(helper.name)) {
                                        continue;
                                    }
                                    bundledHelpers.set(helper.name, true);
                                }
                            }
                            else if (bundle) {
                                // Skip the helper if it is scoped and we are emitting bundled helpers
                                continue;
                            }
                            if (typeof helper.text === "string") {
                                writeLines(helper.text);
                            }
                            else {
                                writeLines(helper.text(makeFileLevelOptimisticUniqueName));
                            }
                            helpersEmitted = true;
                        }
                    }
                }
                return helpersEmitted;
            }
            //
            // Literals/Pseudo-literals
            //
            // SyntaxKind.NumericLiteral
            function emitNumericLiteral(node) {
                emitLiteral(node);
            }
            // SyntaxKind.StringLiteral
            // SyntaxKind.RegularExpressionLiteral
            // SyntaxKind.NoSubstitutionTemplateLiteral
            // SyntaxKind.TemplateHead
            // SyntaxKind.TemplateMiddle
            // SyntaxKind.TemplateTail
            function emitLiteral(node) {
                var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape);
                if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
                    && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
                    writeLiteral(text);
                }
                else {
                    // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
                    writeStringLiteral(text);
                }
            }
            // SyntaxKind.UnparsedSource
            function emitUnparsedSource(unparsed) {
                writer.rawWrite(unparsed.text);
            }
            //
            // Identifiers
            //
            function emitIdentifier(node) {
                var writeText = node.symbol ? writeSymbol : write;
                writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
                emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
            }
            //
            // Names
            //
            function emitQualifiedName(node) {
                emitEntityName(node.left);
                writePunctuation(".");
                emit(node.right);
            }
            function emitEntityName(node) {
                if (node.kind === 71 /* Identifier */) {
                    emitExpression(node);
                }
                else {
                    emit(node);
                }
            }
            function emitComputedPropertyName(node) {
                writePunctuation("[");
                emitExpression(node.expression);
                writePunctuation("]");
            }
            //
            // Signature elements
            //
            function emitTypeParameter(node) {
                emit(node.name);
                if (node.constraint) {
                    writeSpace();
                    writeKeyword("extends");
                    writeSpace();
                    emit(node.constraint);
                }
                if (node.default) {
                    writeSpace();
                    writeOperator("=");
                    writeSpace();
                    emit(node.default);
                }
            }
            function emitParameter(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emit(node.dotDotDotToken);
                emitNodeWithWriter(node.name, writeParameter);
                emit(node.questionToken);
                if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) {
                    emit(node.type);
                }
                else {
                    emitTypeAnnotation(node.type);
                }
                // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer.
                emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node);
            }
            function emitDecorator(decorator) {
                writePunctuation("@");
                emitExpression(decorator.expression);
            }
            //
            // Type members
            //
            function emitPropertySignature(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emitNodeWithWriter(node.name, writeProperty);
                emit(node.questionToken);
                emitTypeAnnotation(node.type);
                writeSemicolon();
            }
            function emitPropertyDeclaration(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emit(node.name);
                emit(node.questionToken);
                emit(node.exclamationToken);
                emitTypeAnnotation(node.type);
                emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
                writeSemicolon();
            }
            function emitMethodSignature(node) {
                pushNameGenerationScope(node);
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emit(node.name);
                emit(node.questionToken);
                emitTypeParameters(node, node.typeParameters);
                emitParameters(node, node.parameters);
                emitTypeAnnotation(node.type);
                writeSemicolon();
                popNameGenerationScope(node);
            }
            function emitMethodDeclaration(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emit(node.asteriskToken);
                emit(node.name);
                emit(node.questionToken);
                emitSignatureAndBody(node, emitSignatureHead);
            }
            function emitConstructor(node) {
                emitModifiers(node, node.modifiers);
                writeKeyword("constructor");
                emitSignatureAndBody(node, emitSignatureHead);
            }
            function emitAccessorDeclaration(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set");
                writeSpace();
                emit(node.name);
                emitSignatureAndBody(node, emitSignatureHead);
            }
            function emitCallSignature(node) {
                pushNameGenerationScope(node);
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emitTypeParameters(node, node.typeParameters);
                emitParameters(node, node.parameters);
                emitTypeAnnotation(node.type);
                writeSemicolon();
                popNameGenerationScope(node);
            }
            function emitConstructSignature(node) {
                pushNameGenerationScope(node);
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                writeKeyword("new");
                writeSpace();
                emitTypeParameters(node, node.typeParameters);
                emitParameters(node, node.parameters);
                emitTypeAnnotation(node.type);
                writeSemicolon();
                popNameGenerationScope(node);
            }
            function emitIndexSignature(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emitParametersForIndexSignature(node, node.parameters);
                emitTypeAnnotation(node.type);
                writeSemicolon();
            }
            function emitSemicolonClassElement() {
                writeSemicolon();
            }
            //
            // Types
            //
            function emitTypePredicate(node) {
                emit(node.parameterName);
                writeSpace();
                writeKeyword("is");
                writeSpace();
                emit(node.type);
            }
            function emitTypeReference(node) {
                emit(node.typeName);
                emitTypeArguments(node, node.typeArguments);
            }
            function emitFunctionType(node) {
                pushNameGenerationScope(node);
                emitTypeParameters(node, node.typeParameters);
                emitParametersForArrow(node, node.parameters);
                writeSpace();
                writePunctuation("=>");
                writeSpace();
                emit(node.type);
                popNameGenerationScope(node);
            }
            function emitJSDocFunctionType(node) {
                write("function");
                emitParameters(node, node.parameters);
                write(":");
                emit(node.type);
            }
            function emitJSDocNullableType(node) {
                write("?");
                emit(node.type);
            }
            function emitJSDocNonNullableType(node) {
                write("!");
                emit(node.type);
            }
            function emitJSDocOptionalType(node) {
                emit(node.type);
                write("=");
            }
            function emitConstructorType(node) {
                pushNameGenerationScope(node);
                writeKeyword("new");
                writeSpace();
                emitTypeParameters(node, node.typeParameters);
                emitParameters(node, node.parameters);
                writeSpace();
                writePunctuation("=>");
                writeSpace();
                emit(node.type);
                popNameGenerationScope(node);
            }
            function emitTypeQuery(node) {
                writeKeyword("typeof");
                writeSpace();
                emit(node.exprName);
            }
            function emitTypeLiteral(node) {
                writePunctuation("{");
                var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */;
                emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */);
                writePunctuation("}");
            }
            function emitArrayType(node) {
                emit(node.elementType);
                writePunctuation("[");
                writePunctuation("]");
            }
            function emitRestOrJSDocVariadicType(node) {
                write("...");
                emit(node.type);
            }
            function emitTupleType(node) {
                writePunctuation("[");
                emitList(node, node.elementTypes, 272 /* TupleTypeElements */);
                writePunctuation("]");
            }
            function emitOptionalType(node) {
                emit(node.type);
                write("?");
            }
            function emitUnionType(node) {
                emitList(node, node.types, 260 /* UnionTypeConstituents */);
            }
            function emitIntersectionType(node) {
                emitList(node, node.types, 264 /* IntersectionTypeConstituents */);
            }
            function emitConditionalType(node) {
                emit(node.checkType);
                writeSpace();
                writeKeyword("extends");
                writeSpace();
                emit(node.extendsType);
                writeSpace();
                writePunctuation("?");
                writeSpace();
                emit(node.trueType);
                writeSpace();
                writePunctuation(":");
                writeSpace();
                emit(node.falseType);
            }
            function emitInferType(node) {
                writeKeyword("infer");
                writeSpace();
                emit(node.typeParameter);
            }
            function emitParenthesizedType(node) {
                writePunctuation("(");
                emit(node.type);
                writePunctuation(")");
            }
            function emitThisType() {
                writeKeyword("this");
            }
            function emitTypeOperator(node) {
                writeTokenText(node.operator, writeKeyword);
                writeSpace();
                emit(node.type);
            }
            function emitIndexedAccessType(node) {
                emit(node.objectType);
                writePunctuation("[");
                emit(node.indexType);
                writePunctuation("]");
            }
            function emitMappedType(node) {
                var emitFlags = ts.getEmitFlags(node);
                writePunctuation("{");
                if (emitFlags & 1 /* SingleLine */) {
                    writeSpace();
                }
                else {
                    writeLine();
                    increaseIndent();
                }
                if (node.readonlyToken) {
                    emit(node.readonlyToken);
                    if (node.readonlyToken.kind !== 132 /* ReadonlyKeyword */) {
                        writeKeyword("readonly");
                    }
                    writeSpace();
                }
                writePunctuation("[");
                var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */);
                pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter);
                writePunctuation("]");
                if (node.questionToken) {
                    emit(node.questionToken);
                    if (node.questionToken.kind !== 55 /* QuestionToken */) {
                        writePunctuation("?");
                    }
                }
                writePunctuation(":");
                writeSpace();
                emit(node.type);
                writeSemicolon();
                if (emitFlags & 1 /* SingleLine */) {
                    writeSpace();
                }
                else {
                    writeLine();
                    decreaseIndent();
                }
                writePunctuation("}");
            }
            function emitLiteralType(node) {
                emitExpression(node.literal);
            }
            function emitImportTypeNode(node) {
                if (node.isTypeOf) {
                    writeKeyword("typeof");
                    writeSpace();
                }
                writeKeyword("import");
                writePunctuation("(");
                emit(node.argument);
                writePunctuation(")");
                if (node.qualifier) {
                    writePunctuation(".");
                    emit(node.qualifier);
                }
                emitTypeArguments(node, node.typeArguments);
            }
            //
            // Binding patterns
            //
            function emitObjectBindingPattern(node) {
                writePunctuation("{");
                emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */);
                writePunctuation("}");
            }
            function emitArrayBindingPattern(node) {
                writePunctuation("[");
                emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */);
                writePunctuation("]");
            }
            function emitBindingElement(node) {
                emit(node.dotDotDotToken);
                if (node.propertyName) {
                    emit(node.propertyName);
                    writePunctuation(":");
                    writeSpace();
                }
                emit(node.name);
                emitInitializer(node.initializer, node.name.end, node);
            }
            //
            // Expressions
            //
            function emitArrayLiteralExpression(node) {
                var elements = node.elements;
                var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */;
                emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine);
            }
            function emitObjectLiteralExpression(node) {
                ts.forEach(node.properties, generateMemberNames);
                var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
                if (indentedFlag) {
                    increaseIndent();
                }
                var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */;
                var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */;
                emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
                if (indentedFlag) {
                    decreaseIndent();
                }
            }
            function emitPropertyAccessExpression(node) {
                var indentBeforeDot = false;
                var indentAfterDot = false;
                if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) {
                    var dotRangeStart = node.expression.end;
                    var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1;
                    var dotToken = ts.createToken(23 /* DotToken */);
                    dotToken.pos = dotRangeStart;
                    dotToken.end = dotRangeEnd;
                    indentBeforeDot = needsIndentation(node, node.expression, dotToken);
                    indentAfterDot = needsIndentation(node, dotToken, node.name);
                }
                emitExpression(node.expression);
                increaseIndentIf(indentBeforeDot);
                var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression);
                if (shouldEmitDotDot) {
                    writePunctuation(".");
                }
                emitTokenWithComment(23 /* DotToken */, node.expression.end, writePunctuation, node);
                increaseIndentIf(indentAfterDot);
                emit(node.name);
                decreaseIndentIf(indentBeforeDot, indentAfterDot);
            }
            // 1..toString is a valid property access, emit a dot after the literal
            // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
            function needsDotDotForPropertyAccess(expression) {
                expression = ts.skipPartiallyEmittedExpressions(expression);
                if (ts.isNumericLiteral(expression)) {
                    // check if numeric literal is a decimal literal that was originally written with a dot
                    var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true);
                    return !expression.numericLiteralFlags
                        && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */));
                }
                else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) {
                    // check if constant enum value is integer
                    var constantValue = ts.getConstantValue(expression);
                    // isFinite handles cases when constantValue is undefined
                    return typeof constantValue === "number" && isFinite(constantValue)
                        && Math.floor(constantValue) === constantValue
                        && printerOptions.removeComments;
                }
            }
            function emitElementAccessExpression(node) {
                emitExpression(node.expression);
                emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
                emitExpression(node.argumentExpression);
                emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
            }
            function emitCallExpression(node) {
                emitExpression(node.expression);
                emitTypeArguments(node, node.typeArguments);
                emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */);
            }
            function emitNewExpression(node) {
                emitTokenWithComment(94 /* NewKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
                emitTypeArguments(node, node.typeArguments);
                emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */);
            }
            function emitTaggedTemplateExpression(node) {
                emitExpression(node.tag);
                emitTypeArguments(node, node.typeArguments);
                writeSpace();
                emitExpression(node.template);
            }
            function emitTypeAssertionExpression(node) {
                writePunctuation("<");
                emit(node.type);
                writePunctuation(">");
                emitExpression(node.expression);
            }
            function emitParenthesizedExpression(node) {
                var openParenPos = emitTokenWithComment(19 /* OpenParenToken */, node.pos, writePunctuation, node);
                emitExpression(node.expression);
                emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
            }
            function emitFunctionExpression(node) {
                generateNameIfNeeded(node.name);
                emitFunctionDeclarationOrExpression(node);
            }
            function emitArrowFunction(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                emitSignatureAndBody(node, emitArrowFunctionHead);
            }
            function emitArrowFunctionHead(node) {
                emitTypeParameters(node, node.typeParameters);
                emitParametersForArrow(node, node.parameters);
                emitTypeAnnotation(node.type);
                writeSpace();
                emit(node.equalsGreaterThanToken);
            }
            function emitDeleteExpression(node) {
                emitTokenWithComment(80 /* DeleteKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
            }
            function emitTypeOfExpression(node) {
                emitTokenWithComment(103 /* TypeOfKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
            }
            function emitVoidExpression(node) {
                emitTokenWithComment(105 /* VoidKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
            }
            function emitAwaitExpression(node) {
                emitTokenWithComment(121 /* AwaitKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
            }
            function emitPrefixUnaryExpression(node) {
                writeTokenText(node.operator, writeOperator);
                if (shouldEmitWhitespaceBeforeOperand(node)) {
                    writeSpace();
                }
                emitExpression(node.operand);
            }
            function shouldEmitWhitespaceBeforeOperand(node) {
                // In some cases, we need to emit a space between the operator and the operand. One obvious case
                // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
                // and minus expressions in certain cases. Specifically, consider the following two cases (parens
                // are just for clarity of exposition, and not part of the source code):
                //
                //  (+(+1))
                //  (+(++1))
                //
                // We need to emit a space in both cases. In the first case, the absence of a space will make
                // the resulting expression a prefix increment operation. And in the second, it will make the resulting
                // expression a prefix increment whose operand is a plus expression - (++(+x))
                // The same is true of minus of course.
                var operand = node.operand;
                return operand.kind === 200 /* PrefixUnaryExpression */
                    && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */))
                        || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */)));
            }
            function emitPostfixUnaryExpression(node) {
                emitExpression(node.operand);
                writeTokenText(node.operator, writeOperator);
            }
            function emitBinaryExpression(node) {
                var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */;
                var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken);
                var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right);
                emitExpression(node.left);
                increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined);
                emitLeadingCommentsOfPosition(node.operatorToken.pos);
                writeTokenNode(node.operatorToken, writeOperator);
                emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
                increaseIndentIf(indentAfterOperator, " ");
                emitExpression(node.right);
                decreaseIndentIf(indentBeforeOperator, indentAfterOperator);
            }
            function emitConditionalExpression(node) {
                var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken);
                var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue);
                var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken);
                var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse);
                emitExpression(node.condition);
                increaseIndentIf(indentBeforeQuestion, " ");
                emit(node.questionToken);
                increaseIndentIf(indentAfterQuestion, " ");
                emitExpression(node.whenTrue);
                decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion);
                increaseIndentIf(indentBeforeColon, " ");
                emit(node.colonToken);
                increaseIndentIf(indentAfterColon, " ");
                emitExpression(node.whenFalse);
                decreaseIndentIf(indentBeforeColon, indentAfterColon);
            }
            function emitTemplateExpression(node) {
                emit(node.head);
                emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */);
            }
            function emitYieldExpression(node) {
                emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
                emit(node.asteriskToken);
                emitExpressionWithLeadingSpace(node.expression);
            }
            function emitSpreadExpression(node) {
                writePunctuation("...");
                emitExpression(node.expression);
            }
            function emitClassExpression(node) {
                generateNameIfNeeded(node.name);
                emitClassDeclarationOrExpression(node);
            }
            function emitExpressionWithTypeArguments(node) {
                emitExpression(node.expression);
                emitTypeArguments(node, node.typeArguments);
            }
            function emitAsExpression(node) {
                emitExpression(node.expression);
                if (node.type) {
                    writeSpace();
                    writeKeyword("as");
                    writeSpace();
                    emit(node.type);
                }
            }
            function emitNonNullExpression(node) {
                emitExpression(node.expression);
                writeOperator("!");
            }
            function emitMetaProperty(node) {
                writeToken(node.keywordToken, node.pos, writePunctuation);
                writePunctuation(".");
                emit(node.name);
            }
            //
            // Misc
            //
            function emitTemplateSpan(node) {
                emitExpression(node.expression);
                emit(node.literal);
            }
            //
            // Statements
            //
            function emitBlock(node) {
                emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
            }
            function emitBlockStatements(node, forceSingleLine) {
                emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
                var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */;
                emitList(node, node.statements, format);
                emitTokenWithComment(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
            }
            function emitVariableStatement(node) {
                emitModifiers(node, node.modifiers);
                emit(node.declarationList);
                writeSemicolon();
            }
            function emitEmptyStatement() {
                writeSemicolon();
            }
            function emitExpressionStatement(node) {
                emitExpression(node.expression);
                // Emit semicolon in non json files
                // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
                if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
                    writeSemicolon();
                }
            }
            function emitIfStatement(node) {
                var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
                emitExpression(node.expression);
                emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
                emitEmbeddedStatement(node, node.thenStatement);
                if (node.elseStatement) {
                    writeLineOrSpace(node);
                    emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
                    if (node.elseStatement.kind === 220 /* IfStatement */) {
                        writeSpace();
                        emit(node.elseStatement);
                    }
                    else {
                        emitEmbeddedStatement(node, node.elseStatement);
                    }
                }
            }
            function emitWhileClause(node, startPos) {
                var openParenPos = emitTokenWithComment(106 /* WhileKeyword */, startPos, writeKeyword, node);
                writeSpace();
                emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
                emitExpression(node.expression);
                emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
            }
            function emitDoStatement(node) {
                emitTokenWithComment(81 /* DoKeyword */, node.pos, writeKeyword, node);
                emitEmbeddedStatement(node, node.statement);
                if (ts.isBlock(node.statement)) {
                    writeSpace();
                }
                else {
                    writeLineOrSpace(node);
                }
                emitWhileClause(node, node.statement.end);
                writePunctuation(";");
            }
            function emitWhileStatement(node) {
                emitWhileClause(node, node.pos);
                emitEmbeddedStatement(node, node.statement);
            }
            function emitForStatement(node) {
                var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                var pos = emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
                emitForBinding(node.initializer);
                pos = emitTokenWithComment(25 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writeSemicolon, node);
                emitExpressionWithLeadingSpace(node.condition);
                pos = emitTokenWithComment(25 /* SemicolonToken */, node.condition ? node.condition.end : pos, writeSemicolon, node);
                emitExpressionWithLeadingSpace(node.incrementor);
                emitTokenWithComment(20 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
                emitEmbeddedStatement(node, node.statement);
            }
            function emitForInStatement(node) {
                var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
                emitForBinding(node.initializer);
                writeSpace();
                emitTokenWithComment(92 /* InKeyword */, node.initializer.end, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
                emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
                emitEmbeddedStatement(node, node.statement);
            }
            function emitForOfStatement(node) {
                var openParenPos = emitTokenWithComment(88 /* ForKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitWithTrailingSpace(node.awaitModifier);
                emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
                emitForBinding(node.initializer);
                writeSpace();
                emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
                emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
                emitEmbeddedStatement(node, node.statement);
            }
            function emitForBinding(node) {
                if (node !== undefined) {
                    if (node.kind === 236 /* VariableDeclarationList */) {
                        emit(node);
                    }
                    else {
                        emitExpression(node);
                    }
                }
            }
            function emitContinueStatement(node) {
                emitTokenWithComment(77 /* ContinueKeyword */, node.pos, writeKeyword, node);
                emitWithLeadingSpace(node.label);
                writeSemicolon();
            }
            function emitBreakStatement(node) {
                emitTokenWithComment(72 /* BreakKeyword */, node.pos, writeKeyword, node);
                emitWithLeadingSpace(node.label);
                writeSemicolon();
            }
            function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
                var node = ts.getParseTreeNode(contextNode);
                var isSimilarNode = node && node.kind === contextNode.kind;
                var startPos = pos;
                if (isSimilarNode) {
                    pos = ts.skipTrivia(currentSourceFile.text, pos);
                }
                if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
                    var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
                    if (needsIndent) {
                        increaseIndent();
                    }
                    emitLeadingCommentsOfPosition(startPos);
                    if (needsIndent) {
                        decreaseIndent();
                    }
                }
                pos = writeTokenText(token, writer, pos);
                if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
                    emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
                }
                return pos;
            }
            function emitReturnStatement(node) {
                emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
                emitExpressionWithLeadingSpace(node.expression);
                writeSemicolon();
            }
            function emitWithStatement(node) {
                var openParenPos = emitTokenWithComment(107 /* WithKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
                emitExpression(node.expression);
                emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
                emitEmbeddedStatement(node, node.statement);
            }
            function emitSwitchStatement(node) {
                var openParenPos = emitTokenWithComment(98 /* SwitchKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
                emitExpression(node.expression);
                emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node);
                writeSpace();
                emit(node.caseBlock);
            }
            function emitLabeledStatement(node) {
                emit(node.label);
                emitTokenWithComment(56 /* ColonToken */, node.label.end, writePunctuation, node);
                writeSpace();
                emit(node.statement);
            }
            function emitThrowStatement(node) {
                emitTokenWithComment(100 /* ThrowKeyword */, node.pos, writeKeyword, node);
                emitExpressionWithLeadingSpace(node.expression);
                writeSemicolon();
            }
            function emitTryStatement(node) {
                emitTokenWithComment(102 /* TryKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emit(node.tryBlock);
                if (node.catchClause) {
                    writeLineOrSpace(node);
                    emit(node.catchClause);
                }
                if (node.finallyBlock) {
                    writeLineOrSpace(node);
                    emitTokenWithComment(87 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
                    writeSpace();
                    emit(node.finallyBlock);
                }
            }
            function emitDebuggerStatement(node) {
                writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword);
                writeSemicolon();
            }
            //
            // Declarations
            //
            function emitVariableDeclaration(node) {
                emit(node.name);
                emitTypeAnnotation(node.type);
                emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
            }
            function emitVariableDeclarationList(node) {
                writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
                writeSpace();
                emitList(node, node.declarations, 272 /* VariableDeclarationList */);
            }
            function emitFunctionDeclaration(node) {
                emitFunctionDeclarationOrExpression(node);
            }
            function emitFunctionDeclarationOrExpression(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                writeKeyword("function");
                emit(node.asteriskToken);
                writeSpace();
                emitIdentifierName(node.name); // TODO: GH#18217
                emitSignatureAndBody(node, emitSignatureHead);
            }
            function emitBlockCallback(_hint, body) {
                emitBlockFunctionBody(body);
            }
            function emitSignatureAndBody(node, emitSignatureHead) {
                var body = node.body;
                if (body) {
                    if (ts.isBlock(body)) {
                        var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
                        if (indentedFlag) {
                            increaseIndent();
                        }
                        pushNameGenerationScope(node);
                        ts.forEach(node.parameters, generateNames);
                        generateNames(node.body);
                        emitSignatureHead(node);
                        if (onEmitNode) {
                            onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
                        }
                        else {
                            emitBlockFunctionBody(body);
                        }
                        popNameGenerationScope(node);
                        if (indentedFlag) {
                            decreaseIndent();
                        }
                    }
                    else {
                        emitSignatureHead(node);
                        writeSpace();
                        emitExpression(body);
                    }
                }
                else {
                    emitSignatureHead(node);
                    writeSemicolon();
                }
            }
            function emitSignatureHead(node) {
                emitTypeParameters(node, node.typeParameters);
                emitParameters(node, node.parameters);
                emitTypeAnnotation(node.type);
            }
            function shouldEmitBlockFunctionBodyOnSingleLine(body) {
                // We must emit a function body as a single-line body in the following case:
                // * The body has NodeEmitFlags.SingleLine specified.
                // We must emit a function body as a multi-line body in the following cases:
                // * The body is explicitly marked as multi-line.
                // * A non-synthesized body's start and end position are on different lines.
                // * Any statement in the body starts on a new line.
                if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
                    return true;
                }
                if (body.multiLine) {
                    return false;
                }
                if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
                    return false;
                }
                if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */)
                    || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) {
                    return false;
                }
                var previousStatement;
                for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
                    var statement = _b[_a];
                    if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) {
                        return false;
                    }
                    previousStatement = statement;
                }
                return true;
            }
            function emitBlockFunctionBody(body) {
                writeSpace();
                writePunctuation("{");
                increaseIndent();
                var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
                    ? emitBlockFunctionBodyOnSingleLine
                    : emitBlockFunctionBodyWorker;
                if (emitBodyWithDetachedComments) {
                    emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
                }
                else {
                    emitBlockFunctionBody(body);
                }
                decreaseIndent();
                writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
            }
            function emitBlockFunctionBodyOnSingleLine(body) {
                emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
            }
            function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
                // Emit all the prologue directives (like "use strict").
                var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
                var pos = writer.getTextPos();
                emitHelpers(body);
                if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
                    decreaseIndent();
                    emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */);
                    increaseIndent();
                }
                else {
                    emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
                }
            }
            function emitClassDeclaration(node) {
                emitClassDeclarationOrExpression(node);
            }
            function emitClassDeclarationOrExpression(node) {
                ts.forEach(node.members, generateMemberNames);
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                writeKeyword("class");
                if (node.name) {
                    writeSpace();
                    emitIdentifierName(node.name);
                }
                var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
                if (indentedFlag) {
                    increaseIndent();
                }
                emitTypeParameters(node, node.typeParameters);
                emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
                writeSpace();
                writePunctuation("{");
                emitList(node, node.members, 65 /* ClassMembers */);
                writePunctuation("}");
                if (indentedFlag) {
                    decreaseIndent();
                }
            }
            function emitInterfaceDeclaration(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                writeKeyword("interface");
                writeSpace();
                emit(node.name);
                emitTypeParameters(node, node.typeParameters);
                emitList(node, node.heritageClauses, 256 /* HeritageClauses */);
                writeSpace();
                writePunctuation("{");
                emitList(node, node.members, 65 /* InterfaceMembers */);
                writePunctuation("}");
            }
            function emitTypeAliasDeclaration(node) {
                emitDecorators(node, node.decorators);
                emitModifiers(node, node.modifiers);
                writeKeyword("type");
                writeSpace();
                emit(node.name);
                emitTypeParameters(node, node.typeParameters);
                writeSpace();
                writePunctuation("=");
                writeSpace();
                emit(node.type);
                writeSemicolon();
            }
            function emitEnumDeclaration(node) {
                emitModifiers(node, node.modifiers);
                writeKeyword("enum");
                writeSpace();
                emit(node.name);
                writeSpace();
                writePunctuation("{");
                emitList(node, node.members, 81 /* EnumMembers */);
                writePunctuation("}");
            }
            function emitModuleDeclaration(node) {
                emitModifiers(node, node.modifiers);
                if (~node.flags & 512 /* GlobalAugmentation */) {
                    writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
                    writeSpace();
                }
                emit(node.name);
                var body = node.body;
                if (!body)
                    return writeSemicolon();
                while (body.kind === 242 /* ModuleDeclaration */) {
                    writePunctuation(".");
                    emit(body.name);
                    body = body.body;
                }
                writeSpace();
                emit(body);
            }
            function emitModuleBlock(node) {
                pushNameGenerationScope(node);
                ts.forEach(node.statements, generateNames);
                emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
                popNameGenerationScope(node);
            }
            function emitCaseBlock(node) {
                emitTokenWithComment(17 /* OpenBraceToken */, node.pos, writePunctuation, node);
                emitList(node, node.clauses, 65 /* CaseBlockClauses */);
                emitTokenWithComment(18 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
            }
            function emitImportEqualsDeclaration(node) {
                emitModifiers(node, node.modifiers);
                emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
                writeSpace();
                emit(node.name);
                writeSpace();
                emitTokenWithComment(58 /* EqualsToken */, node.name.end, writePunctuation, node);
                writeSpace();
                emitModuleReference(node.moduleReference);
                writeSemicolon();
            }
            function emitModuleReference(node) {
                if (node.kind === 71 /* Identifier */) {
                    emitExpression(node);
                }
                else {
                    emit(node);
                }
            }
            function emitImportDeclaration(node) {
                emitModifiers(node, node.modifiers);
                emitTokenWithComment(91 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
                writeSpace();
                if (node.importClause) {
                    emit(node.importClause);
                    writeSpace();
                    emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node);
                    writeSpace();
                }
                emitExpression(node.moduleSpecifier);
                writeSemicolon();
            }
            function emitImportClause(node) {
                emit(node.name);
                if (node.name && node.namedBindings) {
                    emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
                    writeSpace();
                }
                emit(node.namedBindings);
            }
            function emitNamespaceImport(node) {
                var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
                writeSpace();
                emitTokenWithComment(118 /* AsKeyword */, asPos, writeKeyword, node);
                writeSpace();
                emit(node.name);
            }
            function emitNamedImports(node) {
                emitNamedImportsOrExports(node);
            }
            function emitImportSpecifier(node) {
                emitImportOrExportSpecifier(node);
            }
            function emitExportAssignment(node) {
                var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                if (node.isExportEquals) {
                    emitTokenWithComment(58 /* EqualsToken */, nextPos, writeOperator, node);
                }
                else {
                    emitTokenWithComment(79 /* DefaultKeyword */, nextPos, writeKeyword, node);
                }
                writeSpace();
                emitExpression(node.expression);
                writeSemicolon();
            }
            function emitExportDeclaration(node) {
                var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                if (node.exportClause) {
                    emit(node.exportClause);
                }
                else {
                    nextPos = emitTokenWithComment(39 /* AsteriskToken */, nextPos, writePunctuation, node);
                }
                if (node.moduleSpecifier) {
                    writeSpace();
                    var fromPos = node.exportClause ? node.exportClause.end : nextPos;
                    emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node);
                    writeSpace();
                    emitExpression(node.moduleSpecifier);
                }
                writeSemicolon();
            }
            function emitNamespaceExportDeclaration(node) {
                var nextPos = emitTokenWithComment(84 /* ExportKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                nextPos = emitTokenWithComment(118 /* AsKeyword */, nextPos, writeKeyword, node);
                writeSpace();
                nextPos = emitTokenWithComment(130 /* NamespaceKeyword */, nextPos, writeKeyword, node);
                writeSpace();
                emit(node.name);
                writeSemicolon();
            }
            function emitNamedExports(node) {
                emitNamedImportsOrExports(node);
            }
            function emitExportSpecifier(node) {
                emitImportOrExportSpecifier(node);
            }
            function emitNamedImportsOrExports(node) {
                writePunctuation("{");
                emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */);
                writePunctuation("}");
            }
            function emitImportOrExportSpecifier(node) {
                if (node.propertyName) {
                    emit(node.propertyName);
                    writeSpace();
                    emitTokenWithComment(118 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
                    writeSpace();
                }
                emit(node.name);
            }
            //
            // Module references
            //
            function emitExternalModuleReference(node) {
                writeKeyword("require");
                writePunctuation("(");
                emitExpression(node.expression);
                writePunctuation(")");
            }
            //
            // JSX
            //
            function emitJsxElement(node) {
                emit(node.openingElement);
                emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */);
                emit(node.closingElement);
            }
            function emitJsxSelfClosingElement(node) {
                writePunctuation("<");
                emitJsxTagName(node.tagName);
                writeSpace();
                emit(node.attributes);
                writePunctuation("/>");
            }
            function emitJsxFragment(node) {
                emit(node.openingFragment);
                emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */);
                emit(node.closingFragment);
            }
            function emitJsxOpeningElementOrFragment(node) {
                writePunctuation("<");
                if (ts.isJsxOpeningElement(node)) {
                    emitJsxTagName(node.tagName);
                    if (node.attributes.properties && node.attributes.properties.length > 0) {
                        writeSpace();
                    }
                    emit(node.attributes);
                }
                writePunctuation(">");
            }
            function emitJsxText(node) {
                commitPendingSemicolon();
                writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
            }
            function emitJsxClosingElementOrFragment(node) {
                writePunctuation("</");
                if (ts.isJsxClosingElement(node)) {
                    emitJsxTagName(node.tagName);
                }
                writePunctuation(">");
            }
            function emitJsxAttributes(node) {
                emitList(node, node.properties, 131328 /* JsxElementAttributes */);
            }
            function emitJsxAttribute(node) {
                emit(node.name);
                emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217
            }
            function emitJsxSpreadAttribute(node) {
                writePunctuation("{...");
                emitExpression(node.expression);
                writePunctuation("}");
            }
            function emitJsxExpression(node) {
                if (node.expression) {
                    writePunctuation("{");
                    emit(node.dotDotDotToken);
                    emitExpression(node.expression);
                    writePunctuation("}");
                }
            }
            function emitJsxTagName(node) {
                if (node.kind === 71 /* Identifier */) {
                    emitExpression(node);
                }
                else {
                    emit(node);
                }
            }
            //
            // Clauses
            //
            function emitCaseClause(node) {
                emitTokenWithComment(73 /* CaseKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                emitExpression(node.expression);
                emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
            }
            function emitDefaultClause(node) {
                var pos = emitTokenWithComment(79 /* DefaultKeyword */, node.pos, writeKeyword, node);
                emitCaseOrDefaultClauseRest(node, node.statements, pos);
            }
            function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
                var emitAsSingleStatement = statements.length === 1 &&
                    (
                    // treat synthesized nodes as located on the same line for emit purposes
                    ts.nodeIsSynthesized(parentNode) ||
                        ts.nodeIsSynthesized(statements[0]) ||
                        ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
                var format = 81985 /* CaseOrDefaultClauseStatements */;
                if (emitAsSingleStatement) {
                    writeToken(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
                    writeSpace();
                    format &= ~(1 /* MultiLine */ | 64 /* Indented */);
                }
                else {
                    emitTokenWithComment(56 /* ColonToken */, colonPos, writePunctuation, parentNode);
                }
                emitList(parentNode, statements, format);
            }
            function emitHeritageClause(node) {
                writeSpace();
                writeTokenText(node.token, writeKeyword);
                writeSpace();
                emitList(node, node.types, 272 /* HeritageClauseTypes */);
            }
            function emitCatchClause(node) {
                var openParenPos = emitTokenWithComment(74 /* CatchKeyword */, node.pos, writeKeyword, node);
                writeSpace();
                if (node.variableDeclaration) {
                    emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node);
                    emit(node.variableDeclaration);
                    emitTokenWithComment(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
                    writeSpace();
                }
                emit(node.block);
            }
            //
            // Property assignments
            //
            function emitPropertyAssignment(node) {
                emit(node.name);
                writePunctuation(":");
                writeSpace();
                // This is to ensure that we emit comment in the following case:
                //      For example:
                //          obj = {
                //              id: /*comment1*/ ()=>void
                //          }
                // "comment1" is not considered to be leading comment for node.initializer
                // but rather a trailing comment on the previous node.
                var initializer = node.initializer;
                if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
                    var commentRange = ts.getCommentRange(initializer);
                    emitTrailingCommentsOfPosition(commentRange.pos);
                }
                emitExpression(initializer);
            }
            function emitShorthandPropertyAssignment(node) {
                emit(node.name);
                if (node.objectAssignmentInitializer) {
                    writeSpace();
                    writePunctuation("=");
                    writeSpace();
                    emitExpression(node.objectAssignmentInitializer);
                }
            }
            function emitSpreadAssignment(node) {
                if (node.expression) {
                    writePunctuation("...");
                    emitExpression(node.expression);
                }
            }
            //
            // Enum
            //
            function emitEnumMember(node) {
                emit(node.name);
                emitInitializer(node.initializer, node.name.end, node);
            }
            //
            // Top-level nodes
            //
            function emitSourceFile(node) {
                writeLine();
                var statements = node.statements;
                if (emitBodyWithDetachedComments) {
                    // Emit detached comment if there are no prologue directives or if the first node is synthesized.
                    // The synthesized node will have no leading comment so some comments may be missed.
                    var shouldEmitDetachedComment = statements.length === 0 ||
                        !ts.isPrologueDirective(statements[0]) ||
                        ts.nodeIsSynthesized(statements[0]);
                    if (shouldEmitDetachedComment) {
                        emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
                        return;
                    }
                }
                emitSourceFileWorker(node);
            }
            function emitSyntheticTripleSlashReferencesIfNeeded(node) {
                emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
            }
            function emitTripleSlashDirectivesIfNeeded(node) {
                if (node.isDeclarationFile)
                    emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
            }
            function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
                if (hasNoDefaultLib) {
                    write("/// <reference no-default-lib=\"true\"/>");
                    writeLine();
                }
                if (currentSourceFile && currentSourceFile.moduleName) {
                    write("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
                    writeLine();
                }
                if (currentSourceFile && currentSourceFile.amdDependencies) {
                    for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
                        var dep = _b[_a];
                        if (dep.name) {
                            write("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
                        }
                        else {
                            write("/// <amd-dependency path=\"" + dep.path + "\" />");
                        }
                        writeLine();
                    }
                }
                for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
                    var directive = files_1[_c];
                    write("/// <reference path=\"" + directive.fileName + "\" />");
                    writeLine();
                }
                for (var _d = 0, types_16 = types; _d < types_16.length; _d++) {
                    var directive = types_16[_d];
                    write("/// <reference types=\"" + directive.fileName + "\" />");
                    writeLine();
                }
                for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
                    var directive = libs_1[_e];
                    write("/// <reference lib=\"" + directive.fileName + "\" />");
                    writeLine();
                }
            }
            function emitSourceFileWorker(node) {
                var statements = node.statements;
                pushNameGenerationScope(node);
                ts.forEach(node.statements, generateNames);
                emitHelpers(node);
                var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
                emitTripleSlashDirectivesIfNeeded(node);
                emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
                popNameGenerationScope(node);
            }
            // Transformation nodes
            function emitPartiallyEmittedExpression(node) {
                emitExpression(node.expression);
            }
            function emitCommaList(node) {
                emitExpressionList(node, node.elements, 272 /* CommaListElements */);
            }
            /**
             * Emits any prologue directives at the start of a Statement list, returning the
             * number of prologue directives written to the output.
             */
            function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
                for (var i = 0; i < statements.length; i++) {
                    var statement = statements[i];
                    if (ts.isPrologueDirective(statement)) {
                        var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
                        if (shouldEmitPrologueDirective) {
                            if (startWithNewLine || i > 0) {
                                writeLine();
                            }
                            emit(statement);
                            if (seenPrologueDirectives) {
                                seenPrologueDirectives.set(statement.expression.text, true);
                            }
                        }
                    }
                    else {
                        // return index of the first non prologue directive
                        return i;
                    }
                }
                return statements.length;
            }
            function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
                if (ts.isSourceFile(sourceFileOrBundle)) {
                    setSourceFile(sourceFileOrBundle);
                    emitPrologueDirectives(sourceFileOrBundle.statements);
                }
                else {
                    var seenPrologueDirectives = ts.createMap();
                    for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
                        var sourceFile = _b[_a];
                        setSourceFile(sourceFile);
                        emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
                    }
                }
            }
            function emitShebangIfNeeded(sourceFileOrBundle) {
                if (ts.isSourceFile(sourceFileOrBundle)) {
                    var shebang = ts.getShebang(sourceFileOrBundle.text);
                    if (shebang) {
                        write(shebang);
                        writeLine();
                        return true;
                    }
                }
                else {
                    for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
                        var sourceFile = _b[_a];
                        // Emit only the first encountered shebang
                        if (emitShebangIfNeeded(sourceFile)) {
                            break;
                        }
                    }
                }
            }
            //
            // Helpers
            //
            function emitNodeWithWriter(node, writer) {
                if (!node)
                    return;
                var savedWrite = write;
                write = writer;
                emit(node);
                write = savedWrite;
            }
            function emitModifiers(node, modifiers) {
                if (modifiers && modifiers.length) {
                    emitList(node, modifiers, 131328 /* Modifiers */);
                    writeSpace();
                }
            }
            function emitTypeAnnotation(node) {
                if (node) {
                    writePunctuation(":");
                    writeSpace();
                    emit(node);
                }
            }
            function emitInitializer(node, equalCommentStartPos, container) {
                if (node) {
                    writeSpace();
                    emitTokenWithComment(58 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
                    writeSpace();
                    emitExpression(node);
                }
            }
            function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
                if (node) {
                    prefixWriter(prefix);
                    emit(node);
                }
            }
            function emitWithLeadingSpace(node) {
                if (node) {
                    writeSpace();
                    emit(node);
                }
            }
            function emitExpressionWithLeadingSpace(node) {
                if (node) {
                    writeSpace();
                    emitExpression(node);
                }
            }
            function emitWithTrailingSpace(node) {
                if (node) {
                    emit(node);
                    writeSpace();
                }
            }
            function emitEmbeddedStatement(parent, node) {
                if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
                    writeSpace();
                    emit(node);
                }
                else {
                    writeLine();
                    increaseIndent();
                    emit(node);
                    decreaseIndent();
                }
            }
            function emitDecorators(parentNode, decorators) {
                emitList(parentNode, decorators, 24577 /* Decorators */);
            }
            function emitTypeArguments(parentNode, typeArguments) {
                emitList(parentNode, typeArguments, 26896 /* TypeArguments */);
            }
            function emitTypeParameters(parentNode, typeParameters) {
                if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
                    return emitTypeArguments(parentNode, parentNode.typeArguments);
                }
                emitList(parentNode, typeParameters, 26896 /* TypeParameters */);
            }
            function emitParameters(parentNode, parameters) {
                emitList(parentNode, parameters, 1296 /* Parameters */);
            }
            function canEmitSimpleArrowHead(parentNode, parameters) {
                var parameter = ts.singleOrUndefined(parameters);
                return parameter
                    && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
                    && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
                    && !parentNode.type // arrow function may not have return type annotation
                    && !ts.some(parentNode.decorators) // parent may not have decorators
                    && !ts.some(parentNode.modifiers) // parent may not have modifiers
                    && !ts.some(parentNode.typeParameters) // parent may not have type parameters
                    && !ts.some(parameter.decorators) // parameter may not have decorators
                    && !ts.some(parameter.modifiers) // parameter may not have modifiers
                    && !parameter.dotDotDotToken // parameter may not be rest
                    && !parameter.questionToken // parameter may not be optional
                    && !parameter.type // parameter may not have a type annotation
                    && !parameter.initializer // parameter may not have an initializer
                    && ts.isIdentifier(parameter.name); // parameter name must be identifier
            }
            function emitParametersForArrow(parentNode, parameters) {
                if (canEmitSimpleArrowHead(parentNode, parameters)) {
                    emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */);
                }
                else {
                    emitParameters(parentNode, parameters);
                }
            }
            function emitParametersForIndexSignature(parentNode, parameters) {
                emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */);
            }
            function emitList(parentNode, children, format, start, count) {
                emitNodeList(emit, parentNode, children, format, start, count);
            }
            function emitExpressionList(parentNode, children, format, start, count) {
                emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
            }
            function writeDelimiter(format) {
                switch (format & 28 /* DelimitersMask */) {
                    case 0 /* None */:
                        break;
                    case 16 /* CommaDelimited */:
                        writePunctuation(",");
                        break;
                    case 4 /* BarDelimited */:
                        writeSpace();
                        writePunctuation("|");
                        break;
                    case 8 /* AmpersandDelimited */:
                        writeSpace();
                        writePunctuation("&");
                        break;
                }
            }
            function emitNodeList(emit, parentNode, children, format, start, count) {
                if (start === void 0) {
                    start = 0;
                }
                if (count === void 0) {
                    count = children ? children.length - start : 0;
                }
                var isUndefined = children === undefined;
                if (isUndefined && format & 8192 /* OptionalIfUndefined */) {
                    return;
                }
                var isEmpty = children === undefined || start >= children.length || count === 0;
                if (isEmpty && format & 16384 /* OptionalIfEmpty */) {
                    if (onBeforeEmitNodeArray) {
                        onBeforeEmitNodeArray(children);
                    }
                    if (onAfterEmitNodeArray) {
                        onAfterEmitNodeArray(children);
                    }
                    return;
                }
                if (format & 7680 /* BracketsMask */) {
                    writePunctuation(getOpeningBracket(format));
                    if (isEmpty && !isUndefined) {
                        // TODO: GH#18217
                        emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
                    }
                }
                if (onBeforeEmitNodeArray) {
                    onBeforeEmitNodeArray(children);
                }
                if (isEmpty) {
                    // Write a line terminator if the parent node was multi-line
                    if (format & 1 /* MultiLine */) {
                        writeLine();
                    }
                    else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) {
                        writeSpace();
                    }
                }
                else {
                    // Write the opening line terminator or leading whitespace.
                    var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0;
                    var shouldEmitInterveningComments = mayEmitInterveningComments;
                    if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217
                        writeLine();
                        shouldEmitInterveningComments = false;
                    }
                    else if (format & 128 /* SpaceBetweenBraces */) {
                        writeSpace();
                    }
                    // Increase the indent, if requested.
                    if (format & 64 /* Indented */) {
                        increaseIndent();
                    }
                    // Emit each child.
                    var previousSibling = void 0;
                    var shouldDecreaseIndentAfterEmit = false;
                    for (var i = 0; i < count; i++) {
                        var child = children[start + i];
                        // Write the delimiter if this is not the first node.
                        if (previousSibling) {
                            // i.e
                            //      function commentedParameters(
                            //          /* Parameter a */
                            //          a
                            //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
                            //          ,
                            if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
                                emitLeadingCommentsOfPosition(previousSibling.end);
                            }
                            writeDelimiter(format);
                            // Write either a line terminator or whitespace to separate the elements.
                            if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
                                // If a synthesized node in a single-line list starts on a new
                                // line, we should increase the indent.
                                if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) {
                                    increaseIndent();
                                    shouldDecreaseIndentAfterEmit = true;
                                }
                                writeLine();
                                shouldEmitInterveningComments = false;
                            }
                            else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) {
                                writeSpace();
                            }
                        }
                        // Emit this child.
                        if (shouldEmitInterveningComments) {
                            if (emitTrailingCommentsOfPosition) {
                                var commentRange = ts.getCommentRange(child);
                                emitTrailingCommentsOfPosition(commentRange.pos);
                            }
                        }
                        else {
                            shouldEmitInterveningComments = mayEmitInterveningComments;
                        }
                        emit(child);
                        if (shouldDecreaseIndentAfterEmit) {
                            decreaseIndent();
                            shouldDecreaseIndentAfterEmit = false;
                        }
                        previousSibling = child;
                    }
                    // Write a trailing comma, if requested.
                    var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma;
                    if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
                        writePunctuation(",");
                    }
                    // Emit any trailing comment of the last element in the list
                    // i.e
                    //       var array = [...
                    //          2
                    //          /* end of element 2 */
                    //       ];
                    if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
                        emitLeadingCommentsOfPosition(previousSibling.end);
                    }
                    // Decrease the indent, if requested.
                    if (format & 64 /* Indented */) {
                        decreaseIndent();
                    }
                    // Write the closing line terminator or closing whitespace.
                    if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
                        writeLine();
                    }
                    else if (format & 128 /* SpaceBetweenBraces */) {
                        writeSpace();
                    }
                }
                if (onAfterEmitNodeArray) {
                    onAfterEmitNodeArray(children);
                }
                if (format & 7680 /* BracketsMask */) {
                    if (isEmpty && !isUndefined) {
                        // TODO: GH#18217
                        emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
                    }
                    writePunctuation(getClosingBracket(format));
                }
            }
            function commitPendingSemicolonInternal() {
                if (pendingSemicolon) {
                    writeSemicolonInternal();
                    pendingSemicolon = false;
                }
            }
            function writeLiteral(s) {
                commitPendingSemicolon();
                writer.writeLiteral(s);
            }
            function writeStringLiteral(s) {
                commitPendingSemicolon();
                writer.writeStringLiteral(s);
            }
            function writeBase(s) {
                commitPendingSemicolon();
                writer.write(s);
            }
            function writeSymbol(s, sym) {
                commitPendingSemicolon();
                writer.writeSymbol(s, sym);
            }
            function writePunctuation(s) {
                commitPendingSemicolon();
                writer.writePunctuation(s);
            }
            function deferWriteSemicolon() {
                pendingSemicolon = true;
            }
            function writeSemicolonInternal() {
                writer.writePunctuation(";");
            }
            function writeKeyword(s) {
                commitPendingSemicolon();
                writer.writeKeyword(s);
            }
            function writeOperator(s) {
                commitPendingSemicolon();
                writer.writeOperator(s);
            }
            function writeParameter(s) {
                commitPendingSemicolon();
                writer.writeParameter(s);
            }
            function writeSpace() {
                commitPendingSemicolon();
                writer.writeSpace(" ");
            }
            function writeProperty(s) {
                commitPendingSemicolon();
                writer.writeProperty(s);
            }
            function writeLine() {
                commitPendingSemicolon();
                writer.writeLine();
            }
            function increaseIndent() {
                commitPendingSemicolon();
                writer.increaseIndent();
            }
            function decreaseIndent() {
                commitPendingSemicolon();
                writer.decreaseIndent();
            }
            function writeToken(token, pos, writer, contextNode) {
                return onEmitSourceMapOfToken
                    ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText)
                    : writeTokenText(token, writer, pos);
            }
            function writeTokenNode(node, writer) {
                if (onBeforeEmitToken) {
                    onBeforeEmitToken(node);
                }
                writer(ts.tokenToString(node.kind));
                if (onAfterEmitToken) {
                    onAfterEmitToken(node);
                }
            }
            function writeTokenText(token, writer, pos) {
                var tokenString = ts.tokenToString(token);
                writer(tokenString);
                return pos < 0 ? pos : pos + tokenString.length;
            }
            function writeLineOrSpace(node) {
                if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
                    writeSpace();
                }
                else {
                    writeLine();
                }
            }
            function writeLines(text) {
                var lines = text.split(/\r\n?|\n/g);
                var indentation = ts.guessIndentation(lines);
                for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
                    var lineText = lines_2[_a];
                    var line = indentation ? lineText.slice(indentation) : lineText;
                    if (line.length) {
                        writeLine();
                        write(line);
                        writeLine();
                    }
                }
            }
            function increaseIndentIf(value, valueToWriteWhenNotIndenting) {
                if (value) {
                    increaseIndent();
                    writeLine();
                }
                else if (valueToWriteWhenNotIndenting) {
                    write(valueToWriteWhenNotIndenting);
                }
            }
            // Helper function to decrease the indent if we previously indented.  Allows multiple
            // previous indent values to be considered at a time.  This also allows caller to just
            // call this once, passing in all their appropriate indent values, instead of needing
            // to call this helper function multiple times.
            function decreaseIndentIf(value1, value2) {
                if (value1) {
                    decreaseIndent();
                }
                if (value2) {
                    decreaseIndent();
                }
            }
            function shouldWriteLeadingLineTerminator(parentNode, children, format) {
                if (format & 1 /* MultiLine */) {
                    return true;
                }
                if (format & 2 /* PreserveLines */) {
                    if (format & 32768 /* PreferNewLine */) {
                        return true;
                    }
                    var firstChild = children[0];
                    if (firstChild === undefined) {
                        return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile);
                    }
                    else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) {
                        return synthesizedNodeStartsOnNewLine(firstChild, format);
                    }
                    else {
                        return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile);
                    }
                }
                else {
                    return false;
                }
            }
            function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) {
                if (format & 1 /* MultiLine */) {
                    return true;
                }
                else if (format & 2 /* PreserveLines */) {
                    if (previousNode === undefined || nextNode === undefined) {
                        return false;
                    }
                    else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) {
                        return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format);
                    }
                    else {
                        return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile);
                    }
                }
                else {
                    return ts.getStartsOnNewLine(nextNode);
                }
            }
            function shouldWriteClosingLineTerminator(parentNode, children, format) {
                if (format & 1 /* MultiLine */) {
                    return (format & 65536 /* NoTrailingNewLine */) === 0;
                }
                else if (format & 2 /* PreserveLines */) {
                    if (format & 32768 /* PreferNewLine */) {
                        return true;
                    }
                    var lastChild = ts.lastOrUndefined(children);
                    if (lastChild === undefined) {
                        return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile);
                    }
                    else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) {
                        return synthesizedNodeStartsOnNewLine(lastChild, format);
                    }
                    else {
                        return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile);
                    }
                }
                else {
                    return false;
                }
            }
            function synthesizedNodeStartsOnNewLine(node, format) {
                if (ts.nodeIsSynthesized(node)) {
                    var startsOnNewLine = ts.getStartsOnNewLine(node);
                    if (startsOnNewLine === undefined) {
                        return (format & 32768 /* PreferNewLine */) !== 0;
                    }
                    return startsOnNewLine;
                }
                return (format & 32768 /* PreferNewLine */) !== 0;
            }
            function needsIndentation(parent, node1, node2) {
                parent = skipSynthesizedParentheses(parent);
                node1 = skipSynthesizedParentheses(node1);
                node2 = skipSynthesizedParentheses(node2);
                // Always use a newline for synthesized code if the synthesizer desires it.
                if (ts.getStartsOnNewLine(node2)) {
                    return true;
                }
                return !ts.nodeIsSynthesized(parent)
                    && !ts.nodeIsSynthesized(node1)
                    && !ts.nodeIsSynthesized(node2)
                    && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile);
            }
            function isEmptyBlock(block) {
                return block.statements.length === 0
                    && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
            }
            function skipSynthesizedParentheses(node) {
                while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
                    node = node.expression;
                }
                return node;
            }
            function getTextOfNode(node, includeTrivia) {
                if (ts.isGeneratedIdentifier(node)) {
                    return generateName(node);
                }
                else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
                    return ts.idText(node);
                }
                else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) {
                    return getTextOfNode(node.textSourceNode, includeTrivia);
                }
                else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
                    return node.text;
                }
                return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
            }
            function getLiteralTextOfNode(node, neverAsciiEscape) {
                if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) {
                    var textSourceNode = node.textSourceNode;
                    if (ts.isIdentifier(textSourceNode)) {
                        return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ?
                            "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
                            "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
                    }
                    else {
                        return getLiteralTextOfNode(textSourceNode, neverAsciiEscape);
                    }
                }
                return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape);
            }
            /**
             * Push a new name generation scope.
             */
            function pushNameGenerationScope(node) {
                if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
                    return;
                }
                tempFlagsStack.push(tempFlags);
                tempFlags = 0;
                reservedNamesStack.push(reservedNames);
            }
            /**
             * Pop the current name generation scope.
             */
            function popNameGenerationScope(node) {
                if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
                    return;
                }
                tempFlags = tempFlagsStack.pop();
                reservedNames = reservedNamesStack.pop();
            }
            function reserveNameInNestedScopes(name) {
                if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
                    reservedNames = ts.createMap();
                }
                reservedNames.set(name, true);
            }
            function generateNames(node) {
                if (!node)
                    return;
                switch (node.kind) {
                    case 216 /* Block */:
                        ts.forEach(node.statements, generateNames);
                        break;
                    case 231 /* LabeledStatement */:
                    case 229 /* WithStatement */:
                    case 221 /* DoStatement */:
                    case 222 /* WhileStatement */:
                        generateNames(node.statement);
                        break;
                    case 220 /* IfStatement */:
                        generateNames(node.thenStatement);
                        generateNames(node.elseStatement);
                        break;
                    case 223 /* ForStatement */:
                    case 225 /* ForOfStatement */:
                    case 224 /* ForInStatement */:
                        generateNames(node.initializer);
                        generateNames(node.statement);
                        break;
                    case 230 /* SwitchStatement */:
                        generateNames(node.caseBlock);
                        break;
                    case 244 /* CaseBlock */:
                        ts.forEach(node.clauses, generateNames);
                        break;
                    case 269 /* CaseClause */:
                    case 270 /* DefaultClause */:
                        ts.forEach(node.statements, generateNames);
                        break;
                    case 233 /* TryStatement */:
                        generateNames(node.tryBlock);
                        generateNames(node.catchClause);
                        generateNames(node.finallyBlock);
                        break;
                    case 272 /* CatchClause */:
                        generateNames(node.variableDeclaration);
                        generateNames(node.block);
                        break;
                    case 217 /* VariableStatement */:
                        generateNames(node.declarationList);
                        break;
                    case 236 /* VariableDeclarationList */:
                        ts.forEach(node.declarations, generateNames);
                        break;
                    case 235 /* VariableDeclaration */:
                    case 149 /* Parameter */:
                    case 184 /* BindingElement */:
                    case 238 /* ClassDeclaration */:
                        generateNameIfNeeded(node.name);
                        break;
                    case 237 /* FunctionDeclaration */:
                        generateNameIfNeeded(node.name);
                        if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
                            ts.forEach(node.parameters, generateNames);
                            generateNames(node.body);
                        }
                        break;
                    case 182 /* ObjectBindingPattern */:
                    case 183 /* ArrayBindingPattern */:
                        ts.forEach(node.elements, generateNames);
                        break;
                    case 247 /* ImportDeclaration */:
                        generateNames(node.importClause);
                        break;
                    case 248 /* ImportClause */:
                        generateNameIfNeeded(node.name);
                        generateNames(node.namedBindings);
                        break;
                    case 249 /* NamespaceImport */:
                        generateNameIfNeeded(node.name);
                        break;
                    case 250 /* NamedImports */:
                        ts.forEach(node.elements, generateNames);
                        break;
                    case 251 /* ImportSpecifier */:
                        generateNameIfNeeded(node.propertyName || node.name);
                        break;
                }
            }
            function generateMemberNames(node) {
                if (!node)
                    return;
                switch (node.kind) {
                    case 273 /* PropertyAssignment */:
                    case 274 /* ShorthandPropertyAssignment */:
                    case 152 /* PropertyDeclaration */:
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        generateNameIfNeeded(node.name);
                        break;
                }
            }
            function generateNameIfNeeded(name) {
                if (name) {
                    if (ts.isGeneratedIdentifier(name)) {
                        generateName(name);
                    }
                    else if (ts.isBindingPattern(name)) {
                        generateNames(name);
                    }
                }
            }
            /**
             * Generate the text for a generated identifier.
             */
            function generateName(name) {
                if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
                    // Node names generate unique names based on their original node
                    // and are cached based on that node's id.
                    return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
                }
                else {
                    // Auto, Loop, and Unique names are cached based on their unique
                    // autoGenerateId.
                    var autoGenerateId = name.autoGenerateId;
                    return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
                }
            }
            function generateNameCached(node, flags) {
                var nodeId = ts.getNodeId(node);
                return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
            }
            /**
             * Returns a value indicating whether a name is unique globally, within the current file,
             * or within the NameGenerator.
             */
            function isUniqueName(name) {
                return isFileLevelUniqueName(name)
                    && !generatedNames.has(name)
                    && !(reservedNames && reservedNames.has(name));
            }
            /**
             * Returns a value indicating whether a name is unique globally or within the current file.
             */
            function isFileLevelUniqueName(name) {
                return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
            }
            /**
             * Returns a value indicating whether a name is unique within a container.
             */
            function isUniqueLocalName(name, container) {
                for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
                    if (node.locals) {
                        var local = node.locals.get(ts.escapeLeadingUnderscores(name));
                        // We conservatively include alias symbols to cover cases where they're emitted as locals
                        if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
                            return false;
                        }
                    }
                }
                return true;
            }
            /**
             * Return the next available name in the pattern _a ... _z, _0, _1, ...
             * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
             * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
             */
            function makeTempVariableName(flags, reservedInNestedScopes) {
                if (flags && !(tempFlags & flags)) {
                    var name = flags === 268435456 /* _i */ ? "_i" : "_n";
                    if (isUniqueName(name)) {
                        tempFlags |= flags;
                        if (reservedInNestedScopes) {
                            reserveNameInNestedScopes(name);
                        }
                        return name;
                    }
                }
                while (true) {
                    var count = tempFlags & 268435455 /* CountMask */;
                    tempFlags++;
                    // Skip over 'i' and 'n'
                    if (count !== 8 && count !== 13) {
                        var name = count < 26
                            ? "_" + String.fromCharCode(97 /* a */ + count)
                            : "_" + (count - 26);
                        if (isUniqueName(name)) {
                            if (reservedInNestedScopes) {
                                reserveNameInNestedScopes(name);
                            }
                            return name;
                        }
                    }
                }
            }
            /**
             * Generate a name that is unique within the current file and doesn't conflict with any names
             * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
             * where n is a positive integer. Note that names generated by makeTempVariableName and
             * makeUniqueName are guaranteed to never conflict.
             * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
             */
            function makeUniqueName(baseName, checkFn, optimistic, scoped) {
                if (checkFn === void 0) {
                    checkFn = isUniqueName;
                }
                if (optimistic) {
                    if (checkFn(baseName)) {
                        if (scoped) {
                            reserveNameInNestedScopes(baseName);
                        }
                        else {
                            generatedNames.set(baseName, true);
                        }
                        return baseName;
                    }
                }
                // Find the first unique 'name_n', where n is a positive number
                if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
                    baseName += "_";
                }
                var i = 1;
                while (true) {
                    var generatedName = baseName + i;
                    if (checkFn(generatedName)) {
                        if (scoped) {
                            reserveNameInNestedScopes(generatedName);
                        }
                        else {
                            generatedNames.set(generatedName, true);
                        }
                        return generatedName;
                    }
                    i++;
                }
            }
            function makeFileLevelOptimisticUniqueName(name) {
                return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
            }
            /**
             * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
             */
            function generateNameForModuleOrEnum(node) {
                var name = getTextOfNode(node.name);
                // Use module/enum name itself if it is unique, otherwise make a unique variation
                return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
            }
            /**
             * Generates a unique name for an ImportDeclaration or ExportDeclaration.
             */
            function generateNameForImportOrExportDeclaration(node) {
                var expr = ts.getExternalModuleName(node); // TODO: GH#18217
                var baseName = ts.isStringLiteral(expr) ?
                    ts.makeIdentifierFromModuleName(expr.text) : "module";
                return makeUniqueName(baseName);
            }
            /**
             * Generates a unique name for a default export.
             */
            function generateNameForExportDefault() {
                return makeUniqueName("default");
            }
            /**
             * Generates a unique name for a class expression.
             */
            function generateNameForClassExpression() {
                return makeUniqueName("class");
            }
            function generateNameForMethodOrAccessor(node) {
                if (ts.isIdentifier(node.name)) {
                    return generateNameCached(node.name);
                }
                return makeTempVariableName(0 /* Auto */);
            }
            /**
             * Generates a unique name from a node.
             */
            function generateNameForNode(node, flags) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
                    case 242 /* ModuleDeclaration */:
                    case 241 /* EnumDeclaration */:
                        return generateNameForModuleOrEnum(node);
                    case 247 /* ImportDeclaration */:
                    case 253 /* ExportDeclaration */:
                        return generateNameForImportOrExportDeclaration(node);
                    case 237 /* FunctionDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 252 /* ExportAssignment */:
                        return generateNameForExportDefault();
                    case 207 /* ClassExpression */:
                        return generateNameForClassExpression();
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return generateNameForMethodOrAccessor(node);
                    default:
                        return makeTempVariableName(0 /* Auto */);
                }
            }
            /**
             * Generates a unique identifier for a node.
             */
            function makeName(name) {
                switch (name.autoGenerateFlags & 7 /* KindMask */) {
                    case 1 /* Auto */:
                        return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
                    case 2 /* Loop */:
                        return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
                    case 3 /* Unique */:
                        return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
                }
                return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
            }
            /**
             * Gets the node from which a name should be generated.
             */
            function getNodeForGeneratedName(name) {
                var autoGenerateId = name.autoGenerateId;
                var node = name;
                var original = node.original;
                while (original) {
                    node = original;
                    // if "node" is a different generated name (having a different
                    // "autoGenerateId"), use it and stop traversing.
                    if (ts.isIdentifier(node)
                        && !!(node.autoGenerateFlags & 4 /* Node */)
                        && node.autoGenerateId !== autoGenerateId) {
                        break;
                    }
                    original = node.original;
                }
                // otherwise, return the original node for the source;
                return node;
            }
        }
        ts.createPrinter = createPrinter;
        function createBracketsMap() {
            var brackets = [];
            brackets[512 /* Braces */] = ["{", "}"];
            brackets[1024 /* Parenthesis */] = ["(", ")"];
            brackets[2048 /* AngleBrackets */] = ["<", ">"];
            brackets[4096 /* SquareBrackets */] = ["[", "]"];
            return brackets;
        }
        function getOpeningBracket(format) {
            return brackets[format & 7680 /* BracketsMask */][0];
        }
        function getClosingBracket(format) {
            return brackets[format & 7680 /* BracketsMask */][1];
        }
        // Flags enum to track count of temp variables and a few dedicated names
        var TempFlags;
        (function (TempFlags) {
            TempFlags[TempFlags["Auto"] = 0] = "Auto";
            TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
            TempFlags[TempFlags["_i"] = 268435456] = "_i";
        })(TempFlags || (TempFlags = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
            if (!host.getDirectories || !host.readDirectory) {
                return undefined;
            }
            var cachedReadDirectoryResult = ts.createMap();
            var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
            return {
                useCaseSensitiveFileNames: useCaseSensitiveFileNames,
                fileExists: fileExists,
                readFile: function (path, encoding) { return host.readFile(path, encoding); },
                directoryExists: host.directoryExists && directoryExists,
                getDirectories: getDirectories,
                readDirectory: readDirectory,
                createDirectory: host.createDirectory && createDirectory,
                writeFile: host.writeFile && writeFile,
                addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
                addOrDeleteFile: addOrDeleteFile,
                clearCache: clearCache
            };
            function toPath(fileName) {
                return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
            }
            function getCachedFileSystemEntries(rootDirPath) {
                return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
            }
            function getCachedFileSystemEntriesForBaseDir(path) {
                return getCachedFileSystemEntries(ts.getDirectoryPath(path));
            }
            function getBaseNameOfFileName(fileName) {
                return ts.getBaseFileName(ts.normalizePath(fileName));
            }
            function createCachedFileSystemEntries(rootDir, rootDirPath) {
                var resultFromHost = {
                    files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
                    directories: host.getDirectories(rootDir) || []
                };
                cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
                return resultFromHost;
            }
            /**
             * If the readDirectory result was already cached, it returns that
             * Otherwise gets result from host and caches it.
             * The host request is done under try catch block to avoid caching incorrect result
             */
            function tryReadDirectory(rootDir, rootDirPath) {
                rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
                var cachedResult = getCachedFileSystemEntries(rootDirPath);
                if (cachedResult) {
                    return cachedResult;
                }
                try {
                    return createCachedFileSystemEntries(rootDir, rootDirPath);
                }
                catch (_e) {
                    // If there is exception to read directories, dont cache the result and direct the calls to host
                    ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
                    return undefined;
                }
            }
            function fileNameEqual(name1, name2) {
                return getCanonicalFileName(name1) === getCanonicalFileName(name2);
            }
            function hasEntry(entries, name) {
                return ts.some(entries, function (file) { return fileNameEqual(file, name); });
            }
            function updateFileSystemEntry(entries, baseName, isValid) {
                if (hasEntry(entries, baseName)) {
                    if (!isValid) {
                        return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
                    }
                }
                else if (isValid) {
                    return entries.push(baseName);
                }
            }
            function writeFile(fileName, data, writeByteOrderMark) {
                var path = toPath(fileName);
                var result = getCachedFileSystemEntriesForBaseDir(path);
                if (result) {
                    updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
                }
                return host.writeFile(fileName, data, writeByteOrderMark);
            }
            function fileExists(fileName) {
                var path = toPath(fileName);
                var result = getCachedFileSystemEntriesForBaseDir(path);
                return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
                    host.fileExists(fileName);
            }
            function directoryExists(dirPath) {
                var path = toPath(dirPath);
                return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
            }
            function createDirectory(dirPath) {
                var path = toPath(dirPath);
                var result = getCachedFileSystemEntriesForBaseDir(path);
                var baseFileName = getBaseNameOfFileName(dirPath);
                if (result) {
                    updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
                }
                host.createDirectory(dirPath);
            }
            function getDirectories(rootDir) {
                var rootDirPath = toPath(rootDir);
                var result = tryReadDirectory(rootDir, rootDirPath);
                if (result) {
                    return result.directories.slice();
                }
                return host.getDirectories(rootDir);
            }
            function readDirectory(rootDir, extensions, excludes, includes, depth) {
                var rootDirPath = toPath(rootDir);
                var result = tryReadDirectory(rootDir, rootDirPath);
                if (result) {
                    return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
                }
                return host.readDirectory(rootDir, extensions, excludes, includes, depth);
                function getFileSystemEntries(dir) {
                    var path = toPath(dir);
                    if (path === rootDirPath) {
                        return result;
                    }
                    return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
                }
            }
            function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
                var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
                if (existingResult) {
                    // Just clear the cache for now
                    // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
                    clearCache();
                    return undefined;
                }
                var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
                if (!parentResult) {
                    return undefined;
                }
                // This was earlier a file (hence not in cached directory contents)
                // or we never cached the directory containing it
                if (!host.directoryExists) {
                    // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
                    clearCache();
                    return undefined;
                }
                var baseName = getBaseNameOfFileName(fileOrDirectory);
                var fsQueryResult = {
                    fileExists: host.fileExists(fileOrDirectoryPath),
                    directoryExists: host.directoryExists(fileOrDirectoryPath)
                };
                if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
                    // Folder added or removed, clear the cache instead of updating the folder and its structure
                    clearCache();
                }
                else {
                    // No need to update the directory structure, just files
                    updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
                }
                return fsQueryResult;
            }
            function addOrDeleteFile(fileName, filePath, eventKind) {
                if (eventKind === ts.FileWatcherEventKind.Changed) {
                    return;
                }
                var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
                if (parentResult) {
                    updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
                }
            }
            function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
                updateFileSystemEntry(parentResult.files, baseName, fileExists);
            }
            function clearCache() {
                cachedReadDirectoryResult.clear();
            }
        }
        ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
        var ConfigFileProgramReloadLevel;
        (function (ConfigFileProgramReloadLevel) {
            ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
            /** Update the file name list from the disk */
            ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
            /** Reload completely by re-reading contents of config file from disk and updating program */
            ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
        })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
        /**
         * Updates the existing missing file watches with the new set of missing files after new program is created
         */
        function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
            var missingFilePaths = program.getMissingFilePaths();
            var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
            // Update the missing file paths watcher
            ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
                // Watch the missing files
                createNewValue: createMissingFileWatch,
                // Files that are no longer missing (e.g. because they are no longer required)
                // should no longer be watched.
                onDeleteValue: ts.closeFileWatcher
            });
        }
        ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
        /**
         * Updates the existing wild card directory watches with the new set of wild card directories from the config file
         * after new program is created because the config file was reloaded or program was created first time from the config file
         * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
         * as wildcard directories wont change unless reloading config file
         */
        function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
            ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
                // Create new watch and recursive info
                createNewValue: createWildcardDirectoryWatcher,
                // Close existing watch thats not needed any more
                onDeleteValue: closeFileWatcherOf,
                // Close existing watch that doesnt match in the flags
                onExistingValue: updateWildcardDirectoryWatcher
            });
            function createWildcardDirectoryWatcher(directory, flags) {
                // Create new watch and recursive info
                return {
                    watcher: watchDirectory(directory, flags),
                    flags: flags
                };
            }
            function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
                // Watcher needs to be updated if the recursive flags dont match
                if (existingWatcher.flags === flags) {
                    return;
                }
                existingWatcher.watcher.close();
                existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
            }
        }
        ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
        function isEmittedFileOfProgram(program, file) {
            if (!program) {
                return false;
            }
            return program.isEmittedFile(file);
        }
        ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
        var WatchLogLevel;
        (function (WatchLogLevel) {
            WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
            WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
            WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
        })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
        function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
            return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
        }
        ts.getWatchFactory = getWatchFactory;
        function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
            var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
            var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
            var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
            return {
                watchFile: function (host, file, callback, pollingInterval, detailInfo1, detailInfo2) {
                    return createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
                },
                watchFilePath: function (host, file, callback, pollingInterval, path, detailInfo1, detailInfo2) {
                    return createFilePathWatcher(host, file, callback, pollingInterval, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
                },
                watchDirectory: function (host, directory, callback, flags, detailInfo1, detailInfo2) {
                    return createDirectoryWatcher(host, directory, callback, flags, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
                }
            };
            function watchFilePath(host, file, callback, pollingInterval, path) {
                return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval);
            }
        }
        function watchFile(host, file, callback, pollingInterval) {
            return host.watchFile(file, callback, pollingInterval);
        }
        function watchDirectory(host, directory, callback, flags) {
            return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0);
        }
        function getCreateFileWatcher(watchLogLevel, addWatch) {
            switch (watchLogLevel) {
                case WatchLogLevel.None:
                    return addWatch;
                case WatchLogLevel.TriggerOnly:
                    return createFileWatcherWithTriggerLogging;
                case WatchLogLevel.Verbose:
                    return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
            }
        }
        function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
            log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo));
            var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
            return {
                close: function () {
                    log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo));
                    watcher.close();
                }
            };
        }
        function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
            var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo);
            log(watchInfo);
            var start = ts.timestamp();
            var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
            var elapsed = ts.timestamp() - start;
            log("Elapsed:: " + elapsed + "ms " + watchInfo);
            return {
                close: function () {
                    var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo);
                    log(watchInfo);
                    var start = ts.timestamp();
                    watcher.close();
                    var elapsed = ts.timestamp() - start;
                    log("Elapsed:: " + elapsed + "ms " + watchInfo);
                }
            };
        }
        function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
            return addWatch(host, file, function (fileName, cbOptional) {
                var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo);
                log(triggerredInfo);
                var start = ts.timestamp();
                cb(fileName, cbOptional, passThrough);
                var elapsed = ts.timestamp() - start;
                log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
            }, flags);
        }
        function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) {
            return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1);
        }
        function closeFileWatcherOf(objWithWatcher) {
            objWithWatcher.watcher.close();
        }
        ts.closeFileWatcherOf = closeFileWatcherOf;
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/;
        function findConfigFile(searchPath, fileExists, configName) {
            if (configName === void 0) {
                configName = "tsconfig.json";
            }
            return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
                var fileName = ts.combinePaths(ancestor, configName);
                return fileExists(fileName) ? fileName : undefined;
            });
        }
        ts.findConfigFile = findConfigFile;
        function resolveTripleslashReference(moduleName, containingFile) {
            var basePath = ts.getDirectoryPath(containingFile);
            var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
            return ts.normalizePath(referencedFileName);
        }
        ts.resolveTripleslashReference = resolveTripleslashReference;
        /* @internal */
        function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
            var commonPathComponents;
            var failed = ts.forEach(fileNames, function (sourceFile) {
                // Each file contributes into common source file path
                var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
                sourcePathComponents.pop(); // The base file name is not part of the common directory path
                if (!commonPathComponents) {
                    // first file
                    commonPathComponents = sourcePathComponents;
                    return;
                }
                var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
                for (var i = 0; i < n; i++) {
                    if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
                        if (i === 0) {
                            // Failed to find any common path component
                            return true;
                        }
                        // New common path found that is 0 -> i-1
                        commonPathComponents.length = i;
                        break;
                    }
                }
                // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
                if (sourcePathComponents.length < commonPathComponents.length) {
                    commonPathComponents.length = sourcePathComponents.length;
                }
            });
            // A common path can not be found when paths span multiple drives on windows, for example
            if (failed) {
                return "";
            }
            if (!commonPathComponents) { // Can happen when all input files are .d.ts files
                return currentDirectory;
            }
            return ts.getPathFromPathComponents(commonPathComponents);
        }
        ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
        function createCompilerHost(options, setParentNodes) {
            return createCompilerHostWorker(options, setParentNodes);
        }
        ts.createCompilerHost = createCompilerHost;
        /*@internal*/
        // TODO(shkamat): update this after reworking ts build API
        function createCompilerHostWorker(options, setParentNodes, system) {
            if (system === void 0) {
                system = ts.sys;
            }
            var existingDirectories = ts.createMap();
            function getCanonicalFileName(fileName) {
                // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
                // otherwise use toLowerCase as a canonical form.
                return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
            }
            function getSourceFile(fileName, languageVersion, onError) {
                var text;
                try {
                    ts.performance.mark("beforeIORead");
                    text = system.readFile(fileName, options.charset);
                    ts.performance.mark("afterIORead");
                    ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
                }
                catch (e) {
                    if (onError) {
                        onError(e.message);
                    }
                    text = "";
                }
                return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
            }
            function directoryExists(directoryPath) {
                if (existingDirectories.has(directoryPath)) {
                    return true;
                }
                if (system.directoryExists(directoryPath)) {
                    existingDirectories.set(directoryPath, true);
                    return true;
                }
                return false;
            }
            function ensureDirectoriesExist(directoryPath) {
                if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
                    var parentDirectory = ts.getDirectoryPath(directoryPath);
                    ensureDirectoriesExist(parentDirectory);
                    system.createDirectory(directoryPath);
                }
            }
            var outputFingerprints;
            function writeFileIfUpdated(fileName, data, writeByteOrderMark) {
                if (!outputFingerprints) {
                    outputFingerprints = ts.createMap();
                }
                var hash = system.createHash(data); // TODO: GH#18217
                var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217
                if (mtimeBefore) {
                    var fingerprint = outputFingerprints.get(fileName);
                    // If output has not been changed, and the file has no external modification
                    if (fingerprint &&
                        fingerprint.byteOrderMark === writeByteOrderMark &&
                        fingerprint.hash === hash &&
                        fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
                        return;
                    }
                }
                system.writeFile(fileName, data, writeByteOrderMark);
                var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217
                outputFingerprints.set(fileName, {
                    hash: hash,
                    byteOrderMark: writeByteOrderMark,
                    mtime: mtimeAfter
                });
            }
            function writeFile(fileName, data, writeByteOrderMark, onError) {
                try {
                    ts.performance.mark("beforeIOWrite");
                    ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
                    if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) {
                        writeFileIfUpdated(fileName, data, writeByteOrderMark);
                    }
                    else {
                        system.writeFile(fileName, data, writeByteOrderMark);
                    }
                    ts.performance.mark("afterIOWrite");
                    ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
                }
                catch (e) {
                    if (onError) {
                        onError(e.message);
                    }
                }
            }
            function getDefaultLibLocation() {
                return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
            }
            var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
            var realpath = system.realpath && (function (path) { return system.realpath(path); });
            return {
                getSourceFile: getSourceFile,
                getDefaultLibLocation: getDefaultLibLocation,
                getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
                writeFile: writeFile,
                getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
                useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
                getCanonicalFileName: getCanonicalFileName,
                getNewLine: function () { return newLine; },
                fileExists: function (fileName) { return system.fileExists(fileName); },
                readFile: function (fileName) { return system.readFile(fileName); },
                trace: function (s) { return system.write(s + newLine); },
                directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
                getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
                getDirectories: function (path) { return system.getDirectories(path); },
                realpath: realpath,
                readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }
            };
        }
        ts.createCompilerHostWorker = createCompilerHostWorker;
        function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
            var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
            if (ts.getEmitDeclarations(program.getCompilerOptions())) {
                ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
            }
            return ts.sortAndDeduplicateDiagnostics(diagnostics);
        }
        ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
        function formatDiagnostics(diagnostics, host) {
            var output = "";
            for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
                var diagnostic = diagnostics_2[_i];
                output += formatDiagnostic(diagnostic, host);
            }
            return output;
        }
        ts.formatDiagnostics = formatDiagnostics;
        function formatDiagnostic(diagnostic, host) {
            var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
            if (diagnostic.file) {
                var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
                var fileName = diagnostic.file.fileName;
                var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
                return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
            }
            return errorMessage;
        }
        ts.formatDiagnostic = formatDiagnostic;
        /** @internal */
        var ForegroundColorEscapeSequences;
        (function (ForegroundColorEscapeSequences) {
            ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
            ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
            ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
            ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
            ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
        })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
        var gutterStyleSequence = "\u001b[7m";
        var gutterSeparator = " ";
        var resetEscapeSequence = "\u001b[0m";
        var ellipsis = "...";
        var halfIndent = "  ";
        var indent = "    ";
        function getCategoryFormat(category) {
            switch (category) {
                case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
                case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
                case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
                case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
            }
        }
        /** @internal */
        function formatColorAndReset(text, formatStyle) {
            return formatStyle + text + resetEscapeSequence;
        }
        ts.formatColorAndReset = formatColorAndReset;
        function padLeft(s, length) {
            while (s.length < length) {
                s = " " + s;
            }
            return s;
        }
        function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
            var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
            var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
            var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
            var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
            var gutterWidth = (lastLine + 1 + "").length;
            if (hasMoreThanFiveLines) {
                gutterWidth = Math.max(ellipsis.length, gutterWidth);
            }
            var context = "";
            for (var i = firstLine; i <= lastLine; i++) {
                context += host.getNewLine();
                // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
                // so we'll skip ahead to the second-to-last line.
                if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
                    context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
                    i = lastLine - 1;
                }
                var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
                var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
                var lineContent = file.text.slice(lineStart, lineEnd);
                lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
                lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
                // Output the gutter and the actual contents of the line.
                context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
                context += lineContent + host.getNewLine();
                // Output the gutter and the error span for the line using tildes.
                context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
                context += squiggleColor;
                if (i === firstLine) {
                    // If we're on the last line, then limit it to the last character of the last line.
                    // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
                    var lastCharForLine = i === lastLine ? lastLineChar : undefined;
                    context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
                    context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
                }
                else if (i === lastLine) {
                    context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
                }
                else {
                    // Squiggle the entire line.
                    context += lineContent.replace(/./g, "~");
                }
                context += resetEscapeSequence;
            }
            return context;
        }
        /* @internal */
        function formatLocation(file, start, host, color) {
            if (color === void 0) {
                color = formatColorAndReset;
            }
            var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
            var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
            var output = "";
            output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
            output += ":";
            output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
            output += ":";
            output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
            return output;
        }
        ts.formatLocation = formatLocation;
        function formatDiagnosticsWithColorAndContext(diagnostics, host) {
            var output = "";
            for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
                var diagnostic = diagnostics_3[_i];
                if (diagnostic.file) {
                    var file = diagnostic.file, start = diagnostic.start;
                    output += formatLocation(file, start, host); // TODO: GH#18217
                    output += " - ";
                }
                output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
                output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
                output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
                if (diagnostic.file) {
                    output += host.getNewLine();
                    output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
                    if (diagnostic.relatedInformation) {
                        output += host.getNewLine();
                        for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
                            var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText;
                            if (file) {
                                output += host.getNewLine();
                                output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
                                output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
                            }
                            output += host.getNewLine();
                            output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
                        }
                    }
                }
                output += host.getNewLine();
            }
            return output;
        }
        ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
        function flattenDiagnosticMessageText(messageText, newLine) {
            if (ts.isString(messageText)) {
                return messageText;
            }
            else {
                var diagnosticChain = messageText;
                var result = "";
                var indent_1 = 0;
                while (diagnosticChain) {
                    if (indent_1) {
                        result += newLine;
                        for (var i = 0; i < indent_1; i++) {
                            result += "  ";
                        }
                    }
                    result += diagnosticChain.messageText;
                    indent_1++;
                    diagnosticChain = diagnosticChain.next;
                }
                return result;
            }
        }
        ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
        function loadWithLocalCache(names, containingFile, loader) {
            if (names.length === 0) {
                return [];
            }
            var resolutions = [];
            var cache = ts.createMap();
            for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
                var name = names_1[_i];
                var result = void 0;
                if (cache.has(name)) {
                    result = cache.get(name);
                }
                else {
                    cache.set(name, result = loader(name, containingFile));
                }
                resolutions.push(result);
            }
            return resolutions;
        }
        /**
         * Determines if program structure is upto date or needs to be recreated
         */
        /* @internal */
        function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
            // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
            if (!program || hasChangedAutomaticTypeDirectiveNames) {
                return false;
            }
            // If number of files in the program do not match, it is not up-to-date
            if (program.getRootFileNames().length !== rootFileNames.length) {
                return false;
            }
            // If project references dont match
            if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
                return false;
            }
            // If any file is not up-to-date, then the whole program is not up-to-date
            if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
                return false;
            }
            // If any of the missing file paths are now created
            if (program.getMissingFilePaths().some(fileExists)) {
                return false;
            }
            var currentOptions = program.getCompilerOptions();
            // If the compilation settings do no match, then the program is not up-to-date
            if (!ts.compareDataObjects(currentOptions, newOptions)) {
                return false;
            }
            // If everything matches but the text of config file is changed,
            // error locations can change for program options, so update the program
            if (currentOptions.configFile && newOptions.configFile) {
                return currentOptions.configFile.text === newOptions.configFile.text;
            }
            return true;
            function sourceFileNotUptoDate(sourceFile) {
                return !sourceFileVersionUptoDate(sourceFile) ||
                    hasInvalidatedResolution(sourceFile.resolvedPath);
            }
            function sourceFileVersionUptoDate(sourceFile) {
                return sourceFile.version === getSourceVersion(sourceFile.resolvedPath);
            }
            function projectReferenceUptoDate(oldRef, newRef, index) {
                if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
                    return false;
                }
                var oldResolvedRef = program.getResolvedProjectReferences()[index];
                if (oldResolvedRef) {
                    // If sourceFile for the oldResolvedRef existed, check the version for uptodate
                    return sourceFileVersionUptoDate(oldResolvedRef.sourceFile);
                }
                // In old program, not able to resolve project reference path,
                // so if config file doesnt exist, it is uptodate.
                return !fileExists(resolveProjectReferencePath(oldRef));
            }
        }
        ts.isProgramUptoDate = isProgramUptoDate;
        function getConfigFileParsingDiagnostics(configFileParseResult) {
            return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) :
                configFileParseResult.errors;
        }
        ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
        /**
         * Determine if source file needs to be re-created even if its text hasn't changed
         */
        function shouldProgramCreateNewSourceFiles(program, newOptions) {
            if (!program)
                return false;
            // If any compiler options change, we can't reuse old source file even if version match
            // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
            var oldOptions = program.getCompilerOptions();
            return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
                return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
            });
        }
        function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
            return {
                rootNames: rootNames,
                options: options,
                host: host,
                oldProgram: oldProgram,
                configFileParsingDiagnostics: configFileParsingDiagnostics
            };
        }
        function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
            var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
            var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
            var oldProgram = createProgramOptions.oldProgram;
            var program;
            var processingDefaultLibFiles;
            var processingOtherFiles;
            var files;
            var commonSourceDirectory;
            var diagnosticsProducingTypeChecker;
            var noDiagnosticsTypeChecker;
            var classifiableNames;
            var ambientModuleNameToUnmodifiedFileName = ts.createMap();
            var cachedSemanticDiagnosticsForFile = {};
            var cachedDeclarationDiagnosticsForFile = {};
            var resolvedTypeReferenceDirectives = ts.createMap();
            var fileProcessingDiagnostics = ts.createDiagnosticCollection();
            // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
            // This works as imported modules are discovered recursively in a depth first manner, specifically:
            // - For each root file, findSourceFile is called.
            // - This calls processImportedModules for each module imported in the source file.
            // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
            // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
            // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
            var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
            var currentNodeModulesDepth = 0;
            // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
            // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
            var modulesWithElidedImports = ts.createMap();
            // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
            var sourceFilesFoundSearchingNodeModules = ts.createMap();
            ts.performance.mark("beforeProgram");
            var host = createProgramOptions.host || createCompilerHost(options);
            var configParsingHost = parseConfigHostFromCompilerHost(host);
            var skipDefaultLib = options.noLib;
            var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
            var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
            var programDiagnostics = ts.createDiagnosticCollection();
            var currentDirectory = host.getCurrentDirectory();
            var supportedExtensions = ts.getSupportedExtensions(options);
            var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined;
            // Map storing if there is emit blocking diagnostics for given input
            var hasEmitBlockingDiagnostics = ts.createMap();
            var _compilerOptionsObjectLiteralSyntax;
            var _referencesArrayLiteralSyntax;
            var moduleResolutionCache;
            var resolveModuleNamesWorker;
            var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
            if (host.resolveModuleNames) {
                resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) {
                    return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) {
                        // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
                        if (!resolved || resolved.extension !== undefined) {
                            return resolved;
                        }
                        var withExtension = ts.clone(resolved);
                        withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
                        return withExtension;
                    });
                };
            }
            else {
                moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); });
                var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217
                resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); };
            }
            var resolveTypeReferenceDirectiveNamesWorker;
            if (host.resolveTypeReferenceDirectives) {
                resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); };
            }
            else {
                var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217
                resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader_2); };
            }
            // Map from a stringified PackageId to the source file with that id.
            // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
            // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
            var packageIdToSourceFile = ts.createMap();
            // Maps from a SourceFile's `.path` to the name of the package it was imported with.
            var sourceFileToPackageName = ts.createMap();
            // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
            var redirectTargetsMap = ts.createMultiMap();
            var filesByName = ts.createMap();
            var missingFilePaths;
            // stores 'filename -> file association' ignoring case
            // used to track cases when two file names differ only in casing
            var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
            // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
            var resolvedProjectReferences = projectReferences ? [] : undefined;
            var projectReferenceRedirects;
            var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
            var structuralIsReused = tryReuseStructureFromOldProgram();
            if (structuralIsReused !== 2 /* Completely */) {
                processingDefaultLibFiles = [];
                processingOtherFiles = [];
                if (projectReferences) {
                    for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) {
                        var ref = projectReferences_1[_i];
                        var parsedRef = parseProjectReferenceConfigFile(ref);
                        resolvedProjectReferences.push(parsedRef);
                        if (parsedRef) {
                            var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
                            if (out) {
                                var dtsOutfile = ts.changeExtension(out, ".d.ts");
                                processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
                            }
                            addProjectReferenceRedirects(parsedRef.commandLine);
                        }
                    }
                }
                ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
                // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
                var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host);
                if (typeReferences.length) {
                    // This containingFilename needs to match with the one used in managed-side
                    var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
                    var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts");
                    var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
                    for (var i = 0; i < typeReferences.length; i++) {
                        processTypeReferenceDirective(typeReferences[i], resolutions[i]);
                    }
                }
                // Do not process the default library if:
                //  - The '--noLib' flag is used.
                //  - A 'no-default-lib' reference comment is encountered in
                //      processing the root files.
                if (!skipDefaultLib) {
                    // If '--lib' is not specified, include default library file according to '--target'
                    // otherwise, using options specified in '--lib' instead of '--target' default library file
                    var defaultLibraryFileName = getDefaultLibraryFileName();
                    if (!options.lib && defaultLibraryFileName) {
                        processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
                    }
                    else {
                        ts.forEach(options.lib, function (libFileName) {
                            processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
                        });
                    }
                }
                missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); });
                files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
                processingDefaultLibFiles = undefined;
                processingOtherFiles = undefined;
            }
            ts.Debug.assert(!!missingFilePaths);
            // Release any files we have acquired in the old program but are
            // not part of the new program.
            if (oldProgram && host.onReleaseOldSourceFile) {
                var oldSourceFiles = oldProgram.getSourceFiles();
                for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
                    var oldSourceFile = oldSourceFiles_1[_a];
                    if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) {
                        host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions());
                    }
                }
            }
            // unconditionally set oldProgram to undefined to prevent it from being captured in closure
            oldProgram = undefined;
            program = {
                getRootFileNames: function () { return rootNames; },
                getSourceFile: getSourceFile,
                getSourceFileByPath: getSourceFileByPath,
                getSourceFiles: function () { return files; },
                getMissingFilePaths: function () { return missingFilePaths; },
                getCompilerOptions: function () { return options; },
                getSyntacticDiagnostics: getSyntacticDiagnostics,
                getOptionsDiagnostics: getOptionsDiagnostics,
                getGlobalDiagnostics: getGlobalDiagnostics,
                getSemanticDiagnostics: getSemanticDiagnostics,
                getSuggestionDiagnostics: getSuggestionDiagnostics,
                getDeclarationDiagnostics: getDeclarationDiagnostics,
                getTypeChecker: getTypeChecker,
                getClassifiableNames: getClassifiableNames,
                getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
                getCommonSourceDirectory: getCommonSourceDirectory,
                emit: emit,
                getCurrentDirectory: function () { return currentDirectory; },
                getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
                getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
                getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
                getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
                getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
                getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
                isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
                isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
                dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
                getSourceFileFromReference: getSourceFileFromReference,
                getLibFileFromReference: getLibFileFromReference,
                sourceFileToPackageName: sourceFileToPackageName,
                redirectTargetsMap: redirectTargetsMap,
                isEmittedFile: isEmittedFile,
                getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
                getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
                getProjectReferences: getProjectReferences,
                getResolvedProjectReferences: getResolvedProjectReferences,
                getProjectReferenceRedirect: getProjectReferenceRedirect
            };
            verifyCompilerOptions();
            ts.performance.mark("afterProgram");
            ts.performance.measure("Program", "beforeProgram", "afterProgram");
            return program;
            function compareDefaultLibFiles(a, b) {
                return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
            }
            function getDefaultLibFilePriority(a) {
                if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
                    var basename = ts.getBaseFileName(a.fileName);
                    if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
                        return 0;
                    var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
                    var index = ts.libs.indexOf(name);
                    if (index !== -1)
                        return index + 1;
                }
                return ts.libs.length + 2;
            }
            function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
                return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
            }
            function toPath(fileName) {
                return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
            }
            function getCommonSourceDirectory() {
                if (commonSourceDirectory === undefined) {
                    var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
                    if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
                        // If a rootDir is specified use it as the commonSourceDirectory
                        commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
                    }
                    else if (options.composite && options.configFilePath) {
                        // Project compilations never infer their root from the input source paths
                        commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
                        checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
                    }
                    else {
                        commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
                    }
                    if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
                        // Make sure directory path ends with directory separator so this string can directly
                        // used to replace with "" to get the relative path of the source file and the relative path doesn't
                        // start with / making it rooted path
                        commonSourceDirectory += ts.directorySeparator;
                    }
                }
                return commonSourceDirectory;
            }
            function getClassifiableNames() {
                if (!classifiableNames) {
                    // Initialize a checker so that all our files are bound.
                    getTypeChecker();
                    classifiableNames = ts.createUnderscoreEscapedMap();
                    for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
                        var sourceFile = files_2[_i];
                        ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
                    }
                }
                return classifiableNames;
            }
            function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
                if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
                    // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
                    // the best we can do is fallback to the default logic.
                    return resolveModuleNamesWorker(moduleNames, containingFile);
                }
                var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
                if (oldSourceFile !== file && file.resolvedModules) {
                    // `file` was created for the new program.
                    //
                    // We only set `file.resolvedModules` via work from the current function,
                    // so it is defined iff we already called the current function on `file`.
                    // That call happened no later than the creation of the `file` object,
                    // which per above occurred during the current program creation.
                    // Since we assume the filesystem does not change during program creation,
                    // it is safe to reuse resolutions from the earlier call.
                    var result_5 = [];
                    for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
                        var moduleName = moduleNames_1[_i];
                        var resolvedModule = file.resolvedModules.get(moduleName);
                        result_5.push(resolvedModule);
                    }
                    return result_5;
                }
                // At this point, we know at least one of the following hold:
                // - file has local declarations for ambient modules
                // - old program state is available
                // With this information, we can infer some module resolutions without performing resolution.
                /** An ordered list of module names for which we cannot recover the resolution. */
                var unknownModuleNames;
                /**
                 * The indexing of elements in this list matches that of `moduleNames`.
                 *
                 * Before combining results, result[i] is in one of the following states:
                 * * undefined: needs to be recomputed,
                 * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
                 * Needs to be reset to undefined before returning,
                 * * ResolvedModuleFull instance: can be reused.
                 */
                var result;
                var reusedNames;
                /** A transient placeholder used to mark predicted resolution in the result list. */
                var predictedToResolveToAmbientModuleMarker = {};
                for (var i = 0; i < moduleNames.length; i++) {
                    var moduleName = moduleNames[i];
                    // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
                    if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
                        var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
                        if (oldResolvedModule) {
                            if (ts.isTraceEnabled(options, host)) {
                                ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
                            }
                            (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
                            (reusedNames || (reusedNames = [])).push(moduleName);
                            continue;
                        }
                    }
                    // We know moduleName resolves to an ambient module provided that moduleName:
                    // - is in the list of ambient modules locally declared in the current source file.
                    // - resolved to an ambient module in the old program whose declaration is in an unmodified file
                    //   (so the same module declaration will land in the new program)
                    var resolvesToAmbientModuleInNonModifiedFile = false;
                    if (ts.contains(file.ambientModuleNames, moduleName)) {
                        resolvesToAmbientModuleInNonModifiedFile = true;
                        if (ts.isTraceEnabled(options, host)) {
                            ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
                        }
                    }
                    else {
                        resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
                    }
                    if (resolvesToAmbientModuleInNonModifiedFile) {
                        (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
                    }
                    else {
                        // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
                        (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
                    }
                }
                var resolutions = unknownModuleNames && unknownModuleNames.length
                    ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames)
                    : ts.emptyArray;
                // Combine results of resolutions and predicted results
                if (!result) {
                    // There were no unresolved/ambient resolutions.
                    ts.Debug.assert(resolutions.length === moduleNames.length);
                    return resolutions;
                }
                var j = 0;
                for (var i = 0; i < result.length; i++) {
                    if (result[i]) {
                        // `result[i]` is either a `ResolvedModuleFull` or a marker.
                        // If it is the former, we can leave it as is.
                        if (result[i] === predictedToResolveToAmbientModuleMarker) {
                            result[i] = undefined; // TODO: GH#18217
                        }
                    }
                    else {
                        result[i] = resolutions[j];
                        j++;
                    }
                }
                ts.Debug.assert(j === resolutions.length);
                return result;
                // If we change our policy of rechecking failed lookups on each program create,
                // we should adjust the value returned here.
                function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
                    var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
                    var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
                    if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) {
                        // In the old program, we resolved to an ambient module that was in the same
                        //   place as we expected to find an actual module file.
                        // We actually need to return 'false' here even though this seems like a 'true' case
                        //   because the normal module resolution algorithm will find this anyway.
                        return false;
                    }
                    // at least one of declarations should come from non-modified source file
                    var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
                    if (!unmodifiedFile) {
                        return false;
                    }
                    if (ts.isTraceEnabled(options, host)) {
                        ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
                    }
                    return true;
                }
            }
            function tryReuseStructureFromOldProgram() {
                if (!oldProgram) {
                    return 0 /* Not */;
                }
                // check properties that can affect structure of the program or module resolution strategy
                // if any of these properties has changed - structure cannot be reused
                var oldOptions = oldProgram.getCompilerOptions();
                if (ts.changesAffectModuleResolution(oldOptions, options)) {
                    return oldProgram.structureIsReused = 0 /* Not */;
                }
                ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
                // there is an old program, check if we can reuse its structure
                var oldRootNames = oldProgram.getRootFileNames();
                if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
                    return oldProgram.structureIsReused = 0 /* Not */;
                }
                if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
                    return oldProgram.structureIsReused = 0 /* Not */;
                }
                // Check if any referenced project tsconfig files are different
                // If array of references is changed, we cant resue old program
                var oldProjectReferences = oldProgram.getProjectReferences();
                if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) {
                    return oldProgram.structureIsReused = 0 /* Not */;
                }
                // Check the json files for the project references
                var oldRefs = oldProgram.getResolvedProjectReferences();
                if (projectReferences) {
                    // Resolved project referenced should be array if projectReferences provided are array
                    ts.Debug.assert(!!oldRefs);
                    for (var i = 0; i < projectReferences.length; i++) {
                        var oldRef = oldRefs[i];
                        var newRef = parseProjectReferenceConfigFile(projectReferences[i]);
                        if (oldRef) {
                            if (!newRef || newRef.sourceFile !== oldRef.sourceFile) {
                                // Resolved project reference has gone missing or changed
                                return oldProgram.structureIsReused = 0 /* Not */;
                            }
                        }
                        else {
                            // A previously-unresolved reference may be resolved now
                            if (newRef !== undefined) {
                                return oldProgram.structureIsReused = 0 /* Not */;
                            }
                        }
                    }
                }
                else {
                    // Resolved project referenced should be undefined if projectReferences is undefined
                    ts.Debug.assert(!oldRefs);
                }
                // check if program source files has changed in the way that can affect structure of the program
                var newSourceFiles = [];
                var filePaths = [];
                var modifiedSourceFiles = [];
                oldProgram.structureIsReused = 2 /* Completely */;
                // If the missing file paths are now present, it can change the progam structure,
                // and hence cant reuse the structure.
                // This is same as how we dont reuse the structure if one of the file from old program is now missing
                if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
                    return oldProgram.structureIsReused = 0 /* Not */;
                }
                var oldSourceFiles = oldProgram.getSourceFiles();
                var SeenPackageName;
                (function (SeenPackageName) {
                    SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
                    SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
                })(SeenPackageName || (SeenPackageName = {}));
                var seenPackageNames = ts.createMap();
                for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
                    var oldSourceFile = oldSourceFiles_2[_i];
                    var newSourceFile = host.getSourceFileByPath
                        ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
                        : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
                    if (!newSourceFile) {
                        return oldProgram.structureIsReused = 0 /* Not */;
                    }
                    ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
                    var fileChanged = void 0;
                    if (oldSourceFile.redirectInfo) {
                        // We got `newSourceFile` by path, so it is actually for the unredirected file.
                        // This lets us know if the unredirected file has changed. If it has we should break the redirect.
                        if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
                            // Underlying file has changed. Might not redirect anymore. Must rebuild program.
                            return oldProgram.structureIsReused = 0 /* Not */;
                        }
                        fileChanged = false;
                        newSourceFile = oldSourceFile; // Use the redirect.
                    }
                    else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
                        // If a redirected-to source file changes, the redirect may be broken.
                        if (newSourceFile !== oldSourceFile) {
                            return oldProgram.structureIsReused = 0 /* Not */;
                        }
                        fileChanged = false;
                    }
                    else {
                        fileChanged = newSourceFile !== oldSourceFile;
                    }
                    // Since the project references havent changed, its right to set originalFileName and resolvedPath here
                    newSourceFile.path = oldSourceFile.path;
                    newSourceFile.originalFileName = oldSourceFile.originalFileName;
                    newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
                    newSourceFile.fileName = oldSourceFile.fileName;
                    filePaths.push(newSourceFile.path);
                    var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
                    if (packageName !== undefined) {
                        // If there are 2 different source files for the same package name and at least one of them changes,
                        // they might become redirects. So we must rebuild the program.
                        var prevKind = seenPackageNames.get(packageName);
                        var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
                        if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
                            return oldProgram.structureIsReused = 0 /* Not */;
                        }
                        seenPackageNames.set(packageName, newKind);
                    }
                    if (fileChanged) {
                        // The `newSourceFile` object was created for the new program.
                        if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
                            // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
                            return oldProgram.structureIsReused = 0 /* Not */;
                        }
                        if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
                            // value of no-default-lib has changed
                            // this will affect if default library is injected into the list of files
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                        }
                        // check tripleslash references
                        if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
                            // tripleslash references has changed
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                        }
                        // check imports and module augmentations
                        collectExternalModuleReferences(newSourceFile);
                        if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
                            // imports has changed
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                        }
                        if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
                            // moduleAugmentations has changed
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                        }
                        if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) {
                            // dynamicImport has changed
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                        }
                        if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
                            // 'types' references has changed
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                        }
                        // tentatively approve the file
                        modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
                    }
                    else if (hasInvalidatedResolution(oldSourceFile.path)) {
                        // 'module/types' references could have changed
                        oldProgram.structureIsReused = 1 /* SafeModules */;
                        // add file to the modified list so that we will resolve it later
                        modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
                    }
                    // if file has passed all checks it should be safe to reuse it
                    newSourceFiles.push(newSourceFile);
                }
                if (oldProgram.structureIsReused !== 2 /* Completely */) {
                    return oldProgram.structureIsReused;
                }
                var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
                for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
                    var oldFile = oldSourceFiles_3[_a];
                    if (!ts.contains(modifiedFiles, oldFile)) {
                        for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
                            var moduleName = _c[_b];
                            ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
                        }
                    }
                }
                // try to verify results of module resolution
                for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
                    var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
                    var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
                    if (resolveModuleNamesWorker) {
                        var moduleNames = getModuleNames(newSourceFile);
                        var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
                        // ensure that module resolution results are still correct
                        var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
                        if (resolutionsChanged) {
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                            newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
                        }
                        else {
                            newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
                        }
                    }
                    if (resolveTypeReferenceDirectiveNamesWorker) {
                        // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
                        var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
                        var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath);
                        // ensure that types resolutions are still correct
                        var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
                        if (resolutionsChanged) {
                            oldProgram.structureIsReused = 1 /* SafeModules */;
                            newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions);
                        }
                        else {
                            newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
                        }
                    }
                }
                if (oldProgram.structureIsReused !== 2 /* Completely */) {
                    return oldProgram.structureIsReused;
                }
                if (host.hasChangedAutomaticTypeDirectiveNames) {
                    return oldProgram.structureIsReused = 1 /* SafeModules */;
                }
                missingFilePaths = oldProgram.getMissingFilePaths();
                // update fileName -> file mapping
                for (var i = 0; i < newSourceFiles.length; i++) {
                    filesByName.set(filePaths[i], newSourceFiles[i]);
                    // Set the file as found during node modules search if it was found that way in old progra,
                    if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) {
                        sourceFilesFoundSearchingNodeModules.set(filePaths[i], true);
                    }
                }
                files = newSourceFiles;
                fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
                for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) {
                    var modifiedFile = modifiedSourceFiles_2[_f];
                    fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
                }
                resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
                resolvedProjectReferences = oldProgram.getResolvedProjectReferences();
                if (resolvedProjectReferences) {
                    resolvedProjectReferences.forEach(function (ref) {
                        if (ref) {
                            addProjectReferenceRedirects(ref.commandLine);
                        }
                    });
                }
                sourceFileToPackageName = oldProgram.sourceFileToPackageName;
                redirectTargetsMap = oldProgram.redirectTargetsMap;
                return oldProgram.structureIsReused = 2 /* Completely */;
            }
            function getEmitHost(writeFileCallback) {
                return __assign({ getPrependNodes: getPrependNodes,
                    getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) {
                        // Use local caches
                        var path = toPath(f);
                        if (getSourceFileByPath(path))
                            return true;
                        if (ts.contains(missingFilePaths, path))
                            return false;
                        // Before falling back to the host
                        return host.fileExists(f);
                    } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
            }
            function getResolvedProjectReferences() {
                return resolvedProjectReferences;
            }
            function getProjectReferences() {
                return projectReferences;
            }
            function getPrependNodes() {
                if (!projectReferences) {
                    return ts.emptyArray;
                }
                var nodes = [];
                for (var i = 0; i < projectReferences.length; i++) {
                    var ref = projectReferences[i];
                    var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
                    if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
                        var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
                        // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
                        if (!out)
                            continue;
                        var dtsFilename = ts.changeExtension(out, ".d.ts");
                        var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n";
                        var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file
                        var jsMap = host.readFile(jsMapPath);
                        var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n";
                        var dtsMapPath = dtsFilename + ".map";
                        var dtsMap = host.readFile(dtsMapPath);
                        var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap);
                        nodes.push(node);
                    }
                }
                return nodes;
            }
            function isSourceFileFromExternalLibrary(file) {
                return !!sourceFilesFoundSearchingNodeModules.get(file.path);
            }
            function isSourceFileDefaultLibrary(file) {
                if (file.hasNoDefaultLib) {
                    return true;
                }
                if (!options.noLib) {
                    return false;
                }
                // If '--lib' is not specified, include default library file according to '--target'
                // otherwise, using options specified in '--lib' instead of '--target' default library file
                var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
                if (!options.lib) {
                    return equalityComparer(file.fileName, getDefaultLibraryFileName());
                }
                else {
                    return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
                }
            }
            function getDiagnosticsProducingTypeChecker() {
                return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
            }
            function dropDiagnosticsProducingTypeChecker() {
                diagnosticsProducingTypeChecker = undefined;
            }
            function getTypeChecker() {
                return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
            }
            function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) {
                return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); });
            }
            function isEmitBlocked(emitFileName) {
                return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
            }
            function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) {
                var declarationDiagnostics = [];
                if (!emitOnlyDtsFiles) {
                    if (options.noEmit) {
                        return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
                    }
                    // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
                    // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
                    // get any preEmit diagnostics, not just the ones
                    if (options.noEmitOnError) {
                        var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
                        if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
                            declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
                        }
                        if (diagnostics.length > 0 || declarationDiagnostics.length > 0) {
                            return {
                                diagnostics: ts.concatenate(diagnostics, declarationDiagnostics),
                                sourceMaps: undefined,
                                emittedFiles: undefined,
                                emitSkipped: true
                            };
                        }
                    }
                }
                // Create the emit resolver outside of the "emitTime" tracking code below.  That way
                // any cost associated with it (like type checking) are appropriate associated with
                // the type-checking counter.
                //
                // If the -out option is specified, we should not pass the source file to getEmitResolver.
                // This is because in the -out scenario all files need to be emitted, and therefore all
                // files need to be type checked. And the way to specify that all files need to be type
                // checked is to not pass the file to getEmitResolver.
                var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
                ts.performance.mark("beforeEmit");
                var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
                var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
                emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
                ts.performance.mark("afterEmit");
                ts.performance.measure("Emit", "beforeEmit", "afterEmit");
                return emitResult;
            }
            function getSourceFile(fileName) {
                return getSourceFileByPath(toPath(fileName));
            }
            function getSourceFileByPath(path) {
                return filesByName.get(path);
            }
            function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
                if (sourceFile) {
                    return getDiagnostics(sourceFile, cancellationToken);
                }
                return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
                    if (cancellationToken) {
                        cancellationToken.throwIfCancellationRequested();
                    }
                    return getDiagnostics(sourceFile, cancellationToken);
                }));
            }
            function getSyntacticDiagnostics(sourceFile, cancellationToken) {
                return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
            }
            function getSemanticDiagnostics(sourceFile, cancellationToken) {
                return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
            }
            function getDeclarationDiagnostics(sourceFile, cancellationToken) {
                var options = program.getCompilerOptions();
                // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
                if (!sourceFile || options.out || options.outFile) {
                    return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
                }
                else {
                    return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
                }
            }
            function getSyntacticDiagnosticsForFile(sourceFile) {
                // For JavaScript files, we report semantic errors for using TypeScript-only
                // constructs from within a JavaScript file as syntactic errors.
                if (ts.isSourceFileJS(sourceFile)) {
                    if (!sourceFile.additionalSyntacticDiagnostics) {
                        sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
                    }
                    return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
                }
                return sourceFile.parseDiagnostics;
            }
            function runWithCancellationToken(func) {
                try {
                    return func();
                }
                catch (e) {
                    if (e instanceof ts.OperationCanceledException) {
                        // We were canceled while performing the operation.  Because our type checker
                        // might be a bad state, we need to throw it away.
                        //
                        // Note: we are overly aggressive here.  We do not actually *have* to throw away
                        // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
                        // the lifetimes of these two TypeCheckers the same.  Also, we generally only
                        // cancel when the user has made a change anyways.  And, in that case, we (the
                        // program instance) will get thrown away anyways.  So trying to keep one of
                        // these type checkers alive doesn't serve much purpose.
                        noDiagnosticsTypeChecker = undefined;
                        diagnosticsProducingTypeChecker = undefined;
                    }
                    throw e;
                }
            }
            function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
                return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache);
            }
            function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
                return runWithCancellationToken(function () {
                    if (ts.skipTypeChecking(sourceFile, options)) {
                        return ts.emptyArray;
                    }
                    var typeChecker = getDiagnosticsProducingTypeChecker();
                    ts.Debug.assert(!!sourceFile.bindDiagnostics);
                    var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
                    // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
                    var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
                        sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */;
                    var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
                    var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
                    var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
                    var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
                    var diagnostics;
                    for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) {
                        var diags = _a[_i];
                        if (diags) {
                            for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) {
                                var diag = diags_1[_b];
                                if (shouldReportDiagnostic(diag)) {
                                    diagnostics = ts.append(diagnostics, diag);
                                }
                            }
                        }
                    }
                    return diagnostics;
                });
            }
            function getSuggestionDiagnostics(sourceFile, cancellationToken) {
                return runWithCancellationToken(function () {
                    return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
                });
            }
            /**
             * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines
             */
            function shouldReportDiagnostic(diagnostic) {
                var file = diagnostic.file, start = diagnostic.start;
                if (file) {
                    var lineStarts = ts.getLineStarts(file);
                    var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217
                    while (line > 0) {
                        var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]);
                        var result = ignoreDiagnosticCommentRegEx.exec(previousLineText);
                        if (!result) {
                            // non-empty line
                            return true;
                        }
                        if (result[3]) {
                            // @ts-ignore
                            return false;
                        }
                        line--;
                    }
                }
                return true;
            }
            function getJSSyntacticDiagnosticsForFile(sourceFile) {
                return runWithCancellationToken(function () {
                    var diagnostics = [];
                    var parent = sourceFile;
                    walk(sourceFile);
                    return diagnostics;
                    function walk(node) {
                        // Return directly from the case if the given node doesnt want to visit each child
                        // Otherwise break to visit each child
                        switch (parent.kind) {
                            case 149 /* Parameter */:
                            case 152 /* PropertyDeclaration */:
                                if (parent.questionToken === node) {
                                    diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
                                    return;
                                }
                            // falls through
                            case 154 /* MethodDeclaration */:
                            case 153 /* MethodSignature */:
                            case 155 /* Constructor */:
                            case 156 /* GetAccessor */:
                            case 157 /* SetAccessor */:
                            case 194 /* FunctionExpression */:
                            case 237 /* FunctionDeclaration */:
                            case 195 /* ArrowFunction */:
                            case 235 /* VariableDeclaration */:
                                // type annotation
                                if (parent.type === node) {
                                    diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file));
                                    return;
                                }
                        }
                        switch (node.kind) {
                            case 246 /* ImportEqualsDeclaration */:
                                diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file));
                                return;
                            case 252 /* ExportAssignment */:
                                if (node.isExportEquals) {
                                    diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file));
                                    return;
                                }
                                break;
                            case 271 /* HeritageClause */:
                                var heritageClause = node;
                                if (heritageClause.token === 108 /* ImplementsKeyword */) {
                                    diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
                                    return;
                                }
                                break;
                            case 239 /* InterfaceDeclaration */:
                                diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
                                return;
                            case 242 /* ModuleDeclaration */:
                                diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
                                return;
                            case 240 /* TypeAliasDeclaration */:
                                diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
                                return;
                            case 241 /* EnumDeclaration */:
                                diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
                                return;
                            case 211 /* NonNullExpression */:
                                diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file));
                                return;
                            case 210 /* AsExpression */:
                                diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
                                return;
                            case 192 /* TypeAssertionExpression */:
                                ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
                        }
                        var prevParent = parent;
                        parent = node;
                        ts.forEachChild(node, walk, walkArray);
                        parent = prevParent;
                    }
                    function walkArray(nodes) {
                        if (parent.decorators === nodes && !options.experimentalDecorators) {
                            diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
                        }
                        switch (parent.kind) {
                            case 238 /* ClassDeclaration */:
                            case 154 /* MethodDeclaration */:
                            case 153 /* MethodSignature */:
                            case 155 /* Constructor */:
                            case 156 /* GetAccessor */:
                            case 157 /* SetAccessor */:
                            case 194 /* FunctionExpression */:
                            case 237 /* FunctionDeclaration */:
                            case 195 /* ArrowFunction */:
                                // Check type parameters
                                if (nodes === parent.typeParameters) {
                                    diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
                                    return;
                                }
                            // falls through
                            case 217 /* VariableStatement */:
                                // Check modifiers
                                if (nodes === parent.modifiers) {
                                    return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */);
                                }
                                break;
                            case 152 /* PropertyDeclaration */:
                                // Check modifiers of property declaration
                                if (nodes === parent.modifiers) {
                                    for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
                                        var modifier = _a[_i];
                                        if (modifier.kind !== 115 /* StaticKeyword */) {
                                            diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind)));
                                        }
                                    }
                                    return;
                                }
                                break;
                            case 149 /* Parameter */:
                                // Check modifiers of parameter declaration
                                if (nodes === parent.modifiers) {
                                    diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
                                    return;
                                }
                                break;
                            case 189 /* CallExpression */:
                            case 190 /* NewExpression */:
                            case 209 /* ExpressionWithTypeArguments */:
                            case 259 /* JsxSelfClosingElement */:
                            case 260 /* JsxOpeningElement */:
                                // Check type arguments
                                if (nodes === parent.typeArguments) {
                                    diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
                                    return;
                                }
                                break;
                        }
                        for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) {
                            var node = nodes_6[_b];
                            walk(node);
                        }
                    }
                    function checkModifiers(modifiers, isConstValid) {
                        for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
                            var modifier = modifiers_1[_i];
                            switch (modifier.kind) {
                                case 76 /* ConstKeyword */:
                                    if (isConstValid) {
                                        continue;
                                    }
                                // to report error,
                                // falls through
                                case 114 /* PublicKeyword */:
                                case 112 /* PrivateKeyword */:
                                case 113 /* ProtectedKeyword */:
                                case 132 /* ReadonlyKeyword */:
                                case 124 /* DeclareKeyword */:
                                case 117 /* AbstractKeyword */:
                                    diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind)));
                                    break;
                                // These are all legal modifiers.
                                case 115 /* StaticKeyword */:
                                case 84 /* ExportKeyword */:
                                case 79 /* DefaultKeyword */:
                            }
                        }
                    }
                    function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
                        var start = nodes.pos;
                        return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
                    }
                    // Since these are syntactic diagnostics, parent might not have been set
                    // this means the sourceFile cannot be infered from the node
                    function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
                        return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
                    }
                });
            }
            function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
                return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
            }
            function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
                return runWithCancellationToken(function () {
                    var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
                    // Don't actually write any files since we're just getting diagnostics.
                    return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile);
                });
            }
            function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
                var cachedResult = sourceFile
                    ? cache.perFile && cache.perFile.get(sourceFile.path)
                    : cache.allDiagnostics;
                if (cachedResult) {
                    return cachedResult;
                }
                var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217
                if (sourceFile) {
                    if (!cache.perFile) {
                        cache.perFile = ts.createMap();
                    }
                    cache.perFile.set(sourceFile.path, result);
                }
                else {
                    cache.allDiagnostics = result;
                }
                return result;
            }
            function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
                return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
            }
            function getOptionsDiagnostics() {
                return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : [])));
            }
            function getGlobalDiagnostics() {
                return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice());
            }
            function getConfigFileParsingDiagnostics() {
                return configFileParsingDiagnostics || ts.emptyArray;
            }
            function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
                processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
            }
            function fileReferenceIsEqualTo(a, b) {
                return a.fileName === b.fileName;
            }
            function moduleNameIsEqualTo(a, b) {
                return a.kind === 71 /* Identifier */
                    ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText
                    : b.kind === 9 /* StringLiteral */ && a.text === b.text;
            }
            function collectExternalModuleReferences(file) {
                if (file.imports) {
                    return;
                }
                var isJavaScriptFile = ts.isSourceFileJS(file);
                var isExternalModuleFile = ts.isExternalModule(file);
                // file.imports may not be undefined if there exists dynamic import
                var imports;
                var moduleAugmentations;
                var ambientModules;
                // If we are importing helpers, we need to add a synthetic reference to resolve the
                // helpers library.
                if (options.importHelpers
                    && (options.isolatedModules || isExternalModuleFile)
                    && !file.isDeclarationFile) {
                    // synthesize 'import "tslib"' declaration
                    var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
                    var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
                    ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
                    externalHelpersModuleReference.parent = importDecl;
                    importDecl.parent = file;
                    imports = [externalHelpersModuleReference];
                }
                for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
                    var node = _a[_i];
                    collectModuleReferences(node, /*inAmbientModule*/ false);
                    if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
                        collectDynamicImportOrRequireCalls(node);
                    }
                }
                if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
                    collectDynamicImportOrRequireCalls(file.endOfFileToken);
                }
                file.imports = imports || ts.emptyArray;
                file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
                file.ambientModuleNames = ambientModules || ts.emptyArray;
                return;
                function collectModuleReferences(node, inAmbientModule) {
                    if (ts.isAnyImportOrReExport(node)) {
                        var moduleNameExpr = ts.getExternalModuleName(node);
                        // TypeScript 1.0 spec (April 2014): 12.1.6
                        // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
                        // only through top - level external module names. Relative external module names are not permitted.
                        if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
                            imports = ts.append(imports, moduleNameExpr);
                        }
                    }
                    else if (ts.isModuleDeclaration(node)) {
                        if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
                            var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
                            // Ambient module declarations can be interpreted as augmentations for some existing external modules.
                            // This will happen in two cases:
                            // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
                            // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
                            //   immediately nested in top level ambient module declaration .
                            if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
                                (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
                            }
                            else if (!inAmbientModule) {
                                if (file.isDeclarationFile) {
                                    // for global .d.ts files record name of ambient module
                                    (ambientModules || (ambientModules = [])).push(nameText);
                                }
                                // An AmbientExternalModuleDeclaration declares an external module.
                                // This type of declaration is permitted only in the global module.
                                // The StringLiteral must specify a top - level external module name.
                                // Relative external module names are not permitted
                                // NOTE: body of ambient module is always a module block, if it exists
                                var body = node.body;
                                if (body) {
                                    for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
                                        var statement = _a[_i];
                                        collectModuleReferences(statement, /*inAmbientModule*/ true);
                                    }
                                }
                            }
                        }
                    }
                }
                function collectDynamicImportOrRequireCalls(node) {
                    if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
                        imports = ts.append(imports, node.arguments[0]);
                    }
                    // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
                    else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
                        imports = ts.append(imports, node.arguments[0]);
                    }
                    else if (ts.isLiteralImportTypeNode(node)) {
                        imports = ts.append(imports, node.argument.literal);
                    }
                    collectDynamicImportOrRequireCallsForEachChild(node);
                    if (ts.hasJSDocNodes(node)) {
                        ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild);
                    }
                }
                function collectDynamicImportOrRequireCallsForEachChild(node) {
                    ts.forEachChild(node, collectDynamicImportOrRequireCalls);
                }
            }
            function getLibFileFromReference(ref) {
                var libName = ref.fileName.toLocaleLowerCase();
                var libFileName = ts.libMap.get(libName);
                if (libFileName) {
                    return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
                }
            }
            /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
            function getSourceFileFromReference(referencingFile, ref) {
                return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); });
            }
            function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
                if (ts.hasExtension(fileName)) {
                    if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) {
                        if (fail)
                            fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
                        return undefined;
                    }
                    var sourceFile = getSourceFile(fileName);
                    if (fail) {
                        if (!sourceFile) {
                            var redirect = getProjectReferenceRedirect(fileName);
                            if (redirect) {
                                fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
                            }
                            else {
                                fail(ts.Diagnostics.File_0_not_found, fileName);
                            }
                        }
                        else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
                            fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
                        }
                    }
                    return sourceFile;
                }
                else {
                    var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
                    if (sourceFileNoExtension)
                        return sourceFileNoExtension;
                    if (fail && options.allowNonTsExtensions) {
                        fail(ts.Diagnostics.File_0_not_found, fileName);
                        return undefined;
                    }
                    var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
                    if (fail && !sourceFileWithAddedExtension)
                        fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */);
                    return sourceFileWithAddedExtension;
                }
            }
            /** This has side effects through `findSourceFile`. */
            function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) {
                getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217
                function (diagnostic) {
                    var args = [];
                    for (var _i = 1; _i < arguments.length; _i++) {
                        args[_i - 1] = arguments[_i];
                    }
                    fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined
                        ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args)));
                }, refFile);
            }
            function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) {
                if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
                    fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
                }
                else {
                    fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
                }
            }
            function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) {
                var redirect = Object.create(redirectTarget);
                redirect.fileName = fileName;
                redirect.path = path;
                redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
                Object.defineProperties(redirect, {
                    id: {
                        get: function () { return this.redirectInfo.redirectTarget.id; },
                        set: function (value) { this.redirectInfo.redirectTarget.id = value; },
                    },
                    symbol: {
                        get: function () { return this.redirectInfo.redirectTarget.symbol; },
                        set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
                    },
                });
                return redirect;
            }
            // Get source file from normalized fileName
            function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) {
                var originalFileName = fileName;
                if (filesByName.has(path)) {
                    var file_1 = filesByName.get(path);
                    // try to check if we've already seen this file but with a different casing in path
                    // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
                    if (file_1 && options.forceConsistentCasingInFileNames) {
                        var inputName = fileName;
                        var checkedName = file_1.fileName;
                        var isRedirect = toPath(checkedName) !== toPath(inputName);
                        if (isRedirect) {
                            inputName = getProjectReferenceRedirect(fileName) || fileName;
                        }
                        if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) {
                            reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd);
                        }
                    }
                    // If the file was previously found via a node_modules search, but is now being processed as a root file,
                    // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
                    if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) {
                        sourceFilesFoundSearchingNodeModules.set(file_1.path, false);
                        if (!options.noResolve) {
                            processReferencedFiles(file_1, isDefaultLib);
                            processTypeReferenceDirectives(file_1);
                        }
                        processLibReferenceDirectives(file_1);
                        modulesWithElidedImports.set(file_1.path, false);
                        processImportedModules(file_1);
                    }
                    // See if we need to reprocess the imports due to prior skipped imports
                    else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
                        if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
                            modulesWithElidedImports.set(file_1.path, false);
                            processImportedModules(file_1);
                        }
                    }
                    return file_1;
                }
                var redirectedPath;
                if (refFile) {
                    var redirect = getProjectReferenceRedirect(fileName);
                    if (redirect) {
                        (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
                        fileName = redirect;
                        // Once we start redirecting to a file, we can potentially come back to it
                        // via a back-reference from another file in the .d.ts folder. If that happens we'll
                        // end up trying to add it to the program *again* because we were tracking it via its
                        // original (un-redirected) name. So we have to map both the original path and the redirected path
                        // to the source file we're about to find/create
                        redirectedPath = toPath(redirect);
                    }
                }
                // We haven't looked for this file, do so now and cache result
                var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
                    if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
                        fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
                    }
                    else {
                        fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
                    }
                }, shouldCreateNewSourceFile);
                if (packageId) {
                    var packageIdKey = ts.packageIdToString(packageId);
                    var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
                    if (fileFromPackageId) {
                        // Some other SourceFile already exists with this package name and version.
                        // Instead of creating a duplicate, just redirect to the existing one.
                        var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217
                        redirectTargetsMap.add(fileFromPackageId.path, fileName);
                        filesByName.set(path, dupFile);
                        sourceFileToPackageName.set(path, packageId.name);
                        processingOtherFiles.push(dupFile);
                        return dupFile;
                    }
                    else if (file) {
                        // This is the first source file to have this packageId.
                        packageIdToSourceFile.set(packageIdKey, file);
                        sourceFileToPackageName.set(path, packageId.name);
                    }
                }
                filesByName.set(path, file);
                if (redirectedPath) {
                    filesByName.set(redirectedPath, file);
                }
                if (file) {
                    sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
                    file.path = path;
                    file.resolvedPath = toPath(fileName);
                    file.originalFileName = originalFileName;
                    if (host.useCaseSensitiveFileNames()) {
                        var pathLowerCase = path.toLowerCase();
                        // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
                        var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
                        if (existingFile) {
                            reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
                        }
                        else {
                            filesByNameIgnoreCase.set(pathLowerCase, file);
                        }
                    }
                    skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
                    if (!options.noResolve) {
                        processReferencedFiles(file, isDefaultLib);
                        processTypeReferenceDirectives(file);
                    }
                    processLibReferenceDirectives(file);
                    // always process imported modules to record module name resolutions
                    processImportedModules(file);
                    if (isDefaultLib) {
                        processingDefaultLibFiles.push(file);
                    }
                    else {
                        processingOtherFiles.push(file);
                    }
                }
                return file;
            }
            function getProjectReferenceRedirect(fileName) {
                // Ignore dts or any of the non ts files
                if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) {
                    return undefined;
                }
                // If this file is produced by a referenced project, we need to rewrite it to
                // look in the output folder of the referenced project rather than the input
                return ts.forEach(projectReferenceRedirects, function (referencedProject) {
                    // not input file from the referenced project, ignore
                    if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) {
                        return undefined;
                    }
                    var out = referencedProject.options.outFile || referencedProject.options.out;
                    return out ?
                        ts.changeExtension(out, ".d.ts" /* Dts */) :
                        ts.getOutputDeclarationFileName(fileName, referencedProject);
                });
            }
            function processReferencedFiles(file, isDefaultLib) {
                ts.forEach(file.referencedFiles, function (ref) {
                    var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
                    processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end);
                });
            }
            function processTypeReferenceDirectives(file) {
                // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
                var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
                if (!typeDirectives) {
                    return;
                }
                var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName);
                for (var i = 0; i < typeDirectives.length; i++) {
                    var ref = file.typeReferenceDirectives[i];
                    var resolvedTypeReferenceDirective = resolutions[i];
                    // store resolved type directive on the file
                    var fileName = ref.fileName.toLocaleLowerCase();
                    ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
                    processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end);
                }
            }
            function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) {
                // If we already found this library as a primary reference - nothing to do
                var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
                if (previousResolution && previousResolution.primary) {
                    return;
                }
                var saveResolution = true;
                if (resolvedTypeReferenceDirective) {
                    if (resolvedTypeReferenceDirective.primary) {
                        // resolved from the primary path
                        processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217
                    }
                    else {
                        // If we already resolved to this file, it must have been a secondary reference. Check file contents
                        // for sameness and possibly issue an error
                        if (previousResolution) {
                            // Don't bother reading the file again if it's the same file.
                            if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
                                var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
                                if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
                                    fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217
                                    ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName));
                                }
                            }
                            // don't overwrite previous resolution result
                            saveResolution = false;
                        }
                        else {
                            // First resolution of this library
                            processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd);
                        }
                    }
                }
                else {
                    fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217
                }
                if (saveResolution) {
                    resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
                }
            }
            function processLibReferenceDirectives(file) {
                ts.forEach(file.libReferenceDirectives, function (libReference) {
                    var libName = libReference.fileName.toLocaleLowerCase();
                    var libFileName = ts.libMap.get(libName);
                    if (libFileName) {
                        // we ignore any 'no-default-lib' reference set on this file.
                        processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
                    }
                    else {
                        var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
                        var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
                        var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
                        fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion));
                    }
                });
            }
            function createDiagnostic(refFile, refPos, refEnd, message) {
                var args = [];
                for (var _i = 4; _i < arguments.length; _i++) {
                    args[_i - 4] = arguments[_i];
                }
                if (refFile === undefined || refPos === undefined || refEnd === undefined) {
                    return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args));
                }
                else {
                    return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args));
                }
            }
            function getCanonicalFileName(fileName) {
                return host.getCanonicalFileName(fileName);
            }
            function processImportedModules(file) {
                collectExternalModuleReferences(file);
                if (file.imports.length || file.moduleAugmentations.length) {
                    // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
                    var moduleNames = getModuleNames(file);
                    var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
                    ts.Debug.assert(resolutions.length === moduleNames.length);
                    for (var i = 0; i < moduleNames.length; i++) {
                        var resolution = resolutions[i];
                        ts.setResolvedModule(file, moduleNames[i], resolution);
                        if (!resolution) {
                            continue;
                        }
                        var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
                        var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
                        var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
                        var resolvedFileName = resolution.resolvedFileName;
                        if (isFromNodeModulesSearch) {
                            currentNodeModulesDepth++;
                        }
                        // add file to program only if:
                        // - resolution was successful
                        // - noResolve is falsy
                        // - module name comes from the list of imports
                        // - it's not a top level JavaScript module that exceeded the search max
                        var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
                        // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
                        // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
                        var shouldAddFile = resolvedFileName
                            && !getResolutionDiagnostic(options, resolution)
                            && !options.noResolve
                            && i < file.imports.length
                            && !elideImport
                            && !(isJsFile && !options.allowJs)
                            && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */));
                        if (elideImport) {
                            modulesWithElidedImports.set(file.path, true);
                        }
                        else if (shouldAddFile) {
                            var path = toPath(resolvedFileName);
                            var pos = ts.skipTrivia(file.text, file.imports[i].pos);
                            findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId);
                        }
                        if (isFromNodeModulesSearch) {
                            currentNodeModulesDepth--;
                        }
                    }
                }
                else {
                    // no imports - drop cached module resolutions
                    file.resolvedModules = undefined;
                }
            }
            function computeCommonSourceDirectory(sourceFiles) {
                var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
                return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
            }
            function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
                var allFilesBelongToPath = true;
                var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
                for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
                    var sourceFile = sourceFiles_2[_i];
                    if (!sourceFile.isDeclarationFile) {
                        var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
                        if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
                            programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory));
                            allFilesBelongToPath = false;
                        }
                    }
                }
                return allFilesBelongToPath;
            }
            function parseProjectReferenceConfigFile(ref) {
                // The actual filename (i.e. add "/tsconfig.json" if necessary)
                var refPath = resolveProjectReferencePath(ref);
                // An absolute path pointing to the containing directory of the config file
                var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
                var sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
                if (sourceFile === undefined) {
                    return undefined;
                }
                sourceFile.path = toPath(refPath);
                var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
                return { commandLine: commandLine, sourceFile: sourceFile };
            }
            function addProjectReferenceRedirects(referencedProject) {
                (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject);
            }
            function verifyCompilerOptions() {
                if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
                }
                if (options.isolatedModules) {
                    if (ts.getEmitDeclarations(options)) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules");
                    }
                    if (options.noEmitOnError) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules");
                    }
                    if (options.out) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
                    }
                    if (options.outFile) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
                    }
                }
                if (options.inlineSourceMap) {
                    if (options.sourceMap) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
                    }
                    if (options.mapRoot) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
                    }
                }
                if (options.paths && options.baseUrl === undefined) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
                }
                if (options.composite) {
                    if (options.declaration === false) {
                        createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
                    }
                }
                if (projectReferences) {
                    for (var i = 0; i < projectReferences.length; i++) {
                        var ref = projectReferences[i];
                        var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options;
                        if (resolvedRefOpts === undefined) {
                            createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path);
                            continue;
                        }
                        if (!resolvedRefOpts.composite) {
                            createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
                        }
                        if (ref.prepend) {
                            var out = resolvedRefOpts.outFile || resolvedRefOpts.out;
                            if (out) {
                                if (!host.fileExists(out)) {
                                    createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
                                }
                            }
                            else {
                                createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
                            }
                        }
                    }
                }
                // List of collected files is complete; validate exhautiveness if this is a project with a file list
                if (options.composite) {
                    var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
                    if (rootNames.length < sourceFiles.length) {
                        var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
                        for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
                            var file = _a[_i];
                            if (normalizedRootNames.indexOf(file) === -1) {
                                programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file));
                            }
                        }
                    }
                }
                if (options.paths) {
                    for (var key in options.paths) {
                        if (!ts.hasProperty(options.paths, key)) {
                            continue;
                        }
                        if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
                            createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
                        }
                        if (ts.isArray(options.paths[key])) {
                            var len = options.paths[key].length;
                            if (len === 0) {
                                createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
                            }
                            for (var i = 0; i < len; i++) {
                                var subst = options.paths[key][i];
                                var typeOfSubst = typeof subst;
                                if (typeOfSubst === "string") {
                                    if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
                                        createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key);
                                    }
                                }
                                else {
                                    createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
                                }
                            }
                        }
                        else {
                            createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
                        }
                    }
                }
                if (!options.sourceMap && !options.inlineSourceMap) {
                    if (options.inlineSources) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
                    }
                    if (options.sourceRoot) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
                    }
                }
                if (options.out && options.outFile) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
                }
                if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
                    // Error to specify --mapRoot without --sourcemap
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
                }
                if (options.declarationDir) {
                    if (!ts.getEmitDeclarations(options)) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
                    }
                    if (options.out || options.outFile) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
                    }
                }
                if (options.declarationMap && !ts.getEmitDeclarations(options)) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
                }
                if (options.lib && options.noLib) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
                }
                if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
                }
                var languageVersion = options.target || 0 /* ES3 */;
                var outFile = options.outFile || options.out;
                var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; });
                if (options.isolatedModules) {
                    if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
                    }
                    var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; });
                    if (firstNonExternalModuleSourceFile) {
                        var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
                        programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
                    }
                }
                else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
                    // We cannot use createDiagnosticFromNode because nodes do not have parents yet
                    var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
                    programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
                }
                // Cannot specify module gen that isn't amd or system with --out
                if (outFile) {
                    if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
                        createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
                    }
                    else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
                        var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
                        programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
                    }
                }
                if (options.resolveJsonModule) {
                    if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
                    }
                    // Any emit other than common js, amd, es2015 or esnext is error
                    else if (!ts.hasJsonModuleEmitEnabled(options)) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
                    }
                }
                // there has to be common source directory if user specified --outdir || --sourceRoot
                // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
                if (options.outDir || // there is --outDir specified
                    options.sourceRoot || // there is --sourceRoot specified
                    options.mapRoot) { // there is --mapRoot specified
                    // Precalculate and cache the common source directory
                    var dir = getCommonSourceDirectory();
                    // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
                    if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) {
                        createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
                    }
                }
                if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options));
                }
                if (options.checkJs && !options.allowJs) {
                    programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
                }
                if (options.emitDeclarationOnly) {
                    if (!ts.getEmitDeclarations(options)) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
                    }
                    if (options.noEmit) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
                    }
                }
                if (options.emitDecoratorMetadata &&
                    !options.experimentalDecorators) {
                    createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
                }
                if (options.jsxFactory) {
                    if (options.reactNamespace) {
                        createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
                    }
                    if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
                        createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
                    }
                }
                else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
                    createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
                }
                // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
                if (!options.noEmit && !options.suppressOutputPathCheck) {
                    var emitHost = getEmitHost();
                    var emitFilesSeen_1 = ts.createMap();
                    ts.forEachEmittedFile(emitHost, function (emitFileNames) {
                        if (!options.emitDeclarationOnly) {
                            verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
                        }
                        verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
                    });
                }
                // Verify that all the emit files are unique and don't overwrite input files
                function verifyEmitFilePath(emitFileName, emitFilesSeen) {
                    if (emitFileName) {
                        var emitFilePath = toPath(emitFileName);
                        // Report error if the output overwrites input file
                        if (filesByName.has(emitFilePath)) {
                            var chain_2;
                            if (!options.configFilePath) {
                                // The program is from either an inferred project or an external project
                                chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig);
                            }
                            chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
                            blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2));
                        }
                        var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath;
                        // Report error if multiple files write into same file
                        if (emitFilesSeen.has(emitFileKey)) {
                            // Already seen the same emit file - report error
                            blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
                        }
                        else {
                            emitFilesSeen.set(emitFileKey, true);
                        }
                    }
                }
            }
            function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
                var needCompilerDiagnostic = true;
                var pathsSyntax = getOptionPathsSyntax();
                for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
                    var pathProp = pathsSyntax_1[_i];
                    if (ts.isObjectLiteralExpression(pathProp.initializer)) {
                        for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
                            var keyProps = _b[_a];
                            var initializer = keyProps.initializer;
                            if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
                                programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
                                needCompilerDiagnostic = false;
                            }
                        }
                    }
                }
                if (needCompilerDiagnostic) {
                    programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
                }
            }
            function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
                var needCompilerDiagnostic = true;
                var pathsSyntax = getOptionPathsSyntax();
                for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
                    var pathProp = pathsSyntax_2[_i];
                    if (ts.isObjectLiteralExpression(pathProp.initializer) &&
                        createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
                        needCompilerDiagnostic = false;
                    }
                }
                if (needCompilerDiagnostic) {
                    programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
                }
            }
            function getOptionsSyntaxByName(name) {
                var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
                if (compilerOptionsObjectLiteralSyntax) {
                    return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
                }
                return undefined;
            }
            function getOptionPathsSyntax() {
                return getOptionsSyntaxByName("paths") || ts.emptyArray;
            }
            function createDiagnosticForOptionName(message, option1, option2, option3) {
                createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
            }
            function createOptionValueDiagnostic(option1, message, arg0) {
                createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
            }
            function createDiagnosticForReference(index, message, arg0, arg1) {
                var referencesSyntax = getProjectReferencesSyntax();
                if (referencesSyntax && referencesSyntax.elements.length > index) {
                    programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
                }
                else {
                    programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
                }
            }
            function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
                var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
                var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
                    !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
                if (needCompilerDiagnostic) {
                    programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
                }
            }
            function getProjectReferencesSyntax() {
                if (_referencesArrayLiteralSyntax === undefined) {
                    _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword
                    if (options.configFile) {
                        var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217
                        for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) {
                            var prop = _a[_i];
                            if (ts.isArrayLiteralExpression(prop.initializer)) {
                                _referencesArrayLiteralSyntax = prop.initializer;
                                break;
                            }
                        }
                    }
                }
                return _referencesArrayLiteralSyntax;
            }
            function getCompilerOptionsObjectLiteralSyntax() {
                if (_compilerOptionsObjectLiteralSyntax === undefined) {
                    _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword
                    var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
                    if (jsonObjectLiteral) {
                        for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
                            var prop = _a[_i];
                            if (ts.isObjectLiteralExpression(prop.initializer)) {
                                _compilerOptionsObjectLiteralSyntax = prop.initializer;
                                break;
                            }
                        }
                    }
                }
                return _compilerOptionsObjectLiteralSyntax;
            }
            function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
                var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
                for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
                    var prop = props_2[_i];
                    programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
                }
                return !!props.length;
            }
            function blockEmittingOfFile(emitFileName, diag) {
                hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
                programDiagnostics.add(diag);
            }
            function isEmittedFile(file) {
                if (options.noEmit) {
                    return false;
                }
                // If this is source file, its not emitted file
                var filePath = toPath(file);
                if (getSourceFileByPath(filePath)) {
                    return false;
                }
                // If options have --outFile or --out just check that
                var out = options.outFile || options.out;
                if (out) {
                    return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
                }
                // If declarationDir is specified, return if its a file in that directory
                if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
                    return true;
                }
                // If --outDir, check if file is in that directory
                if (options.outDir) {
                    return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
                }
                if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
                    // Otherwise just check if sourceFile with the name exists
                    var filePathWithoutExtension = ts.removeFileExtension(filePath);
                    return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
                        !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
                }
                return false;
            }
            function isSameFile(file1, file2) {
                return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
            }
        }
        ts.createProgram = createProgram;
        /* @internal */
        function parseConfigHostFromCompilerHost(host) {
            return {
                fileExists: function (f) { return host.fileExists(f); },
                readDirectory: function (root, extensions, excludes, includes, depth) {
                    ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
                    return host.readDirectory(root, extensions, excludes, includes, depth);
                },
                readFile: function (f) { return host.readFile(f); },
                useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
                getCurrentDirectory: function () { return host.getCurrentDirectory(); },
                onUnRecoverableConfigFileDiagnostic: function () { return undefined; }
            };
        }
        ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost;
        function resolveProjectReferencePath(hostOrRef, ref) {
            var passedInRef = ref ? ref : hostOrRef;
            return ts.resolveConfigFileProjectName(passedInRef.path);
        }
        ts.resolveProjectReferencePath = resolveProjectReferencePath;
        function getEmitDeclarationOptionName(options) {
            return options.declaration ? "declaration" : "composite";
        }
        /* @internal */
        /**
         * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
         * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
         * This returns a diagnostic even if the module will be an untyped module.
         */
        function getResolutionDiagnostic(options, _a) {
            var extension = _a.extension;
            switch (extension) {
                case ".ts" /* Ts */:
                case ".d.ts" /* Dts */:
                    // These are always allowed.
                    return undefined;
                case ".tsx" /* Tsx */:
                    return needJsx();
                case ".jsx" /* Jsx */:
                    return needJsx() || needAllowJs();
                case ".js" /* Js */:
                    return needAllowJs();
                case ".json" /* Json */:
                    return needResolveJsonModule();
            }
            function needJsx() {
                return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
            }
            function needAllowJs() {
                return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
            }
            function needResolveJsonModule() {
                return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
            }
        }
        ts.getResolutionDiagnostic = getResolutionDiagnostic;
        function getModuleNames(_a) {
            var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
            var res = imports.map(function (i) { return i.text; });
            for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
                var aug = moduleAugmentations_1[_i];
                if (aug.kind === 9 /* StringLiteral */) {
                    res.push(aug.text);
                }
                // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
            }
            return res;
        }
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) {
            var outputFiles = [];
            var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
            return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit };
            function writeFile(fileName, text, writeByteOrderMark) {
                outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
            }
        }
        ts.getFileEmitOutput = getFileEmitOutput;
    })(ts || (ts = {}));
    /*@internal*/
    (function (ts) {
        var BuilderState;
        (function (BuilderState) {
            /**
             * Get the referencedFile from the imported module symbol
             */
            function getReferencedFileFromImportedModuleSymbol(symbol) {
                if (symbol.declarations && symbol.declarations[0]) {
                    var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
                    return declarationSourceFile && declarationSourceFile.resolvedPath;
                }
            }
            /**
             * Get the referencedFile from the import name node from file
             */
            function getReferencedFileFromImportLiteral(checker, importName) {
                var symbol = checker.getSymbolAtLocation(importName);
                return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
            }
            /**
             * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
             */
            function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
                return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
            }
            /**
             * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
             */
            function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
                var referencedFiles;
                // We need to use a set here since the code can contain the same import twice,
                // but that will only be one dependency.
                // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
                if (sourceFile.imports && sourceFile.imports.length > 0) {
                    var checker = program.getTypeChecker();
                    for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
                        var importName = _a[_i];
                        var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
                        if (declarationSourceFilePath) {
                            addReferencedFile(declarationSourceFilePath);
                        }
                    }
                }
                var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path);
                // Handle triple slash references
                if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
                    for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
                        var referencedFile = _c[_b];
                        var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
                        addReferencedFile(referencedPath);
                    }
                }
                // Handle type reference directives
                if (sourceFile.resolvedTypeReferenceDirectiveNames) {
                    sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
                        if (!resolvedTypeReferenceDirective) {
                            return;
                        }
                        var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
                        var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
                        addReferencedFile(typeFilePath);
                    });
                }
                return referencedFiles;
                function addReferencedFile(referencedPath) {
                    if (!referencedFiles) {
                        referencedFiles = ts.createMap();
                    }
                    referencedFiles.set(referencedPath, true);
                }
            }
            /**
             * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
             */
            function canReuseOldState(newReferencedMap, oldState) {
                return oldState && !oldState.referencedMap === !newReferencedMap;
            }
            BuilderState.canReuseOldState = canReuseOldState;
            /**
             * Creates the state of file references and signature for the new program from oldState if it is safe
             */
            function create(newProgram, getCanonicalFileName, oldState) {
                var fileInfos = ts.createMap();
                var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
                var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
                var hasCalledUpdateShapeSignature = ts.createMap();
                var useOldState = canReuseOldState(referencedMap, oldState);
                // Create the reference map, and set the file infos
                for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
                    var sourceFile = _a[_i];
                    var version_1 = sourceFile.version;
                    var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
                    if (referencedMap) {
                        var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
                        if (newReferences) {
                            referencedMap.set(sourceFile.path, newReferences);
                        }
                        // Copy old visible to outside files map
                        if (useOldState) {
                            var exportedModules = oldState.exportedModulesMap.get(sourceFile.path);
                            if (exportedModules) {
                                exportedModulesMap.set(sourceFile.path, exportedModules);
                            }
                        }
                    }
                    fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature });
                }
                return {
                    fileInfos: fileInfos,
                    referencedMap: referencedMap,
                    exportedModulesMap: exportedModulesMap,
                    hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature,
                    allFilesExcludingDefaultLibraryFile: undefined,
                    allFileNames: undefined
                };
            }
            BuilderState.create = create;
            /**
             * Gets the files affected by the path from the program
             */
            function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
                // Since the operation could be cancelled, the signatures are always stored in the cache
                // They will be commited once it is safe to use them
                // eg when calling this api from tsserver, if there is no cancellation of the operation
                // In the other cases the affected files signatures are commited only after the iteration through the result is complete
                var signatureCache = cacheToUpdateSignature || ts.createMap();
                var sourceFile = programOfThisState.getSourceFileByPath(path);
                if (!sourceFile) {
                    return ts.emptyArray;
                }
                if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
                    return [sourceFile];
                }
                var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
                if (!cacheToUpdateSignature) {
                    // Commit all the signatures in the signature cache
                    updateSignaturesFromCache(state, signatureCache);
                }
                return result;
            }
            BuilderState.getFilesAffectedBy = getFilesAffectedBy;
            /**
             * Updates the signatures from the cache into state's fileinfo signatures
             * This should be called whenever it is safe to commit the state of the builder
             */
            function updateSignaturesFromCache(state, signatureCache) {
                signatureCache.forEach(function (signature, path) {
                    state.fileInfos.get(path).signature = signature;
                    state.hasCalledUpdateShapeSignature.set(path, true);
                });
            }
            BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
            /**
             * Returns if the shape of the signature has changed since last emit
             */
            function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
                ts.Debug.assert(!!sourceFile);
                ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
                // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
                if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) {
                    return false;
                }
                var info = state.fileInfos.get(sourceFile.path);
                if (!info)
                    return ts.Debug.fail();
                var prevSignature = info.signature;
                var latestSignature;
                if (sourceFile.isDeclarationFile) {
                    latestSignature = sourceFile.version;
                }
                else {
                    var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken);
                    if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) {
                        latestSignature = computeHash(emitOutput.outputFiles[0].text);
                        if (exportedModulesMapCache && latestSignature !== prevSignature) {
                            updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
                        }
                    }
                    else {
                        latestSignature = prevSignature; // TODO: GH#18217
                    }
                }
                cacheToUpdateSignature.set(sourceFile.path, latestSignature);
                return !prevSignature || latestSignature !== prevSignature;
            }
            /**
             * Coverts the declaration emit result into exported modules map
             */
            function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
                if (!exportedModulesFromDeclarationEmit) {
                    exportedModulesMapCache.set(sourceFile.path, false);
                    return;
                }
                var exportedModules;
                exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
                exportedModulesMapCache.set(sourceFile.path, exportedModules || false);
                function addExportedModule(exportedModulePath) {
                    if (exportedModulePath) {
                        if (!exportedModules) {
                            exportedModules = ts.createMap();
                        }
                        exportedModules.set(exportedModulePath, true);
                    }
                }
            }
            /**
             * Updates the exported modules from cache into state's exported modules map
             * This should be called whenever it is safe to commit the state of the builder
             */
            function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
                if (exportedModulesMapCache) {
                    ts.Debug.assert(!!state.exportedModulesMap);
                    exportedModulesMapCache.forEach(function (exportedModules, path) {
                        if (exportedModules) {
                            state.exportedModulesMap.set(path, exportedModules);
                        }
                        else {
                            state.exportedModulesMap.delete(path);
                        }
                    });
                }
            }
            BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
            /**
             * Get all the dependencies of the sourceFile
             */
            function getAllDependencies(state, programOfThisState, sourceFile) {
                var _a;
                var compilerOptions = programOfThisState.getCompilerOptions();
                // With --out or --outFile all outputs go into single file, all files depend on each other
                if (compilerOptions.outFile || compilerOptions.out) {
                    return getAllFileNames(state, programOfThisState);
                }
                // If this is non module emit, or its a global file, it depends on all the source files
                if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) {
                    return getAllFileNames(state, programOfThisState);
                }
                // Get the references, traversing deep from the referenceMap
                var seenMap = ts.createMap();
                var queue = [sourceFile.path];
                while (queue.length) {
                    var path = queue.pop();
                    if (!seenMap.has(path)) {
                        seenMap.set(path, true);
                        var references = state.referencedMap.get(path);
                        if (references) {
                            var iterator = references.keys();
                            for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
                                queue.push(value);
                            }
                        }
                    }
                }
                return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
                    var file = programOfThisState.getSourceFileByPath(path);
                    return file ? file.fileName : path;
                }));
            }
            BuilderState.getAllDependencies = getAllDependencies;
            /**
             * Gets the names of all files from the program
             */
            function getAllFileNames(state, programOfThisState) {
                if (!state.allFileNames) {
                    var sourceFiles = programOfThisState.getSourceFiles();
                    state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
                }
                return state.allFileNames;
            }
            /**
             * Gets the files referenced by the the file path
             */
            function getReferencedByPaths(state, referencedFilePath) {
                return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
                    var filePath = _a[0], referencesInFile = _a[1];
                    return referencesInFile.has(referencedFilePath) ? filePath : undefined;
                }));
            }
            /**
             * For script files that contains only ambient external modules, although they are not actually external module files,
             * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
             * there are no point to rebuild all script files if these special files have changed. However, if any statement
             * in the file is not ambient external module, we treat it as a regular script file.
             */
            function containsOnlyAmbientModules(sourceFile) {
                for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
                    var statement = _a[_i];
                    if (!ts.isModuleWithStringLiteralName(statement)) {
                        return false;
                    }
                }
                return true;
            }
            /**
             * Gets all files of the program excluding the default library file
             */
            function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
                // Use cached result
                if (state.allFilesExcludingDefaultLibraryFile) {
                    return state.allFilesExcludingDefaultLibraryFile;
                }
                var result;
                addSourceFile(firstSourceFile);
                for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
                    var sourceFile = _a[_i];
                    if (sourceFile !== firstSourceFile) {
                        addSourceFile(sourceFile);
                    }
                }
                state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
                return state.allFilesExcludingDefaultLibraryFile;
                function addSourceFile(sourceFile) {
                    if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
                        (result || (result = [])).push(sourceFile);
                    }
                }
            }
            /**
             * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
             */
            function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
                var compilerOptions = programOfThisState.getCompilerOptions();
                // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
                // so returning the file itself is good enough.
                if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
                    return [sourceFileWithUpdatedShape];
                }
                return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
            }
            /**
             * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
             */
            function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
                if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) {
                    return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
                }
                var compilerOptions = programOfThisState.getCompilerOptions();
                if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
                    return [sourceFileWithUpdatedShape];
                }
                // Now we need to if each file in the referencedBy list has a shape change as well.
                // Because if so, its own referencedBy files need to be saved as well to make the
                // emitting result consistent with files on disk.
                var seenFileNamesMap = ts.createMap();
                // Start with the paths this file was referenced by
                seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape);
                var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path);
                while (queue.length > 0) {
                    var currentPath = queue.pop();
                    if (!seenFileNamesMap.has(currentPath)) {
                        var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
                        seenFileNamesMap.set(currentPath, currentSourceFile);
                        if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
                            queue.push.apply(// TODO: GH#18217
                            queue, getReferencedByPaths(state, currentPath));
                        }
                    }
                }
                // Return array of values that needs emit
                // Return array of values that needs emit
                return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
            }
        })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        function hasSameKeys(map1, map2) {
            // Has same size and every key is present in both maps
            return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
        }
        /**
         * Create the state so that we can iterate on changedFiles/affected files
         */
        function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
            var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
            state.program = newProgram;
            var compilerOptions = newProgram.getCompilerOptions();
            if (!compilerOptions.outFile && !compilerOptions.out) {
                state.semanticDiagnosticsPerFile = ts.createMap();
            }
            state.changedFilesSet = ts.createMap();
            var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
            var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
                !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions());
            if (useOldState) {
                // Verify the sanity of old state
                if (!oldState.currentChangedFilePath) {
                    ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
                }
                if (canCopySemanticDiagnostics) {
                    ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
                }
                // Copy old state's changed files set
                ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
            }
            // Update changed files and copy semantic diagnostics if we can
            var referencedMap = state.referencedMap;
            var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
            state.fileInfos.forEach(function (info, sourceFilePath) {
                var oldInfo;
                var newReferences;
                // if not using old state, every file is changed
                if (!useOldState ||
                    // File wasnt present in old state
                    !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
                    // versions dont match
                    oldInfo.version !== info.version ||
                    // Referenced files changed
                    !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
                    // Referenced file was deleted in the new program
                    newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
                    // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
                    state.changedFilesSet.set(sourceFilePath, true);
                }
                else if (canCopySemanticDiagnostics) {
                    // Unchanged file copy diagnostics
                    var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
                    if (diagnostics) {
                        state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
                        if (!state.semanticDiagnosticsFromOldState) {
                            state.semanticDiagnosticsFromOldState = ts.createMap();
                        }
                        state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
                    }
                }
            });
            return state;
        }
        /**
         * Verifies that source file is ok to be used in calls that arent handled by next
         */
        function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
            ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path));
        }
        /**
         * This function returns the next affected file to be processed.
         * Note that until doneAffected is called it would keep reporting same result
         * This is to allow the callers to be able to actually remove affected file only when the operation is complete
         * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
         */
        function getNextAffectedFile(state, cancellationToken, computeHash) {
            while (true) {
                var affectedFiles = state.affectedFiles;
                if (affectedFiles) {
                    var seenAffectedFiles = state.seenAffectedFiles;
                    var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
                    while (affectedFilesIndex < affectedFiles.length) {
                        var affectedFile = affectedFiles[affectedFilesIndex];
                        if (!seenAffectedFiles.has(affectedFile.path)) {
                            // Set the next affected file as seen and remove the cached semantic diagnostics
                            state.affectedFilesIndex = affectedFilesIndex;
                            cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile);
                            return affectedFile;
                        }
                        seenAffectedFiles.set(affectedFile.path, true);
                        affectedFilesIndex++;
                    }
                    // Remove the changed file from the change set
                    state.changedFilesSet.delete(state.currentChangedFilePath);
                    state.currentChangedFilePath = undefined;
                    // Commit the changes in file signature
                    ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
                    state.currentAffectedFilesSignatures.clear();
                    ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
                    state.affectedFiles = undefined;
                }
                // Get next changed file
                var nextKey = state.changedFilesSet.keys().next();
                if (nextKey.done) {
                    // Done
                    return undefined;
                }
                // With --out or --outFile all outputs go into single file
                // so operations are performed directly on program, return program
                var compilerOptions = state.program.getCompilerOptions();
                if (compilerOptions.outFile || compilerOptions.out) {
                    ts.Debug.assert(!state.semanticDiagnosticsPerFile);
                    return state.program;
                }
                // Get next batch of affected files
                state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
                if (state.exportedModulesMap) {
                    state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
                }
                state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
                state.currentChangedFilePath = nextKey.value;
                state.affectedFilesIndex = 0;
                state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
            }
        }
        /**
         * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file
         */
        function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) {
            if (removeSemanticDiagnosticsOf(state, affectedFile.path)) {
                // If there are no more diagnostics from old cache, done
                return;
            }
            // If there was change in signature for the changed file,
            // then delete the semantic diagnostics for files that are affected by using exports of this module
            if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) {
                return;
            }
            ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
            // Go through exported modules from cache first
            // If exported modules has path, all files referencing file exported from are affected
            if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
                return exportedModules &&
                    exportedModules.has(affectedFile.path) &&
                    removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath);
            })) {
                return;
            }
            // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
            ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
                return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
                    exportedModules.has(affectedFile.path) &&
                    removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath);
            });
        }
        /**
         * removes the semantic diagnostics of files referencing referencedPath and
         * returns true if there are no more semantic diagnostics from old state
         */
        function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) {
            return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
                return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath);
            });
        }
        /**
         * Removes semantic diagnostics for path and
         * returns true if there are no more semantic diagnostics from the old state
         */
        function removeSemanticDiagnosticsOf(state, path) {
            if (!state.semanticDiagnosticsFromOldState) {
                return false;
            }
            state.semanticDiagnosticsFromOldState.delete(path);
            state.semanticDiagnosticsPerFile.delete(path);
            return !state.semanticDiagnosticsFromOldState.size;
        }
        /**
         * This is called after completing operation on the next affected file.
         * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
         */
        function doneWithAffectedFile(state, affected) {
            if (affected === state.program) {
                state.changedFilesSet.clear();
            }
            else {
                state.seenAffectedFiles.set(affected.path, true);
                state.affectedFilesIndex++;
            }
        }
        /**
         * Returns the result with affected file
         */
        function toAffectedFileResult(state, result, affected) {
            doneWithAffectedFile(state, affected);
            return { result: result, affected: affected };
        }
        /**
         * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it
         * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set
         */
        function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
            var path = sourceFile.path;
            var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
            // Report the semantic diagnostics from the cache if we already have those diagnostics present
            if (cachedDiagnostics) {
                return cachedDiagnostics;
            }
            // Diagnostics werent cached, get them from program, and cache the result
            var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken);
            state.semanticDiagnosticsPerFile.set(path, diagnostics);
            return diagnostics;
        }
        var BuilderProgramKind;
        (function (BuilderProgramKind) {
            BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
            BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
        })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
        function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
            var host;
            var newProgram;
            var oldProgram;
            if (newProgramOrRootNames === undefined) {
                ts.Debug.assert(hostOrOptions === undefined);
                host = oldProgramOrHost;
                oldProgram = configFileParsingDiagnosticsOrOldProgram;
                ts.Debug.assert(!!oldProgram);
                newProgram = oldProgram.getProgram();
            }
            else if (ts.isArray(newProgramOrRootNames)) {
                oldProgram = configFileParsingDiagnosticsOrOldProgram;
                newProgram = ts.createProgram({
                    rootNames: newProgramOrRootNames,
                    options: hostOrOptions,
                    host: oldProgramOrHost,
                    oldProgram: oldProgram && oldProgram.getProgram(),
                    configFileParsingDiagnostics: configFileParsingDiagnostics,
                    projectReferences: projectReferences
                });
                host = oldProgramOrHost;
            }
            else {
                newProgram = newProgramOrRootNames;
                host = hostOrOptions;
                oldProgram = oldProgramOrHost;
                configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
            }
            return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
        }
        ts.getBuilderCreationParameters = getBuilderCreationParameters;
        function createBuilderProgram(kind, _a) {
            var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
            // Return same program if underlying program doesnt change
            var oldState = oldProgram && oldProgram.getState();
            if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
                newProgram = undefined; // TODO: GH#18217
                oldState = undefined;
                return oldProgram;
            }
            /**
             * Create the canonical file name for identity
             */
            var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
            /**
             * Computing hash to for signature verification
             */
            var computeHash = host.createHash || ts.identity;
            var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
            // To ensure that we arent storing any references to old program or new program without state
            newProgram = undefined; // TODO: GH#18217
            oldProgram = undefined;
            oldState = undefined;
            var result = {
                getState: function () { return state; },
                getProgram: function () { return state.program; },
                getCompilerOptions: function () { return state.program.getCompilerOptions(); },
                getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); },
                getSourceFiles: function () { return state.program.getSourceFiles(); },
                getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); },
                getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); },
                getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); },
                getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); },
                getSemanticDiagnostics: getSemanticDiagnostics,
                emit: emit,
                getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); },
                getCurrentDirectory: function () { return state.program.getCurrentDirectory(); }
            };
            if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
                result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
            }
            else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
                result.emitNextAffectedFile = emitNextAffectedFile;
            }
            else {
                ts.notImplemented();
            }
            return result;
            /**
             * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
             * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
             * in that order would be used to write the files
             */
            function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
                var affected = getNextAffectedFile(state, cancellationToken, computeHash);
                if (!affected) {
                    // Done
                    return undefined;
                }
                return toAffectedFileResult(state, 
                // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
                // Otherwise just affected file
                state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected);
            }
            /**
             * Emits the JavaScript and declaration files.
             * When targetSource file is specified, emits the files corresponding to that source file,
             * otherwise for the whole program.
             * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
             * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
             * it will only emit all the affected files instead of whole program
             *
             * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
             * in that order would be used to write the files
             */
            function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
                if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
                    assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
                    if (!targetSourceFile) {
                        // Emit and report any errors we ran into.
                        var sourceMaps = [];
                        var emitSkipped = false;
                        var diagnostics = void 0;
                        var emittedFiles = [];
                        var affectedEmitResult = void 0;
                        while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
                            emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
                            diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
                            emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
                            sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
                        }
                        return {
                            emitSkipped: emitSkipped,
                            diagnostics: diagnostics || ts.emptyArray,
                            emittedFiles: emittedFiles,
                            sourceMaps: sourceMaps
                        };
                    }
                }
                return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
            }
            /**
             * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
             * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
             */
            function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
                while (true) {
                    var affected = getNextAffectedFile(state, cancellationToken, computeHash);
                    if (!affected) {
                        // Done
                        return undefined;
                    }
                    else if (affected === state.program) {
                        // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
                        return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
                    }
                    // Get diagnostics for the affected file if its not ignored
                    if (ignoreSourceFile && ignoreSourceFile(affected)) {
                        // Get next affected file
                        doneWithAffectedFile(state, affected);
                        continue;
                    }
                    return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
                }
            }
            /**
             * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
             * The semantic diagnostics are cached and managed here
             * Note that it is assumed that when asked about semantic diagnostics through this API,
             * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
             * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
             * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
             */
            function getSemanticDiagnostics(sourceFile, cancellationToken) {
                assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
                var compilerOptions = state.program.getCompilerOptions();
                if (compilerOptions.outFile || compilerOptions.out) {
                    ts.Debug.assert(!state.semanticDiagnosticsPerFile);
                    // We dont need to cache the diagnostics just return them from program
                    return state.program.getSemanticDiagnostics(sourceFile, cancellationToken);
                }
                if (sourceFile) {
                    return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
                }
                if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
                    // When semantic builder asks for diagnostics of the whole program,
                    // ensure that all the affected files are handled
                    var affected = void 0;
                    while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) {
                        doneWithAffectedFile(state, affected);
                    }
                }
                var diagnostics;
                for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) {
                    var sourceFile_2 = _a[_i];
                    diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
                }
                return diagnostics || ts.emptyArray;
            }
        }
        ts.createBuilderProgram = createBuilderProgram;
    })(ts || (ts = {}));
    (function (ts) {
        function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
            return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
        }
        ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
        function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
            return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
        }
        ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
        function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
            var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram;
            return {
                // Only return program, all other methods are not implemented
                getProgram: function () { return program; },
                getState: ts.notImplemented,
                getCompilerOptions: ts.notImplemented,
                getSourceFile: ts.notImplemented,
                getSourceFiles: ts.notImplemented,
                getOptionsDiagnostics: ts.notImplemented,
                getGlobalDiagnostics: ts.notImplemented,
                getConfigFileParsingDiagnostics: ts.notImplemented,
                getSyntacticDiagnostics: ts.notImplemented,
                getSemanticDiagnostics: ts.notImplemented,
                emit: ts.notImplemented,
                getAllDependencies: ts.notImplemented,
                getCurrentDirectory: ts.notImplemented
            };
        }
        ts.createAbstractBuilder = createAbstractBuilder;
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        ts.maxNumberOfFilesToIterateForInvalidation = 256;
        function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
            var filesWithChangedSetOfUnresolvedImports;
            var filesWithInvalidatedResolutions;
            var filesWithInvalidatedNonRelativeUnresolvedImports;
            var allFilesHaveInvalidatedResolution = false;
            var nonRelativeExternalModuleResolutions = ts.createMultiMap();
            var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
            var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
            // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
            // The key in the map is source file's path.
            // The values are Map of resolutions with key being name lookedup.
            var resolvedModuleNames = ts.createMap();
            var perDirectoryResolvedModuleNames = ts.createMap();
            var nonRelaticeModuleNameCache = ts.createMap();
            var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelaticeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
            var resolvedTypeReferenceDirectives = ts.createMap();
            var perDirectoryResolvedTypeReferenceDirectives = ts.createMap();
            /**
             * These are the extensions that failed lookup files will have by default,
             * any other extension of failed lookup will be store that path in custom failed lookup path
             * This helps in not having to comb through all resolutions when files are added/removed
             * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
             */
            var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
            var customFailedLookupPaths = ts.createMap();
            var directoryWatchesOfFailedLookups = ts.createMap();
            var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
            var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
            // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
            var typeRootsWatches = ts.createMap();
            return {
                startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
                finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
                // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
                // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
                startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
                finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
                resolveModuleNames: resolveModuleNames,
                getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
                resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
                removeResolutionsOfFile: removeResolutionsOfFile,
                invalidateResolutionOfFile: invalidateResolutionOfFile,
                setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
                createHasInvalidatedResolution: createHasInvalidatedResolution,
                updateTypeRootsWatch: updateTypeRootsWatch,
                closeTypeRootsWatch: closeTypeRootsWatch,
                clear: clear
            };
            function getResolvedModule(resolution) {
                return resolution.resolvedModule;
            }
            function getResolvedTypeReferenceDirective(resolution) {
                return resolution.resolvedTypeReferenceDirective;
            }
            function isInDirectoryPath(dir, file) {
                if (dir === undefined || file.length <= dir.length) {
                    return false;
                }
                return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
            }
            function clear() {
                ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
                customFailedLookupPaths.clear();
                nonRelativeExternalModuleResolutions.clear();
                closeTypeRootsWatch();
                resolvedModuleNames.clear();
                resolvedTypeReferenceDirectives.clear();
                allFilesHaveInvalidatedResolution = false;
                // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
                // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
                clearPerDirectoryResolutions();
            }
            function startRecordingFilesWithChangedResolutions() {
                filesWithChangedSetOfUnresolvedImports = [];
            }
            function finishRecordingFilesWithChangedResolutions() {
                var collected = filesWithChangedSetOfUnresolvedImports;
                filesWithChangedSetOfUnresolvedImports = undefined;
                return collected;
            }
            function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
                if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
                    return false;
                }
                // Invalidated if file has unresolved imports
                var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
                return !!value && !!value.length;
            }
            function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
                if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) {
                    // Any file asked would have invalidated resolution
                    filesWithInvalidatedResolutions = undefined;
                    return ts.returnTrue;
                }
                var collected = filesWithInvalidatedResolutions;
                filesWithInvalidatedResolutions = undefined;
                return function (path) {
                    return (!!collected && collected.has(path)) ||
                        isFileWithInvalidatedNonRelativeUnresolvedImports(path);
                };
            }
            function clearPerDirectoryResolutions() {
                perDirectoryResolvedModuleNames.clear();
                nonRelaticeModuleNameCache.clear();
                perDirectoryResolvedTypeReferenceDirectives.clear();
                nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
                nonRelativeExternalModuleResolutions.clear();
            }
            function finishCachingPerDirectoryResolution() {
                allFilesHaveInvalidatedResolution = false;
                filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
                clearPerDirectoryResolutions();
                directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
                    if (watcher.refCount === 0) {
                        directoryWatchesOfFailedLookups.delete(path);
                        watcher.watcher.close();
                    }
                });
            }
            function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
                var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache);
                // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
                if (!resolutionHost.getGlobalCache) {
                    return primaryResult;
                }
                // otherwise try to load typings from @types
                var globalCache = resolutionHost.getGlobalCache();
                if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
                    // create different collection of failed lookup locations for second pass
                    // if it will fail and we've already found something during the first pass - we don't want to pollute its results
                    var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
                    if (resolvedModule) {
                        return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) };
                    }
                }
                // Default return the result from the first pass
                return primaryResult;
            }
            function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) {
                var path = resolutionHost.toPath(containingFile);
                var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
                var dirPath = ts.getDirectoryPath(path);
                var perDirectoryResolution = perDirectoryCache.get(dirPath);
                if (!perDirectoryResolution) {
                    perDirectoryResolution = ts.createMap();
                    perDirectoryCache.set(dirPath, perDirectoryResolution);
                }
                var resolvedModules = [];
                var compilerOptions = resolutionHost.getCompilationSettings();
                var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
                var seenNamesInFile = ts.createMap();
                for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
                    var name = names_2[_i];
                    var resolution = resolutionsInFile.get(name);
                    // Resolution is valid if it is present and not invalidated
                    if (!seenNamesInFile.has(name) &&
                        allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated ||
                        // If the name is unresolved import that was invalidated, recalculate
                        (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) {
                        var existingResolution = resolution;
                        var resolutionInDirectory = perDirectoryResolution.get(name);
                        if (resolutionInDirectory) {
                            resolution = resolutionInDirectory;
                        }
                        else {
                            resolution = loader(name, containingFile, compilerOptions, resolutionHost);
                            perDirectoryResolution.set(name, resolution);
                        }
                        resolutionsInFile.set(name, resolution);
                        watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution);
                        if (existingResolution) {
                            stopWatchFailedLookupLocationOfResolution(existingResolution);
                        }
                        if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
                            filesWithChangedSetOfUnresolvedImports.push(path);
                            // reset log changes to avoid recording the same file multiple times
                            logChanges = false;
                        }
                    }
                    ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
                    seenNamesInFile.set(name, true);
                    resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217
                }
                // Stop watching and remove the unused name
                resolutionsInFile.forEach(function (resolution, name) {
                    if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
                        stopWatchFailedLookupLocationOfResolution(resolution);
                        resolutionsInFile.delete(name);
                    }
                });
                return resolvedModules;
                function resolutionIsEqualTo(oldResolution, newResolution) {
                    if (oldResolution === newResolution) {
                        return true;
                    }
                    if (!oldResolution || !newResolution) {
                        return false;
                    }
                    var oldResult = getResolutionWithResolvedFileName(oldResolution);
                    var newResult = getResolutionWithResolvedFileName(newResolution);
                    if (oldResult === newResult) {
                        return true;
                    }
                    if (!oldResult || !newResult) {
                        return false;
                    }
                    return oldResult.resolvedFileName === newResult.resolvedFileName;
                }
            }
            function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) {
                return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, 
                /*reusedNames*/ undefined, /*logChanges*/ false);
            }
            function resolveModuleNames(moduleNames, containingFile, reusedNames) {
                return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
            }
            function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
                var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
                return cache && cache.get(moduleName);
            }
            function isNodeModulesDirectory(dirPath) {
                return ts.endsWith(dirPath, "/node_modules");
            }
            function isNodeModulesAtTypesDirectory(dirPath) {
                return ts.endsWith(dirPath, "/node_modules/@types");
            }
            /**
             * Filter out paths like
             * "/", "/user", "/user/username", "/user/username/folderAtRoot",
             * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
             * @param dirPath
             */
            function canWatchDirectory(dirPath) {
                var rootLength = ts.getRootLength(dirPath);
                if (dirPath.length === rootLength) {
                    // Ignore "/", "c:/"
                    return false;
                }
                var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
                if (nextDirectorySeparator === -1) {
                    // ignore "/user", "c:/users" or "c:/folderAtRoot"
                    return false;
                }
                if (dirPath.charCodeAt(0) !== 47 /* slash */ &&
                    dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) {
                    // Paths like c:/folderAtRoot/subFolder are allowed
                    return true;
                }
                for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
                    searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
                    if (searchIndex === 0) {
                        // Folder isnt at expected minimun levels
                        return false;
                    }
                }
                return true;
            }
            function filterFSRootDirectoriesToWatch(watchPath, dirPath) {
                if (!canWatchDirectory(dirPath)) {
                    watchPath.ignore = true;
                }
                return watchPath;
            }
            function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
                if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
                    failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
                    ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line
                    var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1);
                    if (subDirectoryInRoot !== -1) {
                        // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
                        return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) };
                    }
                    else {
                        // Always watch root directory non recursively
                        return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217
                    }
                }
                return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
            }
            function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
                // If directory path contains node module, get the most parent node_modules directory for watching
                while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) {
                    dir = ts.getDirectoryPath(dir);
                    dirPath = ts.getDirectoryPath(dirPath);
                }
                // If the directory is node_modules use it to watch, always watch it recursively
                if (isNodeModulesDirectory(dirPath)) {
                    return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath));
                }
                var nonRecursive = true;
                // Use some ancestor of the root directory
                var subDirectoryPath, subDirectory;
                if (rootPath !== undefined) {
                    while (!isInDirectoryPath(dirPath, rootPath)) {
                        var parentPath = ts.getDirectoryPath(dirPath);
                        if (parentPath === dirPath) {
                            break;
                        }
                        nonRecursive = false;
                        subDirectoryPath = dirPath;
                        subDirectory = dir;
                        dirPath = parentPath;
                        dir = ts.getDirectoryPath(dir);
                    }
                }
                return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath);
            }
            function isPathWithDefaultFailedLookupExtension(path) {
                return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
            }
            function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) {
                // No need to set the resolution refCount
                if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) {
                    if (resolution.refCount) {
                        resolution.refCount++;
                    }
                    else {
                        resolution.refCount = 1;
                        if (ts.isExternalModuleNameRelative(name)) {
                            watchFailedLookupLocationOfResolution(resolution);
                        }
                        else {
                            nonRelativeExternalModuleResolutions.add(name, resolution);
                        }
                    }
                }
            }
            function watchFailedLookupLocationOfResolution(resolution) {
                ts.Debug.assert(!!resolution.refCount);
                var failedLookupLocations = resolution.failedLookupLocations;
                var setAtRoot = false;
                for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
                    var failedLookupLocation = failedLookupLocations_1[_i];
                    var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
                    var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore;
                    if (!ignore) {
                        // If the failed lookup location path is not one of the supported extensions,
                        // store it in the custom path
                        if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
                            var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
                            customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
                        }
                        if (dirPath === rootPath) {
                            ts.Debug.assert(!nonRecursive);
                            setAtRoot = true;
                        }
                        else {
                            setDirectoryWatcher(dir, dirPath, nonRecursive);
                        }
                    }
                }
                if (setAtRoot) {
                    // This is always non recursive
                    setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
                }
            }
            function setRefCountToUndefined(resolution) {
                resolution.refCount = undefined;
            }
            function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
                var program = resolutionHost.getCurrentProgram();
                var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ?
                    setRefCountToUndefined : watchFailedLookupLocationOfResolution;
                resolutions.forEach(updateResolution);
            }
            function setDirectoryWatcher(dir, dirPath, nonRecursive) {
                var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
                if (dirWatcher) {
                    ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
                    dirWatcher.refCount++;
                }
                else {
                    directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
                }
            }
            function stopWatchFailedLookupLocationOfResolution(resolution) {
                if (!resolution.refCount) {
                    return;
                }
                resolution.refCount--;
                if (resolution.refCount) {
                    return;
                }
                var failedLookupLocations = resolution.failedLookupLocations;
                var removeAtRoot = false;
                for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
                    var failedLookupLocation = failedLookupLocations_2[_i];
                    var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
                    var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
                    if (!ignore) {
                        var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
                        if (refCount) {
                            if (refCount === 1) {
                                customFailedLookupPaths.delete(failedLookupLocationPath);
                            }
                            else {
                                ts.Debug.assert(refCount > 1);
                                customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
                            }
                        }
                        if (dirPath === rootPath) {
                            removeAtRoot = true;
                        }
                        else {
                            removeDirectoryWatcher(dirPath);
                        }
                    }
                }
                if (removeAtRoot) {
                    removeDirectoryWatcher(rootPath);
                }
            }
            function removeDirectoryWatcher(dirPath) {
                var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
                // Do not close the watcher yet since it might be needed by other failed lookup locations.
                dirWatcher.refCount--;
            }
            function createDirectoryWatcher(directory, dirPath, nonRecursive) {
                return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
                    var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
                    if (cachedDirectoryStructureHost) {
                        // Since the file existence changed, update the sourceFiles cache
                        cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
                    }
                    if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
                        resolutionHost.onInvalidatedResolution();
                    }
                }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
            }
            function removeResolutionsOfFileFromCache(cache, filePath) {
                // Deleted file, stop watching failed lookups for all the resolutions in the file
                var resolutions = cache.get(filePath);
                if (resolutions) {
                    resolutions.forEach(stopWatchFailedLookupLocationOfResolution);
                    cache.delete(filePath);
                }
            }
            function removeResolutionsOfFile(filePath) {
                removeResolutionsOfFileFromCache(resolvedModuleNames, filePath);
                removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath);
            }
            function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) {
                var seen = ts.createMap();
                cache.forEach(function (resolutions, containingFilePath) {
                    var dirPath = ts.getDirectoryPath(containingFilePath);
                    var seenInDir = seen.get(dirPath);
                    if (!seenInDir) {
                        seenInDir = ts.createMap();
                        seen.set(dirPath, seenInDir);
                    }
                    resolutions.forEach(function (resolution, name) {
                        if (seenInDir.has(name)) {
                            return;
                        }
                        seenInDir.set(name, true);
                        if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) {
                            // Mark the file as needing re-evaluation of module resolution instead of using it blindly.
                            resolution.isInvalidated = true;
                            (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
                        }
                    });
                });
            }
            function hasReachedResolutionIterationLimit() {
                var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation;
                return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize;
            }
            function invalidateResolutions(isInvalidatedResolution) {
                // If more than maxNumberOfFilesToIterateForInvalidation present,
                // just invalidated all files and recalculate the resolutions for files instead
                if (hasReachedResolutionIterationLimit()) {
                    allFilesHaveInvalidatedResolution = true;
                    return;
                }
                invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule);
                invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective);
            }
            function invalidateResolutionOfFile(filePath) {
                removeResolutionsOfFile(filePath);
                invalidateResolutions(
                // Resolution is invalidated if the resulting file name is same as the deleted file path
                function (resolution, getResolutionWithResolvedFileName) {
                    var result = getResolutionWithResolvedFileName(resolution);
                    return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217
                });
            }
            function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
                ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
                filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
            }
            function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
                var isChangedFailedLookupLocation;
                if (isCreatingWatchedDirectory) {
                    // Watching directory is created
                    // Invalidate any resolution has failed lookup in this directory
                    isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
                }
                else {
                    // Some file or directory in the watching directory is created
                    // Return early if it does not have any of the watching extension or not the custom failed lookup path
                    var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
                    if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) ||
                        isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) {
                        // Invalidate any resolution from this directory
                        isChangedFailedLookupLocation = function (location) {
                            var locationPath = resolutionHost.toPath(location);
                            return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
                        };
                    }
                    else {
                        if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
                            return false;
                        }
                        // Ignore emits from the program
                        if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
                            return false;
                        }
                        // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
                        isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
                    }
                }
                var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); };
                var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size;
                invalidateResolutions(
                // Resolution is invalidated if the resulting file name is same as the deleted file path
                hasChangedFailedLookupLocation);
                return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount;
            }
            function closeTypeRootsWatch() {
                ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
            }
            function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
                if (allFilesHaveInvalidatedResolution) {
                    return undefined;
                }
                if (isInDirectoryPath(rootPath, typeRootPath)) {
                    return rootPath;
                }
                var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore;
                return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined;
            }
            function createTypeRootsWatch(typeRootPath, typeRoot) {
                // Create new watch and recursive info
                return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
                    var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
                    if (cachedDirectoryStructureHost) {
                        // Since the file existence changed, update the sourceFiles cache
                        cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
                    }
                    // For now just recompile
                    // We could potentially store more data here about whether it was/would be really be used or not
                    // and with that determine to trigger compilation but for now this is enough
                    resolutionHost.onChangedAutomaticTypeDirectiveNames();
                    // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
                    // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
                    var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
                    if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
                        resolutionHost.onInvalidatedResolution();
                    }
                }, 1 /* Recursive */);
            }
            /**
             * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
             * To be called when compiler options change
             */
            function updateTypeRootsWatch() {
                var options = resolutionHost.getCompilationSettings();
                if (options.types) {
                    // No need to do any watch since resolution cache is going to handle the failed lookups
                    // for the types added by this
                    closeTypeRootsWatch();
                    return;
                }
                // we need to assume the directories exist to ensure that we can get all the type root directories that get included
                // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
                var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
                if (typeRoots) {
                    ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
                        createNewValue: createTypeRootsWatch,
                        onDeleteValue: ts.closeFileWatcher
                    });
                }
                else {
                    closeTypeRootsWatch();
                }
            }
            /**
             * Use this function to return if directory exists to get type roots to watch
             * If we return directory exists then only the paths will be added to type roots
             * Hence return true for all directories except root directories which are filtered from watching
             */
            function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
                var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
                var dirPath = resolutionHost.toPath(dir);
                return dirPath === rootPath || canWatchDirectory(dirPath);
            }
        }
        ts.createResolutionCache = createResolutionCache;
    })(ts || (ts = {}));
    // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
    /* @internal */
    var ts;
    (function (ts) {
        var moduleSpecifiers;
        (function (moduleSpecifiers) {
            var RelativePreference;
            (function (RelativePreference) {
                RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
                RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
                RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
            })(RelativePreference || (RelativePreference = {}));
            // See UserPreferences#importPathEnding
            var Ending;
            (function (Ending) {
                Ending[Ending["Minimal"] = 0] = "Minimal";
                Ending[Ending["Index"] = 1] = "Index";
                Ending[Ending["JsExtension"] = 2] = "JsExtension";
            })(Ending || (Ending = {}));
            function getPreferences(_a, compilerOptions, importingSourceFile) {
                var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
                return {
                    relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
                    ending: getEnding(),
                };
                function getEnding() {
                    switch (importModuleSpecifierEnding) {
                        case "minimal": return 0 /* Minimal */;
                        case "index": return 1 /* Index */;
                        case "js": return 2 /* JsExtension */;
                        default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
                            : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
                    }
                }
            }
            function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
                return {
                    relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
                    ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */
                        : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
                };
            }
            function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) {
                var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
                if (res === oldImportSpecifier)
                    return undefined;
                return res;
            }
            moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
            // Note: importingSourceFile is just for usesJsExtensionOnImports
            function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) {
                if (preferences === void 0) {
                    preferences = {};
                }
                return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile));
            }
            moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
            function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) {
                var info = getInfo(importingSourceFileName, host);
                var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap);
                return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
                    getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
            }
            // Returns an import for each symlink and for the realpath.
            function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) {
                var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
                if (ambient)
                    return [ambient];
                var info = getInfo(importingSourceFile.path, host);
                var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
                var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap);
                var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
                var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
                return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
            }
            moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
            // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
            function getInfo(importingSourceFileName, host) {
                var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
                var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
                return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
            }
            function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
                var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
                var ending = _b.ending, relativePreference = _b.relativePreference;
                var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
                var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) ||
                    removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
                if (!baseUrl || relativePreference === 0 /* Relative */) {
                    return relativePath;
                }
                var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
                if (!relativeToBaseUrl) {
                    return relativePath;
                }
                var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
                var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
                var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
                if (relativePreference === 1 /* NonRelative */) {
                    return nonRelative;
                }
                if (relativePreference !== 2 /* Auto */)
                    ts.Debug.assertNever(relativePreference);
                // Prefer a relative import over a baseUrl import if it has fewer components.
                return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
            }
            function countPathComponents(path) {
                var count = 0;
                for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
                    if (path.charCodeAt(i) === 47 /* slash */)
                        count++;
                }
                return count;
            }
            function usesJsExtensionOnImports(_a) {
                var imports = _a.imports;
                return ts.firstDefined(imports, function (_a) {
                    var text = _a.text;
                    return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined;
                }) || false;
            }
            function stringsEqual(a, b, getCanonicalFileName) {
                return getCanonicalFileName(a) === getCanonicalFileName(b);
            }
            // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
            // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
            function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
                return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
            }
            function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
                var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
                var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
                while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
                    !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
                    stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) {
                    aParts.pop();
                    bParts.pop();
                }
                return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
            }
            function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
                var result = ts.createMap();
                var symlinks = ts.mapDefined(files, function (sf) {
                    return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
                        return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
                    });
                });
                for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
                    var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
                    var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
                    result.set(commonOriginal, commonResolved);
                }
                return result;
            }
            /**
             * Looks for existing imports that use symlinks to this module.
             * Symlinks will be returned first so they are preferred over the real path.
             */
            function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) {
                var redirects = redirectTargetsMap.get(importedFileName);
                var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName];
                var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : "";
                var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
                var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd);
                var result = [];
                var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
                links.forEach(function (resolved, path) {
                    if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
                        return; // Don't want to a package to globally import from itself
                    }
                    var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
                    if (target === undefined)
                        return;
                    var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
                    var option = ts.resolvePath(path, relative);
                    if (!host.fileExists || host.fileExists(option)) {
                        result.push(option);
                    }
                });
                result.push.apply(result, targets);
                return result;
            }
            function tryGetModuleNameFromAmbientModule(moduleSymbol) {
                var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
                if (decl) {
                    return decl.name.text;
                }
            }
            function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
                for (var key in paths) {
                    for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
                        var patternText_1 = _a[_i];
                        var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
                        var indexOfStar = pattern.indexOf("*");
                        if (indexOfStar !== -1) {
                            var prefix = pattern.substr(0, indexOfStar);
                            var suffix = pattern.substr(indexOfStar + 1);
                            if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
                                ts.startsWith(relativeToBaseUrl, prefix) &&
                                ts.endsWith(relativeToBaseUrl, suffix) ||
                                !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
                                var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
                                return key.replace("*", matchedStar);
                            }
                        }
                        else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
                            return key;
                        }
                    }
                }
            }
            function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
                var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
                if (normalizedTargetPath === undefined) {
                    return undefined;
                }
                var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
                var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
                return ts.removeFileExtension(relativePath);
            }
            function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) {
                var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
                var parts = getNodeModulePathParts(moduleFileName);
                if (!parts) {
                    return undefined;
                }
                var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex);
                var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
                var packageJsonContent = host.fileExists(packageJsonPath)
                    ? JSON.parse(host.readFile(packageJsonPath))
                    : undefined;
                var versionPaths = packageJsonContent && packageJsonContent.typesVersions
                    ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
                    : undefined;
                if (versionPaths) {
                    var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1);
                    var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
                    if (fromPaths !== undefined) {
                        moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths);
                    }
                }
                // Simplify the full file path to something that can be resolved by Node.
                // If the module could be imported by a directory name, use that directory's name
                var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
                // Get a path that's relative to node_modules or the importing file's path
                // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
                if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex))))
                    return undefined;
                // If the module was found in @types, get the actual Node package name
                var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
                var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
                // For classic resolution, only allow importing from node_modules/@types, not other node_modules
                return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
                function getDirectoryOrExtensionlessFileName(path) {
                    // If the file is the main module, it can be imported by the package name
                    if (packageJsonContent) {
                        var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
                        if (mainFileRelative) {
                            var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
                            if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) {
                                return packageRootPath;
                            }
                        }
                    }
                    // We still have a file name - remove the extension
                    var fullModulePathWithoutExtension = ts.removeFileExtension(path);
                    // If the file is /index, it can be imported by its directory name
                    // IFF there is not _also_ a file by the same name
                    if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
                        return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
                    }
                    return fullModulePathWithoutExtension;
                }
            }
            function tryGetAnyFileFromPath(host, path) {
                // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
                var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
                for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
                    var e = extensions_3[_i];
                    var fullPath = path + e;
                    if (host.fileExists(fullPath)) { // TODO: GH#18217
                        return fullPath;
                    }
                }
            }
            function getNodeModulePathParts(fullPath) {
                // If fullPath can't be valid module file within node_modules, returns undefined.
                // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
                // Returns indices:                       ^            ^                                                      ^             ^
                var topLevelNodeModulesIndex = 0;
                var topLevelPackageNameIndex = 0;
                var packageRootIndex = 0;
                var fileNameIndex = 0;
                var States;
                (function (States) {
                    States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
                    States[States["NodeModules"] = 1] = "NodeModules";
                    States[States["Scope"] = 2] = "Scope";
                    States[States["PackageContent"] = 3] = "PackageContent";
                })(States || (States = {}));
                var partStart = 0;
                var partEnd = 0;
                var state = 0 /* BeforeNodeModules */;
                while (partEnd >= 0) {
                    partStart = partEnd;
                    partEnd = fullPath.indexOf("/", partStart + 1);
                    switch (state) {
                        case 0 /* BeforeNodeModules */:
                            if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
                                topLevelNodeModulesIndex = partStart;
                                topLevelPackageNameIndex = partEnd;
                                state = 1 /* NodeModules */;
                            }
                            break;
                        case 1 /* NodeModules */:
                        case 2 /* Scope */:
                            if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
                                state = 2 /* Scope */;
                            }
                            else {
                                packageRootIndex = partEnd;
                                state = 3 /* PackageContent */;
                            }
                            break;
                        case 3 /* PackageContent */:
                            if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
                                state = 1 /* NodeModules */;
                            }
                            else {
                                state = 3 /* PackageContent */;
                            }
                            break;
                    }
                }
                fileNameIndex = partStart;
                return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
            }
            function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
                return ts.firstDefined(rootDirs, function (rootDir) {
                    var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
                    return isPathRelativeToParent(relativePath) ? undefined : relativePath;
                });
            }
            function removeExtensionAndIndexPostFix(fileName, ending, options) {
                if (ts.fileExtensionIs(fileName, ".json" /* Json */))
                    return fileName;
                var noExtension = ts.removeFileExtension(fileName);
                switch (ending) {
                    case 0 /* Minimal */:
                        return ts.removeSuffix(noExtension, "/index");
                    case 1 /* Index */:
                        return noExtension;
                    case 2 /* JsExtension */:
                        return noExtension + getJSExtensionForFile(fileName, options);
                    default:
                        return ts.Debug.assertNever(ending);
                }
            }
            function getJSExtensionForFile(fileName, options) {
                var ext = ts.extensionFromPath(fileName);
                switch (ext) {
                    case ".ts" /* Ts */:
                    case ".d.ts" /* Dts */:
                        return ".js" /* Js */;
                    case ".tsx" /* Tsx */:
                        return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
                    case ".js" /* Js */:
                    case ".jsx" /* Jsx */:
                    case ".json" /* Json */:
                        return ext;
                    default:
                        return ts.Debug.assertNever(ext);
                }
            }
            function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
                var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
                return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
            }
            function isPathRelativeToParent(path) {
                return ts.startsWith(path, "..");
            }
        })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
    })(ts || (ts = {}));
    /*@internal*/
    var ts;
    (function (ts) {
        var sysFormatDiagnosticsHost = ts.sys ? {
            getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
            getNewLine: function () { return ts.sys.newLine; },
            getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
        } : undefined; // TODO: GH#18217
        /**
         * Create a function that reports error by writing to the system and handles the formating of the diagnostic
         */
        function createDiagnosticReporter(system, pretty) {
            var host = system === ts.sys ? sysFormatDiagnosticsHost : {
                getCurrentDirectory: function () { return system.getCurrentDirectory(); },
                getNewLine: function () { return system.newLine; },
                getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
            };
            if (!pretty) {
                return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
            }
            var diagnostics = new Array(1);
            return function (diagnostic) {
                diagnostics[0] = diagnostic;
                system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
                diagnostics[0] = undefined; // TODO: GH#18217
            };
        }
        ts.createDiagnosticReporter = createDiagnosticReporter;
        /**
         * @returns Whether the screen was cleared.
         */
        function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
            if (system.clearScreen &&
                !options.preserveWatchOutput &&
                !options.extendedDiagnostics &&
                !options.diagnostics &&
                ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
                system.clearScreen();
                return true;
            }
            return false;
        }
        /** @internal */
        ts.screenStartingMessageCodes = [
            ts.Diagnostics.Starting_compilation_in_watch_mode.code,
            ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
        ];
        function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
            return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
                ? newLine + newLine
                : newLine;
        }
        /**
         * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
         */
        function createWatchStatusReporter(system, pretty) {
            return pretty ?
                function (diagnostic, newLine, options) {
                    clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
                    var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] ";
                    output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
                    system.write(output);
                } :
                function (diagnostic, newLine, options) {
                    var output = "";
                    if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
                        output += newLine;
                    }
                    output += new Date().toLocaleTimeString() + " - ";
                    output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
                    system.write(output);
                };
        }
        ts.createWatchStatusReporter = createWatchStatusReporter;
        /** Parses config file using System interface */
        function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) {
            var host = system;
            host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); };
            var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
            host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
            return result;
        }
        ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
        /**
         * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
         */
        function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) {
            // First get and report any syntactic errors.
            var diagnostics = program.getConfigFileParsingDiagnostics().slice();
            var configFileParsingDiagnosticsLength = diagnostics.length;
            ts.addRange(diagnostics, program.getSyntacticDiagnostics());
            var reportSemanticDiagnostics = false;
            // If we didn't have any syntactic errors, then also try getting the global and
            // semantic errors.
            if (diagnostics.length === configFileParsingDiagnosticsLength) {
                ts.addRange(diagnostics, program.getOptionsDiagnostics());
                ts.addRange(diagnostics, program.getGlobalDiagnostics());
                if (diagnostics.length === configFileParsingDiagnosticsLength) {
                    reportSemanticDiagnostics = true;
                }
            }
            // Emit and report any errors we ran into.
            var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
            ts.addRange(diagnostics, emitDiagnostics);
            if (reportSemanticDiagnostics) {
                ts.addRange(diagnostics, program.getSemanticDiagnostics());
            }
            ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
            if (writeFileName) {
                var currentDir_1 = program.getCurrentDirectory();
                ts.forEach(emittedFiles, function (file) {
                    var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
                    writeFileName("TSFILE: " + filepath);
                });
                if (program.getCompilerOptions().listFiles) {
                    ts.forEach(program.getSourceFiles(), function (file) {
                        writeFileName(file.fileName);
                    });
                }
            }
            if (reportSummary) {
                reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length);
            }
            if (emitSkipped && diagnostics.length > 0) {
                // If the emitter didn't emit anything, then pass that value along.
                return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
            }
            else if (diagnostics.length > 0) {
                // The emitter emitted something, inform the caller if that happened in the presence
                // of diagnostics or not.
                return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
            }
            return ts.ExitStatus.Success;
        }
        ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
        var noopFileWatcher = { close: ts.noop };
        function createWatchHost(system, reportWatchStatus) {
            if (system === void 0) {
                system = ts.sys;
            }
            var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
            return {
                onWatchStatusChange: onWatchStatusChange,
                watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; },
                watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; },
                setTimeout: system.setTimeout ? (function (callback, ms) {
                    var args = [];
                    for (var _i = 2; _i < arguments.length; _i++) {
                        args[_i - 2] = arguments[_i];
                    }
                    var _a;
                    return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args));
                }) : ts.noop,
                clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop
            };
        }
        ts.createWatchHost = createWatchHost;
        /**
         * Creates the watch compiler host that can be extended with config file or root file names and options host
         */
        function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
            if (system === void 0) {
                system = ts.sys;
            }
            if (!createProgram) {
                createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
            }
            var host = system;
            host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!)
            var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; };
            var writeFileName = function (s) { return system.write(s + system.newLine); };
            var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout;
            return {
                useCaseSensitiveFileNames: useCaseSensitiveFileNames,
                getNewLine: function () { return system.newLine; },
                getCurrentDirectory: function () { return system.getCurrentDirectory(); },
                getDefaultLibLocation: getDefaultLibLocation,
                getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
                fileExists: function (path) { return system.fileExists(path); },
                readFile: function (path, encoding) { return system.readFile(path, encoding); },
                directoryExists: function (path) { return system.directoryExists(path); },
                getDirectories: function (path) { return system.getDirectories(path); },
                readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
                realpath: system.realpath && (function (path) { return system.realpath(path); }),
                getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }),
                watchFile: watchFile,
                watchDirectory: watchDirectory,
                setTimeout: setTimeout,
                clearTimeout: clearTimeout,
                trace: function (s) { return system.write(s); },
                onWatchStatusChange: onWatchStatusChange,
                createDirectory: function (path) { return system.createDirectory(path); },
                writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
                onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
                createHash: system.createHash && (function (s) { return system.createHash(s); }),
                createProgram: createProgram,
                afterProgramCreate: emitFilesAndReportErrorUsingBuilder
            };
            function getDefaultLibLocation() {
                return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
            }
            function emitFilesAndReportErrorUsingBuilder(builderProgram) {
                var compilerOptions = builderProgram.getCompilerOptions();
                var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
                var reportSummary = function (errorCount) {
                    if (errorCount === 1) {
                        onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions);
                    }
                    else {
                        onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions);
                    }
                };
                emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary);
            }
        }
        /**
         * Report error and exit
         */
        function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
            reportDiagnostic(diagnostic);
            system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
        }
        /**
         * Creates the watch compiler host from system for config file in watch mode
         */
        function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) {
            var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
            var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
            host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
            host.configFileName = configFileName;
            host.optionsToExtend = optionsToExtend;
            return host;
        }
        ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
        /**
         * Creates the watch compiler host from system for compiling root files and options in watch mode
         */
        function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
            var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
            host.rootFiles = rootFiles;
            host.options = options;
            host.projectReferences = projectReferences;
            return host;
        }
        ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
    })(ts || (ts = {}));
    (function (ts) {
        function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
            if (ts.isArray(rootFilesOrConfigFileName)) {
                return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217
            }
            else {
                return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus);
            }
        }
        ts.createWatchCompilerHost = createWatchCompilerHost;
        var initialVersion = 1;
        function createWatchProgram(host) {
            var builderProgram;
            var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
            var missingFilesMap; // Map of file watchers for the missing files
            var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
            var timerToUpdateProgram; // timer callback to recompile the program
            var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
            var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files
            var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
            var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
            var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
            var currentDirectory = host.getCurrentDirectory();
            var getCurrentDirectory = function () { return currentDirectory; };
            var readFile = function (path, encoding) { return host.readFile(path, encoding); };
            var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram;
            var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences;
            var configFileSpecs;
            var configFileParsingDiagnostics;
            var hasChangedConfigFileParsingErrors = false;
            var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
            if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) {
                host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost);
            }
            var directoryStructureHost = cachedDirectoryStructureHost || host;
            var parseConfigFileHost = {
                useCaseSensitiveFileNames: useCaseSensitiveFileNames,
                readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); },
                fileExists: function (path) { return host.fileExists(path); },
                readFile: readFile,
                getCurrentDirectory: getCurrentDirectory,
                onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic
            };
            // From tsc we want to get already parsed result and hence check for rootFileNames
            var newLine = updateNewLine();
            if (configFileName && host.configFileParsingResult) {
                setConfigFileParsingResult(host.configFileParsingResult);
                newLine = updateNewLine();
            }
            reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
            if (configFileName && !host.configFileParsingResult) {
                newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
                ts.Debug.assert(!rootFileNames);
                parseConfigFile();
                newLine = updateNewLine();
            }
            var trace = host.trace && (function (s) { host.trace(s + newLine); });
            var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose :
                compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
            var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217
            var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory;
            var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
            writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
            if (configFileName) {
                watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file");
            }
            var compilerHost = {
                // Members for CompilerHost
                getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); },
                getSourceFileByPath: getVersionedSourceFileByPath,
                getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }),
                getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
                writeFile: writeFile,
                getCurrentDirectory: getCurrentDirectory,
                useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
                getCanonicalFileName: getCanonicalFileName,
                getNewLine: function () { return newLine; },
                fileExists: fileExists,
                readFile: readFile,
                trace: trace,
                directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }),
                getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })),
                realpath: host.realpath && (function (s) { return host.realpath(s); }),
                getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }),
                onReleaseOldSourceFile: onReleaseOldSourceFile,
                createHash: host.createHash && (function (data) { return host.createHash(data); }),
                // Members for ResolutionCacheHost
                toPath: toPath,
                getCompilationSettings: function () { return compilerOptions; },
                watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); },
                watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); },
                getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; },
                onInvalidatedResolution: scheduleProgramUpdate,
                onChangedAutomaticTypeDirectiveNames: function () {
                    hasChangedAutomaticTypeDirectiveNames = true;
                    scheduleProgramUpdate();
                },
                maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation,
                getCurrentProgram: getCurrentProgram,
                writeLog: writeLog,
                readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); },
            };
            // Cache for the module resolution
            var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
                ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
                currentDirectory, 
            /*logChangesWhenResolvingModule*/ false);
            // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
            compilerHost.resolveModuleNames = host.resolveModuleNames ?
                (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) :
                (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); });
            compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
                (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) :
                (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); });
            var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
            synchronizeProgram();
            // Update the wild card directory watch
            watchConfigFileWildCardDirectories();
            return configFileName ?
                { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
                { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
            function getCurrentBuilderProgram() {
                return builderProgram;
            }
            function getCurrentProgram() {
                return builderProgram && builderProgram.getProgram();
            }
            function synchronizeProgram() {
                writeLog("Synchronizing program");
                var program = getCurrentProgram();
                if (hasChangedCompilerOptions) {
                    newLine = updateNewLine();
                    if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
                        resolutionCache.clear();
                    }
                }
                // All resolutions are invalid if user provided resolutions
                var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
                if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
                    if (hasChangedConfigFileParsingErrors) {
                        builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
                        hasChangedConfigFileParsingErrors = false;
                    }
                }
                else {
                    createNewProgram(program, hasInvalidatedResolution);
                }
                if (host.afterProgramCreate) {
                    host.afterProgramCreate(builderProgram);
                }
                return builderProgram;
            }
            function createNewProgram(program, hasInvalidatedResolution) {
                // Compile the program
                if (watchLogLevel !== ts.WatchLogLevel.None) {
                    writeLog("CreatingProgramWith::");
                    writeLog("  roots: " + JSON.stringify(rootFileNames));
                    writeLog("  options: " + JSON.stringify(compilerOptions));
                }
                var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
                hasChangedCompilerOptions = false;
                hasChangedConfigFileParsingErrors = false;
                resolutionCache.startCachingPerDirectoryResolution();
                compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
                compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
                builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
                resolutionCache.finishCachingPerDirectoryResolution();
                // Update watches
                ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
                if (needsUpdateInTypeRootWatch) {
                    resolutionCache.updateTypeRootsWatch();
                }
                if (missingFilePathsRequestedForRelease) {
                    // These are the paths that program creater told us as not in use any more but were missing on the disk.
                    // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
                    // if there is already watcher for it (for missing files)
                    // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
                    // so that at later time we have correct result of their presence
                    for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
                        var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
                        if (!missingFilesMap.has(missingFilePath)) {
                            sourceFilesCache.delete(missingFilePath);
                        }
                    }
                    missingFilePathsRequestedForRelease = undefined;
                }
            }
            function updateRootFileNames(files) {
                ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
                rootFileNames = files;
                scheduleProgramUpdate();
            }
            function updateNewLine() {
                return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
            }
            function toPath(fileName) {
                return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
            }
            function isFileMissingOnHost(hostSourceFile) {
                return typeof hostSourceFile === "number";
            }
            function isFilePresentOnHost(hostSourceFile) {
                return !!hostSourceFile.sourceFile;
            }
            function fileExists(fileName) {
                var path = toPath(fileName);
                // If file is missing on host from cache, we can definitely say file doesnt exist
                // otherwise we need to ensure from the disk
                if (isFileMissingOnHost(sourceFilesCache.get(path))) {
                    return true;
                }
                return directoryStructureHost.fileExists(fileName);
            }
            function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
                var hostSourceFile = sourceFilesCache.get(path);
                // No source file on the host
                if (isFileMissingOnHost(hostSourceFile)) {
                    return undefined;
                }
                // Create new source file if requested or the versions dont match
                if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
                    var sourceFile = getNewSourceFile();
                    if (hostSourceFile) {
                        if (shouldCreateNewSourceFile) {
                            hostSourceFile.version++;
                        }
                        if (sourceFile) {
                            // Set the source file and create file watcher now that file was present on the disk
                            hostSourceFile.sourceFile = sourceFile;
                            sourceFile.version = hostSourceFile.version.toString();
                            if (!hostSourceFile.fileWatcher) {
                                hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file");
                            }
                        }
                        else {
                            // There is no source file on host any more, close the watch, missing file paths will track it
                            if (isFilePresentOnHost(hostSourceFile)) {
                                hostSourceFile.fileWatcher.close();
                            }
                            sourceFilesCache.set(path, hostSourceFile.version);
                        }
                    }
                    else {
                        if (sourceFile) {
                            sourceFile.version = initialVersion.toString();
                            var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file");
                            sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
                        }
                        else {
                            sourceFilesCache.set(path, initialVersion);
                        }
                    }
                    return sourceFile;
                }
                return hostSourceFile.sourceFile;
                function getNewSourceFile() {
                    var text;
                    try {
                        ts.performance.mark("beforeIORead");
                        text = host.readFile(fileName, compilerOptions.charset);
                        ts.performance.mark("afterIORead");
                        ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
                    }
                    catch (e) {
                        if (onError) {
                            onError(e.message);
                        }
                    }
                    return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
                }
            }
            function nextSourceFileVersion(path) {
                var hostSourceFile = sourceFilesCache.get(path);
                if (hostSourceFile !== undefined) {
                    if (isFileMissingOnHost(hostSourceFile)) {
                        // The next version, lets set it as presence unknown file
                        sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
                    }
                    else {
                        hostSourceFile.version++;
                    }
                }
            }
            function getSourceVersion(path) {
                var hostSourceFile = sourceFilesCache.get(path);
                return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
            }
            function onReleaseOldSourceFile(oldSourceFile, _oldOptions) {
                var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path);
                // If this is the source file thats in the cache and new program doesnt need it,
                // remove the cached entry.
                // Note we arent deleting entry if file became missing in new program or
                // there was version update and new source file was created.
                if (hostSourceFileInfo) {
                    // record the missing file paths so they can be removed later if watchers arent tracking them
                    if (isFileMissingOnHost(hostSourceFileInfo)) {
                        (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
                    }
                    else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
                        if (hostSourceFileInfo.fileWatcher) {
                            hostSourceFileInfo.fileWatcher.close();
                        }
                        sourceFilesCache.delete(oldSourceFile.path);
                        resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
                    }
                }
            }
            function reportWatchDiagnostic(message) {
                if (host.onWatchStatusChange) {
                    host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
                }
            }
            // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
            // operations (such as saving all modified files in an editor) a chance to complete before we kick
            // off a new compilation.
            function scheduleProgramUpdate() {
                if (!host.setTimeout || !host.clearTimeout) {
                    return;
                }
                if (timerToUpdateProgram) {
                    host.clearTimeout(timerToUpdateProgram);
                }
                writeLog("Scheduling update");
                timerToUpdateProgram = host.setTimeout(updateProgram, 250);
            }
            function scheduleProgramReload() {
                ts.Debug.assert(!!configFileName);
                reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
                scheduleProgramUpdate();
            }
            function updateProgram() {
                timerToUpdateProgram = undefined;
                reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
                switch (reloadLevel) {
                    case ts.ConfigFileProgramReloadLevel.Partial:
                        return reloadFileNamesFromConfigFile();
                    case ts.ConfigFileProgramReloadLevel.Full:
                        return reloadConfigFile();
                    default:
                        synchronizeProgram();
                        return;
                }
            }
            function reloadFileNamesFromConfigFile() {
                writeLog("Reloading new file names and options");
                var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost);
                if (result.fileNames.length) {
                    configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); });
                    hasChangedConfigFileParsingErrors = true;
                }
                else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) {
                    configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName));
                    hasChangedConfigFileParsingErrors = true;
                }
                rootFileNames = result.fileNames;
                // Update the program
                synchronizeProgram();
            }
            function reloadConfigFile() {
                writeLog("Reloading config file: " + configFileName);
                reloadLevel = ts.ConfigFileProgramReloadLevel.None;
                if (cachedDirectoryStructureHost) {
                    cachedDirectoryStructureHost.clearCache();
                }
                parseConfigFile();
                hasChangedCompilerOptions = true;
                synchronizeProgram();
                // Update the wild card directory watch
                watchConfigFileWildCardDirectories();
            }
            function parseConfigFile() {
                setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217
            }
            function setConfigFileParsingResult(configFileParseResult) {
                rootFileNames = configFileParseResult.fileNames;
                compilerOptions = configFileParseResult.options;
                configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
                projectReferences = configFileParseResult.projectReferences;
                configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult);
                hasChangedConfigFileParsingErrors = true;
            }
            function onSourceFileChange(fileName, eventKind, path) {
                updateCachedSystemWithFile(fileName, path, eventKind);
                // Update the source file cache
                if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
                    resolutionCache.invalidateResolutionOfFile(path);
                }
                nextSourceFileVersion(path);
                // Update the program
                scheduleProgramUpdate();
            }
            function updateCachedSystemWithFile(fileName, path, eventKind) {
                if (cachedDirectoryStructureHost) {
                    cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
                }
            }
            function watchMissingFilePath(missingFilePath) {
                return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file");
            }
            function onMissingFileChange(fileName, eventKind, missingFilePath) {
                updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
                if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
                    missingFilesMap.get(missingFilePath).close();
                    missingFilesMap.delete(missingFilePath);
                    // Delete the entry in the source files cache so that new source file is created
                    nextSourceFileVersion(missingFilePath);
                    // When a missing file is created, we should update the graph.
                    scheduleProgramUpdate();
                }
            }
            function watchConfigFileWildCardDirectories() {
                if (configFileSpecs) {
                    ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
                }
                else if (watchedWildcardDirectories) {
                    ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
                }
            }
            function watchWildcardDirectory(directory, flags) {
                return watchDirectory(host, directory, function (fileOrDirectory) {
                    ts.Debug.assert(!!configFileName);
                    var fileOrDirectoryPath = toPath(fileOrDirectory);
                    // Since the file existance changed, update the sourceFiles cache
                    if (cachedDirectoryStructureHost) {
                        cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
                    }
                    nextSourceFileVersion(fileOrDirectoryPath);
                    // If the the added or created file or directory is not supported file name, ignore the file
                    // But when watched directory is added/removed, we need to reload the file list
                    if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
                        writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
                        return;
                    }
                    // Reload is pending, do the reload
                    if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
                        reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
                        // Schedule Update the program
                        scheduleProgramUpdate();
                    }
                }, flags, "Wild card directories");
            }
            function ensureDirectoriesExist(directoryPath) {
                if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) {
                    var parentDirectory = ts.getDirectoryPath(directoryPath);
                    ensureDirectoriesExist(parentDirectory);
                    host.createDirectory(directoryPath);
                }
            }
            function writeFile(fileName, text, writeByteOrderMark, onError) {
                try {
                    ts.performance.mark("beforeIOWrite");
                    ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName)));
                    host.writeFile(fileName, text, writeByteOrderMark);
                    ts.performance.mark("afterIOWrite");
                    ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
                }
                catch (e) {
                    if (onError) {
                        onError(e.message);
                    }
                }
            }
        }
        ts.createWatchProgram = createWatchProgram;
    })(ts || (ts = {}));
    // Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch
    /*@internal*/
    var ts;
    (function (ts) {
        var minimumDate = new Date(-8640000000000000);
        var maximumDate = new Date(8640000000000000);
        var BuildResultFlags;
        (function (BuildResultFlags) {
            BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
            /**
             * No errors of any kind occurred during build
             */
            BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
            /**
             * None of the .d.ts files emitted by this build were
             * different from the existing files on disk
             */
            BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
            BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
            BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
            BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
            BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
            BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
            BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
        })(BuildResultFlags || (BuildResultFlags = {}));
        var UpToDateStatusType;
        (function (UpToDateStatusType) {
            UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
            UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
            /**
             * The project appears out of date because its upstream inputs are newer than its outputs,
             * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
             * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
             */
            UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
            UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
            UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
            UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
            UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
            UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
            UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
            /**
             * Projects with no outputs (i.e. "solution" files)
             */
            UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
        })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
        function createFileMap(toPath) {
            // tslint:disable-next-line:no-null-keyword
            var lookup = ts.createMap();
            return {
                setValue: setValue,
                getValue: getValue,
                removeKey: removeKey,
                forEach: forEach,
                hasKey: hasKey,
                getSize: getSize,
                clear: clear
            };
            function forEach(action) {
                lookup.forEach(action);
            }
            function hasKey(fileName) {
                return lookup.has(toPath(fileName));
            }
            function removeKey(fileName) {
                lookup.delete(toPath(fileName));
            }
            function setValue(fileName, value) {
                lookup.set(toPath(fileName), value);
            }
            function getValue(fileName) {
                return lookup.get(toPath(fileName));
            }
            function getSize() {
                return lookup.size;
            }
            function clear() {
                lookup.clear();
            }
        }
        function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
            var existingValue = configFileMap.getValue(resolved);
            var newValue;
            if (!existingValue) {
                newValue = createT();
                configFileMap.setValue(resolved, newValue);
            }
            return existingValue || newValue;
        }
        function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
            return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
        }
        function getOutputDeclarationFileName(inputFileName, configFile) {
            var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true);
            var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath);
            return ts.changeExtension(outputPath, ".d.ts" /* Dts */);
        }
        ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
        function getOutputJSFileName(inputFileName, configFile) {
            var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true);
            var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath);
            var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ :
                ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
            return ts.changeExtension(outputPath, newExtension);
        }
        function getOutputFileNames(inputFileName, configFile) {
            // outFile is handled elsewhere; .d.ts files don't generate outputs
            if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) {
                return ts.emptyArray;
            }
            var outputs = [];
            var js = getOutputJSFileName(inputFileName, configFile);
            outputs.push(js);
            if (configFile.options.sourceMap) {
                outputs.push(js + ".map");
            }
            if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) {
                var dts = getOutputDeclarationFileName(inputFileName, configFile);
                outputs.push(dts);
                if (configFile.options.declarationMap) {
                    outputs.push(dts + ".map");
                }
            }
            return outputs;
        }
        function getOutFileOutputs(project) {
            var out = project.options.outFile || project.options.out;
            if (!out) {
                return ts.Debug.fail("outFile must be set");
            }
            var outputs = [];
            outputs.push(out);
            if (project.options.sourceMap) {
                outputs.push(out + ".map");
            }
            if (ts.getEmitDeclarations(project.options)) {
                var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
                outputs.push(dts);
                if (project.options.declarationMap) {
                    outputs.push(dts + ".map");
                }
            }
            return outputs;
        }
        function rootDirOfOptions(opts, configFileName) {
            return opts.rootDir || ts.getDirectoryPath(configFileName);
        }
        function newer(date1, date2) {
            return date2 > date1 ? date2 : date1;
        }
        function isDeclarationFile(fileName) {
            return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
        }
        /**
         * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
         */
        function createBuilderStatusReporter(system, pretty) {
            return function (diagnostic) {
                var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - ";
                output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
                system.write(output);
            };
        }
        ts.createBuilderStatusReporter = createBuilderStatusReporter;
        function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) {
            if (system === void 0) {
                system = ts.sys;
            }
            var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system);
            host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
            host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
            host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
            host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
            host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
            return host;
        }
        ts.createSolutionBuilderHost = createSolutionBuilderHost;
        function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
            if (system === void 0) {
                system = ts.sys;
            }
            var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus);
            var watchHost = ts.createWatchHost(system, reportWatchStatus);
            host.onWatchStatusChange = watchHost.onWatchStatusChange;
            host.watchFile = watchHost.watchFile;
            host.watchDirectory = watchHost.watchDirectory;
            host.setTimeout = watchHost.setTimeout;
            host.clearTimeout = watchHost.clearTimeout;
            return host;
        }
        ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
        function getCompilerOptionsOfBuildOptions(buildOptions) {
            var result = {};
            ts.commonOptionsWithBuild.forEach(function (option) {
                result[option.name] = buildOptions[option.name];
            });
            return result;
        }
        /**
         * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but
         * can dynamically add/remove other projects based on changes on the rootNames' references
         * TODO: use SolutionBuilderWithWatchHost => watchedSolution
         *  use SolutionBuilderHost => Solution
         */
        function createSolutionBuilder(host, rootNames, defaultOptions) {
            var hostWithWatch = host;
            var currentDirectory = host.getCurrentDirectory();
            var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
            var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host);
            // State of the solution
            var options = defaultOptions;
            var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
            var configFileCache = createFileMap(toPath);
            /** Map from output file name to its pre-build timestamp */
            var unchangedOutputs = createFileMap(toPath);
            /** Map from config file name to up-to-date status */
            var projectStatus = createFileMap(toPath);
            var missingRoots = ts.createMap();
            var globalDependencyGraph;
            var writeFileName = function (s) { return host.trace && host.trace(s); };
            // Watch state
            var diagnostics = createFileMap(toPath);
            var projectPendingBuild = createFileMap(toPath);
            var projectErrorsReported = createFileMap(toPath);
            var invalidatedProjectQueue = [];
            var nextProjectToBuild = 0;
            var timerToBuildInvalidatedProject;
            var reportFileChangeDetected = false;
            // Watches for the solution
            var allWatchedWildcardDirectories = createFileMap(toPath);
            var allWatchedInputFiles = createFileMap(toPath);
            var allWatchedConfigFiles = createFileMap(toPath);
            return {
                buildAllProjects: buildAllProjects,
                getUpToDateStatusOfFile: getUpToDateStatusOfFile,
                cleanAllProjects: cleanAllProjects,
                resetBuildContext: resetBuildContext,
                getBuildGraph: getBuildGraph,
                invalidateProject: invalidateProject,
                buildInvalidatedProject: buildInvalidatedProject,
                resolveProjectName: resolveProjectName,
                startWatching: startWatching
            };
            function toPath(fileName) {
                return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
            }
            function resetBuildContext(opts) {
                if (opts === void 0) {
                    opts = defaultOptions;
                }
                options = opts;
                baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
                configFileCache.clear();
                unchangedOutputs.clear();
                projectStatus.clear();
                missingRoots.clear();
                globalDependencyGraph = undefined;
                diagnostics.clear();
                projectPendingBuild.clear();
                projectErrorsReported.clear();
                invalidatedProjectQueue.length = 0;
                nextProjectToBuild = 0;
                if (timerToBuildInvalidatedProject) {
                    clearTimeout(timerToBuildInvalidatedProject);
                    timerToBuildInvalidatedProject = undefined;
                }
                reportFileChangeDetected = false;
                ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); });
                ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
                ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
            }
            function isParsedCommandLine(entry) {
                return !!entry.options;
            }
            function parseConfigFile(configFilePath) {
                var value = configFileCache.getValue(configFilePath);
                if (value) {
                    return isParsedCommandLine(value) ? value : undefined;
                }
                var diagnostic;
                parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
                var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost);
                parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
                configFileCache.setValue(configFilePath, parsed || diagnostic);
                return parsed;
            }
            function reportStatus(message) {
                var args = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    args[_i - 1] = arguments[_i];
                }
                host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)));
            }
            function reportWatchStatus(message) {
                var args = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    args[_i - 1] = arguments[_i];
                }
                if (hostWithWatch.onWatchStatusChange) {
                    hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions);
                }
            }
            function startWatching() {
                var graph = getGlobalDependencyGraph();
                for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
                    var resolved = _a[_i];
                    // Watch this file
                    watchConfigFile(resolved);
                    var cfg = parseConfigFile(resolved);
                    if (cfg) {
                        // Update watchers for wildcard directories
                        watchWildCardDirectories(resolved, cfg);
                        // Watch input files
                        watchInputFiles(resolved, cfg);
                    }
                }
            }
            function watchConfigFile(resolved) {
                if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) {
                    allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () {
                        invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full);
                    }));
                }
            }
            function watchWildCardDirectories(resolved, parsed) {
                if (!options.watch)
                    return;
                ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) {
                    return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) {
                        var fileOrDirectoryPath = toPath(fileOrDirectory);
                        if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
                            // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`);
                            return;
                        }
                        if (isOutputFile(fileOrDirectory, parsed)) {
                            // writeLog(`${fileOrDirectory} is output file`);
                            return;
                        }
                        invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial);
                    }, !!(flags & 1 /* Recursive */));
                });
            }
            function watchInputFiles(resolved, parsed) {
                if (!options.watch)
                    return;
                ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), {
                    createNewValue: function (_key, input) {
                        return hostWithWatch.watchFile(input, function () {
                            invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None);
                        });
                    },
                    onDeleteValue: ts.closeFileWatcher,
                });
            }
            function isOutputFile(fileName, configFile) {
                if (configFile.options.noEmit)
                    return false;
                // ts or tsx files are not output
                if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
                    (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
                    return false;
                }
                // If options have --outFile or --out, check if its that
                var out = configFile.options.outFile || configFile.options.out;
                if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
                    return true;
                }
                // If declarationDir is specified, return if its a file in that directory
                if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) {
                    return true;
                }
                // If --outDir, check if file is in that directory
                if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) {
                    return true;
                }
                return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); });
            }
            function isSameFile(file1, file2) {
                return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
            }
            function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) {
                reportFileChangeDetected = true;
                invalidateResolvedProject(resolved, reloadLevel);
                scheduleBuildInvalidatedProject();
            }
            function getUpToDateStatusOfFile(configFileName) {
                return getUpToDateStatus(parseConfigFile(configFileName));
            }
            function getBuildGraph(configFileNames) {
                return createDependencyGraph(resolveProjectNames(configFileNames));
            }
            function getGlobalDependencyGraph() {
                return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames));
            }
            function getUpToDateStatus(project) {
                if (project === undefined) {
                    return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
                }
                var prior = projectStatus.getValue(project.options.configFilePath);
                if (prior !== undefined) {
                    return prior;
                }
                var actual = getUpToDateStatusWorker(project);
                projectStatus.setValue(project.options.configFilePath, actual);
                return actual;
            }
            function getUpToDateStatusWorker(project) {
                var newestInputFileName = undefined;
                var newestInputFileTime = minimumDate;
                // Get timestamps of input files
                for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
                    var inputFile = _a[_i];
                    if (!host.fileExists(inputFile)) {
                        return {
                            type: UpToDateStatusType.Unbuildable,
                            reason: inputFile + " does not exist"
                        };
                    }
                    var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
                    if (inputTime > newestInputFileTime) {
                        newestInputFileName = inputFile;
                        newestInputFileTime = inputTime;
                    }
                }
                // Collect the expected outputs of this project
                var outputs = getAllProjectOutputs(project);
                if (outputs.length === 0) {
                    return {
                        type: UpToDateStatusType.ContainerOnly
                    };
                }
                // Now see if all outputs are newer than the newest input
                var oldestOutputFileName = "(none)";
                var oldestOutputFileTime = maximumDate;
                var newestOutputFileName = "(none)";
                var newestOutputFileTime = minimumDate;
                var missingOutputFileName;
                var newestDeclarationFileContentChangedTime = minimumDate;
                var isOutOfDateWithInputs = false;
                for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
                    var output = outputs_1[_b];
                    // Output is missing; can stop checking
                    // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
                    if (!host.fileExists(output)) {
                        missingOutputFileName = output;
                        break;
                    }
                    var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
                    if (outputTime < oldestOutputFileTime) {
                        oldestOutputFileTime = outputTime;
                        oldestOutputFileName = output;
                    }
                    // If an output is older than the newest input, we can stop checking
                    // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
                    if (outputTime < newestInputFileTime) {
                        isOutOfDateWithInputs = true;
                        break;
                    }
                    if (outputTime > newestOutputFileTime) {
                        newestOutputFileTime = outputTime;
                        newestOutputFileName = output;
                    }
                    // Keep track of when the most recent time a .d.ts file was changed.
                    // In addition to file timestamps, we also keep track of when a .d.ts file
                    // had its file touched but not had its contents changed - this allows us
                    // to skip a downstream typecheck
                    if (isDeclarationFile(output)) {
                        var unchangedTime = unchangedOutputs.getValue(output);
                        if (unchangedTime !== undefined) {
                            newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime);
                        }
                        else {
                            var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
                            newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
                        }
                    }
                }
                var pseudoUpToDate = false;
                var usesPrepend = false;
                var upstreamChangedProject;
                if (project.projectReferences) {
                    projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream });
                    for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
                        var ref = _d[_c];
                        usesPrepend = usesPrepend || !!(ref.prepend);
                        var resolvedRef = ts.resolveProjectReferencePath(ref);
                        var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef));
                        // Its a circular reference ignore the status of this project
                        if (refStatus.type === UpToDateStatusType.ComputingUpstream) {
                            continue;
                        }
                        // An upstream project is blocked
                        if (refStatus.type === UpToDateStatusType.Unbuildable) {
                            return {
                                type: UpToDateStatusType.UpstreamBlocked,
                                upstreamProjectName: ref.path
                            };
                        }
                        // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
                        if (refStatus.type !== UpToDateStatusType.UpToDate) {
                            return {
                                type: UpToDateStatusType.UpstreamOutOfDate,
                                upstreamProjectName: ref.path
                            };
                        }
                        // If the upstream project's newest file is older than our oldest output, we
                        // can't be out of date because of it
                        if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
                            continue;
                        }
                        // If the upstream project has only change .d.ts files, and we've built
                        // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
                        if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
                            pseudoUpToDate = true;
                            upstreamChangedProject = ref.path;
                            continue;
                        }
                        // We have an output older than an upstream output - we are out of date
                        ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
                        return {
                            type: UpToDateStatusType.OutOfDateWithUpstream,
                            outOfDateOutputFileName: oldestOutputFileName,
                            newerProjectName: ref.path
                        };
                    }
                }
                if (missingOutputFileName !== undefined) {
                    return {
                        type: UpToDateStatusType.OutputMissing,
                        missingOutputFileName: missingOutputFileName
                    };
                }
                if (isOutOfDateWithInputs) {
                    return {
                        type: UpToDateStatusType.OutOfDateWithSelf,
                        outOfDateOutputFileName: oldestOutputFileName,
                        newerInputFileName: newestInputFileName
                    };
                }
                if (usesPrepend && pseudoUpToDate) {
                    return {
                        type: UpToDateStatusType.OutOfDateWithUpstream,
                        outOfDateOutputFileName: oldestOutputFileName,
                        newerProjectName: upstreamChangedProject
                    };
                }
                // Up to date
                return {
                    type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate,
                    newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
                    newestInputFileTime: newestInputFileTime,
                    newestOutputFileTime: newestOutputFileTime,
                    newestInputFileName: newestInputFileName,
                    newestOutputFileName: newestOutputFileName,
                    oldestOutputFileName: oldestOutputFileName
                };
            }
            function invalidateProject(configFileName, reloadLevel) {
                invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
            }
            function invalidateResolvedProject(resolved, reloadLevel) {
                if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
                    configFileCache.removeKey(resolved);
                    globalDependencyGraph = undefined;
                }
                projectStatus.removeKey(resolved);
                if (options.watch) {
                    diagnostics.removeKey(resolved);
                }
                addProjToQueue(resolved, reloadLevel);
            }
            /**
             * return true if new addition
             */
            function addProjToQueue(proj, reloadLevel) {
                var value = projectPendingBuild.getValue(proj);
                if (value === undefined) {
                    projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None);
                    invalidatedProjectQueue.push(proj);
                }
                else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) {
                    projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None);
                }
            }
            function getNextInvalidatedProject() {
                if (nextProjectToBuild < invalidatedProjectQueue.length) {
                    var project = invalidatedProjectQueue[nextProjectToBuild];
                    nextProjectToBuild++;
                    var reloadLevel = projectPendingBuild.getValue(project);
                    projectPendingBuild.removeKey(project);
                    if (!projectPendingBuild.getSize()) {
                        invalidatedProjectQueue.length = 0;
                        nextProjectToBuild = 0;
                    }
                    return { project: project, reloadLevel: reloadLevel };
                }
            }
            function hasPendingInvalidatedProjects() {
                return !!projectPendingBuild.getSize();
            }
            function scheduleBuildInvalidatedProject() {
                if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
                    return;
                }
                if (timerToBuildInvalidatedProject) {
                    hostWithWatch.clearTimeout(timerToBuildInvalidatedProject);
                }
                timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250);
            }
            function buildInvalidatedProject() {
                timerToBuildInvalidatedProject = undefined;
                if (reportFileChangeDetected) {
                    reportFileChangeDetected = false;
                    projectErrorsReported.clear();
                    reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
                }
                var buildProject = getNextInvalidatedProject();
                if (buildProject) {
                    buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel);
                    if (hasPendingInvalidatedProjects()) {
                        if (options.watch && !timerToBuildInvalidatedProject) {
                            scheduleBuildInvalidatedProject();
                        }
                    }
                    else {
                        reportErrorSummary();
                    }
                }
            }
            function reportErrorSummary() {
                if (options.watch) {
                    // Report errors from the other projects
                    getGlobalDependencyGraph().buildQueue.forEach(function (project) {
                        if (!projectErrorsReported.hasKey(project)) {
                            reportErrors(diagnostics.getValue(project) || ts.emptyArray);
                        }
                    });
                    var totalErrors_1 = 0;
                    diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; });
                    reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1);
                }
            }
            function buildSingleInvalidatedProject(resolved, reloadLevel) {
                var proj = parseConfigFile(resolved);
                if (!proj) {
                    reportParseConfigFileDiagnostic(resolved);
                    return;
                }
                if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
                    watchConfigFile(resolved);
                    watchWildCardDirectories(resolved, proj);
                    watchInputFiles(resolved, proj);
                }
                else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
                    // Update file names
                    var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost);
                    if (result.fileNames.length !== 0) {
                        ts.filterMutate(proj.errors, function (error) { return !ts.isErrorNoInputFiles(error); });
                    }
                    else if (!proj.configFileSpecs.filesSpecs && !ts.some(proj.errors, ts.isErrorNoInputFiles)) {
                        proj.errors.push(ts.getErrorForNoInputFiles(proj.configFileSpecs, resolved));
                    }
                    proj.fileNames = result.fileNames;
                    watchInputFiles(resolved, proj);
                }
                var status = getUpToDateStatus(proj);
                verboseReportProjectStatus(resolved, status);
                if (status.type === UpToDateStatusType.UpstreamBlocked) {
                    if (options.verbose)
                        reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName);
                    return;
                }
                var buildResult = buildSingleProject(resolved);
                var dependencyGraph = getGlobalDependencyGraph();
                var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved);
                if (!referencingProjects)
                    return;
                // Always use build order to queue projects
                for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) {
                    var project = _a[_i];
                    var prepend = referencingProjects.getValue(project);
                    // If the project is referenced with prepend, always build downstream projectm,
                    // otherwise queue it only if declaration output changed
                    if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) {
                        addProjToQueue(project);
                    }
                }
            }
            function createDependencyGraph(roots) {
                var temporaryMarks = createFileMap(toPath);
                var permanentMarks = createFileMap(toPath);
                var circularityReportStack = [];
                var buildOrder = [];
                var referencingProjectsMap = createFileMap(toPath);
                for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
                    var root = roots_1[_i];
                    visit(root);
                }
                return {
                    buildQueue: buildOrder,
                    referencingProjectsMap: referencingProjectsMap
                };
                function visit(projPath, inCircularContext) {
                    // Already visited
                    if (permanentMarks.hasKey(projPath))
                        return;
                    // Circular
                    if (temporaryMarks.hasKey(projPath)) {
                        if (!inCircularContext) {
                            // TODO:: Do we report this as error?
                            reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n"));
                        }
                        return;
                    }
                    temporaryMarks.setValue(projPath, true);
                    circularityReportStack.push(projPath);
                    var parsed = parseConfigFile(projPath);
                    if (parsed && parsed.projectReferences) {
                        for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
                            var ref = _a[_i];
                            var resolvedRefPath = resolveProjectName(ref.path);
                            visit(resolvedRefPath, inCircularContext || ref.circular);
                            // Get projects referencing resolvedRefPath and add projPath to it
                            var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); });
                            referencingProjects.setValue(projPath, !!ref.prepend);
                        }
                    }
                    circularityReportStack.pop();
                    permanentMarks.setValue(projPath, true);
                    buildOrder.push(projPath);
                }
            }
            function buildSingleProject(proj) {
                if (options.dry) {
                    reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj);
                    return BuildResultFlags.Success;
                }
                if (options.verbose)
                    reportStatus(ts.Diagnostics.Building_project_0, proj);
                var resultFlags = BuildResultFlags.None;
                resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
                var configFile = parseConfigFile(proj);
                if (!configFile) {
                    // Failed to read the config file
                    resultFlags |= BuildResultFlags.ConfigFileErrors;
                    reportParseConfigFileDiagnostic(proj);
                    projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" });
                    return resultFlags;
                }
                if (configFile.fileNames.length === 0) {
                    // Nothing to build - must be a solution file, basically
                    return BuildResultFlags.None;
                }
                var programOptions = {
                    projectReferences: configFile.projectReferences,
                    host: host,
                    rootNames: configFile.fileNames,
                    options: configFile.options,
                    configFileParsingDiagnostics: configFile.errors
                };
                var program = ts.createProgram(programOptions);
                // Don't emit anything in the presence of syntactic errors or options diagnostics
                var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics());
                if (syntaxDiagnostics.length) {
                    return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
                }
                // Don't emit .d.ts if there are decl file errors
                if (ts.getEmitDeclarations(program.getCompilerOptions())) {
                    var declDiagnostics = program.getDeclarationDiagnostics();
                    if (declDiagnostics.length) {
                        return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
                    }
                }
                // Same as above but now for semantic diagnostics
                var semanticDiagnostics = program.getSemanticDiagnostics();
                if (semanticDiagnostics.length) {
                    return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic");
                }
                var newestDeclarationFileContentChangedTime = minimumDate;
                var anyDtsChanged = false;
                var emitDiagnostics;
                var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); };
                ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) {
                    var priorChangeTime;
                    if (!anyDtsChanged && isDeclarationFile(fileName)) {
                        // Check for unchanged .d.ts files
                        if (host.fileExists(fileName) && host.readFile(fileName) === content) {
                            priorChangeTime = host.getModifiedTime(fileName);
                        }
                        else {
                            resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
                            anyDtsChanged = true;
                        }
                    }
                    host.writeFile(fileName, content, writeBom, onError, ts.emptyArray);
                    if (priorChangeTime !== undefined) {
                        newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
                        unchangedOutputs.setValue(fileName, priorChangeTime);
                    }
                });
                if (emitDiagnostics) {
                    return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
                }
                var status = {
                    type: UpToDateStatusType.UpToDate,
                    newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime
                };
                projectStatus.setValue(proj, status);
                return resultFlags;
                function buildErrors(diagnostics, errorFlags, errorType) {
                    resultFlags |= errorFlags;
                    reportAndStoreErrors(proj, diagnostics);
                    projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
                    return resultFlags;
                }
            }
            function updateOutputTimestamps(proj) {
                if (options.dry) {
                    return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
                }
                if (options.verbose) {
                    reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath);
                }
                var now = new Date();
                var outputs = getAllProjectOutputs(proj);
                var priorNewestUpdateTime = minimumDate;
                for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
                    var file = outputs_2[_i];
                    if (isDeclarationFile(file)) {
                        priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
                    }
                    host.setModifiedTime(file, now);
                }
                projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
            }
            function getFilesToClean() {
                // Get the same graph for cleaning we'd use for building
                var graph = getGlobalDependencyGraph();
                var filesToDelete = [];
                for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
                    var proj = _a[_i];
                    var parsed = parseConfigFile(proj);
                    if (parsed === undefined) {
                        // File has gone missing; fine to ignore here
                        reportParseConfigFileDiagnostic(proj);
                        continue;
                    }
                    var outputs = getAllProjectOutputs(parsed);
                    for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
                        var output = outputs_3[_b];
                        if (host.fileExists(output)) {
                            filesToDelete.push(output);
                        }
                    }
                }
                return filesToDelete;
            }
            function cleanAllProjects() {
                var filesToDelete = getFilesToClean();
                if (options.dry) {
                    reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
                    return ts.ExitStatus.Success;
                }
                for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) {
                    var output = filesToDelete_1[_i];
                    host.deleteFile(output);
                }
                return ts.ExitStatus.Success;
            }
            function resolveProjectName(name) {
                return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name));
            }
            function resolveProjectNames(configFileNames) {
                return configFileNames.map(resolveProjectName);
            }
            function buildAllProjects() {
                if (options.watch) {
                    reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode);
                }
                var graph = getGlobalDependencyGraph();
                reportBuildQueue(graph);
                var anyFailed = false;
                for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) {
                    var next = _a[_i];
                    var proj = parseConfigFile(next);
                    if (proj === undefined) {
                        reportParseConfigFileDiagnostic(next);
                        anyFailed = true;
                        break;
                    }
                    // report errors early when using continue or break statements
                    var errors = proj.errors;
                    var status = getUpToDateStatus(proj);
                    verboseReportProjectStatus(next, status);
                    var projName = proj.options.configFilePath;
                    if (status.type === UpToDateStatusType.UpToDate && !options.force) {
                        reportAndStoreErrors(next, errors);
                        // Up to date, skip
                        if (defaultOptions.dry) {
                            // In a dry build, inform the user of this fact
                            reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName);
                        }
                        continue;
                    }
                    if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) {
                        reportAndStoreErrors(next, errors);
                        // Fake build
                        updateOutputTimestamps(proj);
                        continue;
                    }
                    if (status.type === UpToDateStatusType.UpstreamBlocked) {
                        reportAndStoreErrors(next, errors);
                        if (options.verbose)
                            reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName);
                        continue;
                    }
                    if (status.type === UpToDateStatusType.ContainerOnly) {
                        reportAndStoreErrors(next, errors);
                        // Do nothing
                        continue;
                    }
                    var buildResult = buildSingleProject(next);
                    anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
                }
                reportErrorSummary();
                return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
            }
            function reportParseConfigFileDiagnostic(proj) {
                reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
            }
            function reportAndStoreErrors(proj, errors) {
                reportErrors(errors);
                if (options.watch) {
                    projectErrorsReported.setValue(proj, true);
                    diagnostics.setValue(proj, errors);
                }
            }
            function reportErrors(errors) {
                errors.forEach(function (err) { return host.reportDiagnostic(err); });
            }
            /**
             * Report the build ordering inferred from the current project graph if we're in verbose mode
             */
            function reportBuildQueue(graph) {
                if (options.verbose) {
                    reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n    * " + relName(s); }).join(""));
                }
            }
            function relName(path) {
                return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); });
            }
            /**
             * Report the up-to-date status of a project if we're in verbose mode
             */
            function verboseReportProjectStatus(configFileName, status) {
                if (!options.verbose)
                    return;
                return formatUpToDateStatus(configFileName, status, relName, reportStatus);
            }
        }
        ts.createSolutionBuilder = createSolutionBuilder;
        function resolveConfigFileProjectName(project) {
            if (ts.fileExtensionIs(project, ".json" /* Json */)) {
                return project;
            }
            return ts.combinePaths(project, "tsconfig.json");
        }
        ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
        function getAllProjectOutputs(project) {
            if (project.options.outFile || project.options.out) {
                return getOutFileOutputs(project);
            }
            else {
                var outputs = [];
                for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
                    var inputFile = _a[_i];
                    outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
                }
                return outputs;
            }
        }
        ts.getAllProjectOutputs = getAllProjectOutputs;
        function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
            switch (status.type) {
                case UpToDateStatusType.OutOfDateWithSelf:
                    return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName));
                case UpToDateStatusType.OutOfDateWithUpstream:
                    return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName));
                case UpToDateStatusType.OutputMissing:
                    return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName));
                case UpToDateStatusType.UpToDate:
                    if (status.newestInputFileTime !== undefined) {
                        return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || ""));
                    }
                    // Don't report anything for "up to date because it was already built" -- too verbose
                    break;
                case UpToDateStatusType.UpToDateWithUpstreamTypes:
                    return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
                case UpToDateStatusType.UpstreamOutOfDate:
                    return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName));
                case UpToDateStatusType.UpstreamBlocked:
                    return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
                case UpToDateStatusType.Unbuildable:
                    return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
                case UpToDateStatusType.ContainerOnly:
                // Don't report status on "solution" projects
                case UpToDateStatusType.ComputingUpstream:
                    // Should never leak from getUptoDateStatusWorker
                    break;
                default:
                    ts.assertType(status);
            }
        }
        ts.formatUpToDateStatus = formatUpToDateStatus;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var ValueKind;
        (function (ValueKind) {
            ValueKind[ValueKind["Const"] = 0] = "Const";
            ValueKind[ValueKind["Array"] = 1] = "Array";
            ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass";
            ValueKind[ValueKind["Object"] = 3] = "Object";
        })(ValueKind = ts.ValueKind || (ts.ValueKind = {}));
        function inspectModule(fileNameToRequire) {
            return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire));
        }
        ts.inspectModule = inspectModule;
        function inspectValue(name, value) {
            return getValueInfo(name, value, getRecurser());
        }
        ts.inspectValue = inspectValue;
        function getRecurser() {
            var seen = new Set();
            var nameStack = [];
            return function (obj, name, cbOk, cbFail) {
                if (seen.has(obj) || nameStack.length > 4) {
                    return cbFail(seen.has(obj), nameStack);
                }
                seen.add(obj);
                nameStack.push(name);
                var res = cbOk();
                nameStack.pop();
                seen.delete(obj);
                return res;
            };
        }
        function getValueInfo(name, value, recurser) {
            return recurser(value, name, function () {
                if (typeof value === "function")
                    return getFunctionOrClassInfo(value, name, recurser);
                if (typeof value === "object") {
                    var builtin = getBuiltinType(name, value, recurser);
                    if (builtin !== undefined)
                        return builtin;
                    var entries = getEntriesOfObject(value);
                    return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) {
                            var key = _a.key, value = _a.value;
                            return getValueInfo(key, value, recurser);
                        }) };
                }
                return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value };
            }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); });
        }
        function getFunctionOrClassInfo(fn, name, recurser) {
            var prototypeMembers = getPrototypeMembers(fn, recurser);
            var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) {
                var key = _a.key, value = _a.value;
                return getValueInfo(key, value, recurser);
            });
            var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString);
            var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString;
            return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers };
        }
        var builtins = ts.memoize(function () {
            var map = ts.createMap();
            for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) {
                var _b = _a[_i], key = _b.key, value = _b.value;
                if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) {
                    map.set(key, value);
                }
            }
            return map;
        });
        function getBuiltinType(name, value, recurser) {
            return ts.isArray(value)
                ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) }
                : ts.forEachEntry(builtins(), function (builtin, builtinName) {
                    return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined;
                });
        }
        function getPrototypeMembers(fn, recurser) {
            var prototype = fn.prototype;
            // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary)
            return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) {
                var key = _a.key, value = _a.value;
                return key === "constructor" ? undefined : getValueInfo(key, value, recurser);
            });
        }
        var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]);
        var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop));
        function getEntriesOfObject(obj) {
            var seen = ts.createMap();
            var entries = [];
            var chain = obj;
            while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) {
                for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) {
                    var key = _a[_i];
                    if (!isJsPrivate(key) &&
                        !ignoredProperties.has(key) &&
                        (typeof obj !== "function" || !reservedFunctionProperties.has(key)) &&
                        // Don't add property from a higher prototype if it already exists in a lower one
                        ts.addToSeen(seen, key)) {
                        var value = safeGetPropertyOfObject(chain, key);
                        // Don't repeat "toString" that matches signature from Object.prototype
                        if (!(key === "toString" && typeof value === "function" && value.length === 0)) {
                            entries.push({ key: key, value: value });
                        }
                    }
                }
                chain = Object.getPrototypeOf(chain);
            }
            return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); });
        }
        function getFunctionLength(fn) {
            return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0;
        }
        function safeGetPropertyOfObject(obj, key) {
            var desc = Object.getOwnPropertyDescriptor(obj, key);
            return desc && desc.value;
        }
        function isNullOrUndefined(value) {
            return value == null; // tslint:disable-line
        }
        function anyValue(name, comment) {
            return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment };
        }
        function isJsPrivate(name) {
            return name.startsWith("_");
        }
        ts.isJsPrivate = isJsPrivate;
        function tryRequire(fileNameToRequire) {
            try {
                return require(fileNameToRequire);
            }
            catch (_a) {
                return undefined;
            }
        }
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var server;
        (function (server) {
            // tslint:disable variable-name
            server.ActionSet = "action::set";
            server.ActionInvalidate = "action::invalidate";
            server.ActionPackageInstalled = "action::packageInstalled";
            server.ActionValueInspected = "action::valueInspected";
            server.EventTypesRegistry = "event::typesRegistry";
            server.EventBeginInstallTypes = "event::beginInstallTypes";
            server.EventEndInstallTypes = "event::endInstallTypes";
            server.EventInitializationFailed = "event::initializationFailed";
            var Arguments;
            (function (Arguments) {
                Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
                Arguments.LogFile = "--logFile";
                Arguments.EnableTelemetry = "--enableTelemetry";
                Arguments.TypingSafeListLocation = "--typingSafeListLocation";
                Arguments.TypesMapLocation = "--typesMapLocation";
                /**
                 * This argument specifies the location of the NPM executable.
                 * typingsInstaller will run the command with `${npmLocation} install ...`.
                 */
                Arguments.NpmLocation = "--npmLocation";
            })(Arguments = server.Arguments || (server.Arguments = {}));
            function hasArgument(argumentName) {
                return ts.sys.args.indexOf(argumentName) >= 0;
            }
            server.hasArgument = hasArgument;
            function findArgument(argumentName) {
                var index = ts.sys.args.indexOf(argumentName);
                return index >= 0 && index < ts.sys.args.length - 1
                    ? ts.sys.args[index + 1]
                    : undefined;
            }
            server.findArgument = findArgument;
            /*@internal*/
            function nowString() {
                // E.g. "12:34:56.789"
                var d = new Date();
                return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
            }
            server.nowString = nowString;
        })(server = ts.server || (ts.server = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var JsTyping;
        (function (JsTyping) {
            /* @internal */
            function isTypingUpToDate(cachedTyping, availableTypingVersions) {
                var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
                return availableVersion.compareTo(cachedTyping.version) <= 0;
            }
            JsTyping.isTypingUpToDate = isTypingUpToDate;
            /* @internal */
            JsTyping.nodeCoreModuleList = [
                "assert",
                "async_hooks",
                "buffer",
                "child_process",
                "cluster",
                "console",
                "constants",
                "crypto",
                "dgram",
                "dns",
                "domain",
                "events",
                "fs",
                "http",
                "https",
                "http2",
                "inspector",
                "net",
                "os",
                "path",
                "perf_hooks",
                "process",
                "punycode",
                "querystring",
                "readline",
                "repl",
                "stream",
                "string_decoder",
                "timers",
                "tls",
                "tty",
                "url",
                "util",
                "v8",
                "vm",
                "zlib"
            ];
            /* @internal */
            JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
            function loadSafeList(host, safeListPath) {
                var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
                return ts.createMapFromTemplate(result.config);
            }
            JsTyping.loadSafeList = loadSafeList;
            function loadTypesMap(host, typesMapPath) {
                var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
                if (result.config) {
                    return ts.createMapFromTemplate(result.config.simpleMap);
                }
                return undefined;
            }
            JsTyping.loadTypesMap = loadTypesMap;
            /**
             * @param host is the object providing I/O related operations.
             * @param fileNames are the file names that belong to the same project
             * @param projectRootPath is the path to the project root directory
             * @param safeListPath is the path used to retrieve the safe list
             * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
             * @param typeAcquisition is used to customize the typing acquisition process
             * @param compilerOptions are used as a source for typing inference
             */
            function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
                if (!typeAcquisition || !typeAcquisition.enable) {
                    return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
                }
                // A typing name to typing file path mapping
                var inferredTypings = ts.createMap();
                // Only infer typings for .js and .jsx files
                fileNames = ts.mapDefined(fileNames, function (fileName) {
                    var path = ts.normalizePath(fileName);
                    if (ts.hasJSFileExtension(path)) {
                        return path;
                    }
                });
                var filesToWatch = [];
                if (typeAcquisition.include)
                    addInferredTypings(typeAcquisition.include, "Explicitly included types");
                var exclude = typeAcquisition.exclude || [];
                // Directories to search for package.json, bower.json and other typing information
                var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
                possibleSearchDirs.set(projectRootPath, true);
                possibleSearchDirs.forEach(function (_true, searchDir) {
                    var packageJsonPath = ts.combinePaths(searchDir, "package.json");
                    getTypingNamesFromJson(packageJsonPath, filesToWatch);
                    var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
                    getTypingNamesFromJson(bowerJsonPath, filesToWatch);
                    var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
                    getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
                    var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
                    getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
                });
                getTypingNamesFromSourceFileNames(fileNames);
                // add typings for unresolved imports
                if (unresolvedImports) {
                    var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
                    addInferredTypings(module_1, "Inferred typings from unresolved imports");
                }
                // Add the cached typing locations for inferred typings that are already installed
                packageNameToTypingLocation.forEach(function (typing, name) {
                    var registryEntry = typesRegistry.get(name);
                    if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
                        inferredTypings.set(name, typing.typingLocation);
                    }
                });
                // Remove typings that the user has added to the exclude list
                for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
                    var excludeTypingName = exclude_1[_i];
                    var didDelete = inferredTypings.delete(excludeTypingName);
                    if (didDelete && log)
                        log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
                }
                var newTypingNames = [];
                var cachedTypingPaths = [];
                inferredTypings.forEach(function (inferred, typing) {
                    if (inferred !== undefined) {
                        cachedTypingPaths.push(inferred);
                    }
                    else {
                        newTypingNames.push(typing);
                    }
                });
                var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
                if (log)
                    log("Result: " + JSON.stringify(result));
                return result;
                function addInferredTyping(typingName) {
                    if (!inferredTypings.has(typingName)) {
                        inferredTypings.set(typingName, undefined); // TODO: GH#18217
                    }
                }
                function addInferredTypings(typingNames, message) {
                    if (log)
                        log(message + ": " + JSON.stringify(typingNames));
                    ts.forEach(typingNames, addInferredTyping);
                }
                /**
                 * Get the typing info from common package manager json files like package.json or bower.json
                 */
                function getTypingNamesFromJson(jsonPath, filesToWatch) {
                    if (!host.fileExists(jsonPath)) {
                        return;
                    }
                    filesToWatch.push(jsonPath);
                    var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
                    var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
                    addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
                }
                /**
                 * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
                 * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
                 * to the 'angular-route' typing name.
                 * @param fileNames are the names for source files in the project
                 */
                function getTypingNamesFromSourceFileNames(fileNames) {
                    var fromFileNames = ts.mapDefined(fileNames, function (j) {
                        if (!ts.hasJSFileExtension(j))
                            return undefined;
                        var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
                        var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
                        return safeList.get(cleanedTypingName);
                    });
                    if (fromFileNames.length) {
                        addInferredTypings(fromFileNames, "Inferred typings from file names");
                    }
                    var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
                    if (hasJsxFile) {
                        if (log)
                            log("Inferred 'react' typings due to presence of '.jsx' extension");
                        addInferredTyping("react");
                    }
                }
                /**
                 * Infer typing names from packages folder (ex: node_module, bower_components)
                 * @param packagesFolderPath is the path to the packages folder
                 */
                function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
                    filesToWatch.push(packagesFolderPath);
                    // Todo: add support for ModuleResolutionHost too
                    if (!host.directoryExists(packagesFolderPath)) {
                        return;
                    }
                    // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
                    var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
                    if (log)
                        log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
                    var packageNames = [];
                    for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
                        var fileName = fileNames_1[_i];
                        var normalizedFileName = ts.normalizePath(fileName);
                        var baseFileName = ts.getBaseFileName(normalizedFileName);
                        if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
                            continue;
                        }
                        var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
                        var packageJson = result_6.config;
                        // npm 3's package.json contains a "_requiredBy" field
                        // we should include all the top level module names for npm 2, and only module names whose
                        // "_requiredBy" field starts with "#" or equals "/" for npm 3.
                        if (baseFileName === "package.json" && packageJson._requiredBy &&
                            ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
                            continue;
                        }
                        // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
                        // to download d.ts files from DefinitelyTyped
                        if (!packageJson.name) {
                            continue;
                        }
                        var ownTypes = packageJson.types || packageJson.typings;
                        if (ownTypes) {
                            var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
                            if (log)
                                log("    Package '" + packageJson.name + "' provides its own types.");
                            inferredTypings.set(packageJson.name, absolutePath);
                        }
                        else {
                            packageNames.push(packageJson.name);
                        }
                    }
                    addInferredTypings(packageNames, "    Found package names");
                }
            }
            JsTyping.discoverTypings = discoverTypings;
            var PackageNameValidationResult;
            (function (PackageNameValidationResult) {
                PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok";
                PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported";
                PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName";
                PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong";
                PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot";
                PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore";
                PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters";
            })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {}));
            var maxPackageNameLength = 214;
            /**
             * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
             */
            function validatePackageName(packageName) {
                if (!packageName) {
                    return 2 /* EmptyName */;
                }
                if (packageName.length > maxPackageNameLength) {
                    return 3 /* NameTooLong */;
                }
                if (packageName.charCodeAt(0) === 46 /* dot */) {
                    return 4 /* NameStartsWithDot */;
                }
                if (packageName.charCodeAt(0) === 95 /* _ */) {
                    return 5 /* NameStartsWithUnderscore */;
                }
                // check if name is scope package like: starts with @ and has one '/' in the middle
                // scoped packages are not currently supported
                // TODO: when support will be added we'll need to split and check both scope and package name
                if (/^@[^/]+\/[^/]+$/.test(packageName)) {
                    return 1 /* ScopedPackagesNotSupported */;
                }
                if (encodeURIComponent(packageName) !== packageName) {
                    return 6 /* NameContainsNonURISafeCharacters */;
                }
                return 0 /* Ok */;
            }
            JsTyping.validatePackageName = validatePackageName;
            function renderPackageNameValidationFailure(result, typing) {
                switch (result) {
                    case 2 /* EmptyName */:
                        return "Package name '" + typing + "' cannot be empty";
                    case 3 /* NameTooLong */:
                        return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters";
                    case 4 /* NameStartsWithDot */:
                        return "Package name '" + typing + "' cannot start with '.'";
                    case 5 /* NameStartsWithUnderscore */:
                        return "Package name '" + typing + "' cannot start with '_'";
                    case 1 /* ScopedPackagesNotSupported */:
                        return "Package '" + typing + "' is scoped and currently is not supported";
                    case 6 /* NameContainsNonURISafeCharacters */:
                        return "Package name '" + typing + "' contains non URI safe characters";
                    case 0 /* Ok */:
                        return ts.Debug.fail(); // Shouldn't have called this.
                    default:
                        throw ts.Debug.assertNever(result);
                }
            }
            JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
        })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        var ScriptSnapshot;
        (function (ScriptSnapshot) {
            var StringScriptSnapshot = /** @class */ (function () {
                function StringScriptSnapshot(text) {
                    this.text = text;
                }
                StringScriptSnapshot.prototype.getText = function (start, end) {
                    return start === 0 && end === this.text.length
                        ? this.text
                        : this.text.substring(start, end);
                };
                StringScriptSnapshot.prototype.getLength = function () {
                    return this.text.length;
                };
                StringScriptSnapshot.prototype.getChangeRange = function () {
                    // Text-based snapshots do not support incremental parsing. Return undefined
                    // to signal that to the caller.
                    return undefined;
                };
                return StringScriptSnapshot;
            }());
            function fromString(text) {
                return new StringScriptSnapshot(text);
            }
            ScriptSnapshot.fromString = fromString;
        })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
        /* @internal */
        ts.emptyOptions = {};
        var TextChange = /** @class */ (function () {
            function TextChange() {
            }
            return TextChange;
        }());
        ts.TextChange = TextChange;
        var HighlightSpanKind;
        (function (HighlightSpanKind) {
            HighlightSpanKind["none"] = "none";
            HighlightSpanKind["definition"] = "definition";
            HighlightSpanKind["reference"] = "reference";
            HighlightSpanKind["writtenReference"] = "writtenReference";
        })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {}));
        var IndentStyle;
        (function (IndentStyle) {
            IndentStyle[IndentStyle["None"] = 0] = "None";
            IndentStyle[IndentStyle["Block"] = 1] = "Block";
            IndentStyle[IndentStyle["Smart"] = 2] = "Smart";
        })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {}));
        /* @internal */
        ts.testFormatSettings = {
            baseIndentSize: 0,
            indentSize: 4,
            tabSize: 4,
            newLineCharacter: "\n",
            convertTabsToSpaces: true,
            indentStyle: IndentStyle.Smart,
            insertSpaceAfterCommaDelimiter: true,
            insertSpaceAfterSemicolonInForStatements: true,
            insertSpaceBeforeAndAfterBinaryOperators: true,
            insertSpaceAfterConstructor: false,
            insertSpaceAfterKeywordsInControlFlowStatements: true,
            insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
            insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
            insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
            insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
            insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
            insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
            insertSpaceAfterTypeAssertion: false,
            placeOpenBraceOnNewLineForFunctions: false,
            placeOpenBraceOnNewLineForControlBlocks: false,
            insertSpaceBeforeTypeAnnotation: false
        };
        var SymbolDisplayPartKind;
        (function (SymbolDisplayPartKind) {
            SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className";
            SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword";
            SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak";
            SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral";
            SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral";
            SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator";
            SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation";
            SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space";
            SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text";
            SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
            SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
        })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
        var OutliningSpanKind;
        (function (OutliningSpanKind) {
            /** Single or multi-line comments */
            OutliningSpanKind["Comment"] = "comment";
            /** Sections marked by '// #region' and '// #endregion' comments */
            OutliningSpanKind["Region"] = "region";
            /** Declarations and expressions */
            OutliningSpanKind["Code"] = "code";
            /** Contiguous blocks of import declarations */
            OutliningSpanKind["Imports"] = "imports";
        })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
        var OutputFileType;
        (function (OutputFileType) {
            OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
            OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap";
            OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration";
        })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {}));
        var EndOfLineState;
        (function (EndOfLineState) {
            EndOfLineState[EndOfLineState["None"] = 0] = "None";
            EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia";
            EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral";
            EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral";
            EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate";
            EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail";
            EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition";
        })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {}));
        var TokenClass;
        (function (TokenClass) {
            TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation";
            TokenClass[TokenClass["Keyword"] = 1] = "Keyword";
            TokenClass[TokenClass["Operator"] = 2] = "Operator";
            TokenClass[TokenClass["Comment"] = 3] = "Comment";
            TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace";
            TokenClass[TokenClass["Identifier"] = 5] = "Identifier";
            TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral";
            TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral";
            TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral";
        })(TokenClass = ts.TokenClass || (ts.TokenClass = {}));
        var ScriptElementKind;
        (function (ScriptElementKind) {
            ScriptElementKind["unknown"] = "";
            ScriptElementKind["warning"] = "warning";
            /** predefined type (void) or keyword (class) */
            ScriptElementKind["keyword"] = "keyword";
            /** top level script node */
            ScriptElementKind["scriptElement"] = "script";
            /** module foo {} */
            ScriptElementKind["moduleElement"] = "module";
            /** class X {} */
            ScriptElementKind["classElement"] = "class";
            /** var x = class X {} */
            ScriptElementKind["localClassElement"] = "local class";
            /** interface Y {} */
            ScriptElementKind["interfaceElement"] = "interface";
            /** type T = ... */
            ScriptElementKind["typeElement"] = "type";
            /** enum E */
            ScriptElementKind["enumElement"] = "enum";
            ScriptElementKind["enumMemberElement"] = "enum member";
            /**
             * Inside module and script only
             * const v = ..
             */
            ScriptElementKind["variableElement"] = "var";
            /** Inside function */
            ScriptElementKind["localVariableElement"] = "local var";
            /**
             * Inside module and script only
             * function f() { }
             */
            ScriptElementKind["functionElement"] = "function";
            /** Inside function */
            ScriptElementKind["localFunctionElement"] = "local function";
            /** class X { [public|private]* foo() {} } */
            ScriptElementKind["memberFunctionElement"] = "method";
            /** class X { [public|private]* [get|set] foo:number; } */
            ScriptElementKind["memberGetAccessorElement"] = "getter";
            ScriptElementKind["memberSetAccessorElement"] = "setter";
            /**
             * class X { [public|private]* foo:number; }
             * interface Y { foo:number; }
             */
            ScriptElementKind["memberVariableElement"] = "property";
            /** class X { constructor() { } } */
            ScriptElementKind["constructorImplementationElement"] = "constructor";
            /** interface Y { ():number; } */
            ScriptElementKind["callSignatureElement"] = "call";
            /** interface Y { []:number; } */
            ScriptElementKind["indexSignatureElement"] = "index";
            /** interface Y { new():Y; } */
            ScriptElementKind["constructSignatureElement"] = "construct";
            /** function foo(*Y*: string) */
            ScriptElementKind["parameterElement"] = "parameter";
            ScriptElementKind["typeParameterElement"] = "type parameter";
            ScriptElementKind["primitiveType"] = "primitive type";
            ScriptElementKind["label"] = "label";
            ScriptElementKind["alias"] = "alias";
            ScriptElementKind["constElement"] = "const";
            ScriptElementKind["letElement"] = "let";
            ScriptElementKind["directory"] = "directory";
            ScriptElementKind["externalModuleName"] = "external module name";
            /**
             * <JsxTagName attribute1 attribute2={0} />
             */
            ScriptElementKind["jsxAttribute"] = "JSX attribute";
            /** String literal */
            ScriptElementKind["string"] = "string";
        })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
        var ScriptElementKindModifier;
        (function (ScriptElementKindModifier) {
            ScriptElementKindModifier["none"] = "";
            ScriptElementKindModifier["publicMemberModifier"] = "public";
            ScriptElementKindModifier["privateMemberModifier"] = "private";
            ScriptElementKindModifier["protectedMemberModifier"] = "protected";
            ScriptElementKindModifier["exportedModifier"] = "export";
            ScriptElementKindModifier["ambientModifier"] = "declare";
            ScriptElementKindModifier["staticModifier"] = "static";
            ScriptElementKindModifier["abstractModifier"] = "abstract";
            ScriptElementKindModifier["optionalModifier"] = "optional";
        })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {}));
        var ClassificationTypeNames;
        (function (ClassificationTypeNames) {
            ClassificationTypeNames["comment"] = "comment";
            ClassificationTypeNames["identifier"] = "identifier";
            ClassificationTypeNames["keyword"] = "keyword";
            ClassificationTypeNames["numericLiteral"] = "number";
            ClassificationTypeNames["operator"] = "operator";
            ClassificationTypeNames["stringLiteral"] = "string";
            ClassificationTypeNames["whiteSpace"] = "whitespace";
            ClassificationTypeNames["text"] = "text";
            ClassificationTypeNames["punctuation"] = "punctuation";
            ClassificationTypeNames["className"] = "class name";
            ClassificationTypeNames["enumName"] = "enum name";
            ClassificationTypeNames["interfaceName"] = "interface name";
            ClassificationTypeNames["moduleName"] = "module name";
            ClassificationTypeNames["typeParameterName"] = "type parameter name";
            ClassificationTypeNames["typeAliasName"] = "type alias name";
            ClassificationTypeNames["parameterName"] = "parameter name";
            ClassificationTypeNames["docCommentTagName"] = "doc comment tag name";
            ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name";
            ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name";
            ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name";
            ClassificationTypeNames["jsxAttribute"] = "jsx attribute";
            ClassificationTypeNames["jsxText"] = "jsx text";
            ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value";
        })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {}));
        var ClassificationType;
        (function (ClassificationType) {
            ClassificationType[ClassificationType["comment"] = 1] = "comment";
            ClassificationType[ClassificationType["identifier"] = 2] = "identifier";
            ClassificationType[ClassificationType["keyword"] = 3] = "keyword";
            ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral";
            ClassificationType[ClassificationType["operator"] = 5] = "operator";
            ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral";
            ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral";
            ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace";
            ClassificationType[ClassificationType["text"] = 9] = "text";
            ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation";
            ClassificationType[ClassificationType["className"] = 11] = "className";
            ClassificationType[ClassificationType["enumName"] = 12] = "enumName";
            ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName";
            ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName";
            ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName";
            ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName";
            ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName";
            ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName";
            ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName";
            ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName";
            ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
            ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute";
            ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText";
            ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue";
        })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {}));
    })(ts || (ts = {}));
    // These utilities are common to multiple language service features.
    /* @internal */
    var ts;
    (function (ts) {
        ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
        var SemanticMeaning;
        (function (SemanticMeaning) {
            SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
            SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value";
            SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type";
            SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace";
            SemanticMeaning[SemanticMeaning["All"] = 7] = "All";
        })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {}));
        function getMeaningFromDeclaration(node) {
            switch (node.kind) {
                case 235 /* VariableDeclaration */:
                    return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */;
                case 149 /* Parameter */:
                case 184 /* BindingElement */:
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                case 273 /* PropertyAssignment */:
                case 274 /* ShorthandPropertyAssignment */:
                case 154 /* MethodDeclaration */:
                case 153 /* MethodSignature */:
                case 155 /* Constructor */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                case 195 /* ArrowFunction */:
                case 272 /* CatchClause */:
                case 265 /* JsxAttribute */:
                    return 1 /* Value */;
                case 148 /* TypeParameter */:
                case 239 /* InterfaceDeclaration */:
                case 240 /* TypeAliasDeclaration */:
                case 166 /* TypeLiteral */:
                    return 2 /* Type */;
                case 302 /* JSDocTypedefTag */:
                    // If it has no name node, it shares the name with the value declaration below it.
                    return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
                case 276 /* EnumMember */:
                case 238 /* ClassDeclaration */:
                    return 1 /* Value */ | 2 /* Type */;
                case 242 /* ModuleDeclaration */:
                    if (ts.isAmbientModule(node)) {
                        return 4 /* Namespace */ | 1 /* Value */;
                    }
                    else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) {
                        return 4 /* Namespace */ | 1 /* Value */;
                    }
                    else {
                        return 4 /* Namespace */;
                    }
                case 241 /* EnumDeclaration */:
                case 250 /* NamedImports */:
                case 251 /* ImportSpecifier */:
                case 246 /* ImportEqualsDeclaration */:
                case 247 /* ImportDeclaration */:
                case 252 /* ExportAssignment */:
                case 253 /* ExportDeclaration */:
                    return 7 /* All */;
                // An external module can be a Value
                case 277 /* SourceFile */:
                    return 4 /* Namespace */ | 1 /* Value */;
            }
            return 7 /* All */;
        }
        ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
        function getMeaningFromLocation(node) {
            if (node.kind === 277 /* SourceFile */) {
                return 1 /* Value */;
            }
            else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) {
                return 7 /* All */;
            }
            else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
                return getMeaningFromRightHandSideOfImportEquals(node);
            }
            else if (ts.isDeclarationName(node)) {
                return getMeaningFromDeclaration(node.parent);
            }
            else if (isTypeReference(node)) {
                return 2 /* Type */;
            }
            else if (isNamespaceReference(node)) {
                return 4 /* Namespace */;
            }
            else if (ts.isTypeParameterDeclaration(node.parent)) {
                ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName
                return 2 /* Type */;
            }
            else if (ts.isLiteralTypeNode(node.parent)) {
                // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings.
                return 2 /* Type */ | 1 /* Value */;
            }
            else {
                return 1 /* Value */;
            }
        }
        ts.getMeaningFromLocation = getMeaningFromLocation;
        function getMeaningFromRightHandSideOfImportEquals(node) {
            //     import a = |b|; // Namespace
            //     import a = |b.c|; // Value, type, namespace
            //     import a = |b.c|.d; // Namespace
            var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined;
            return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */;
        }
        function isInRightSideOfInternalImportEqualsDeclaration(node) {
            while (node.parent.kind === 146 /* QualifiedName */) {
                node = node.parent;
            }
            return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
        }
        ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration;
        function isNamespaceReference(node) {
            return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node);
        }
        function isQualifiedNameNamespaceReference(node) {
            var root = node;
            var isLastClause = true;
            if (root.parent.kind === 146 /* QualifiedName */) {
                while (root.parent && root.parent.kind === 146 /* QualifiedName */) {
                    root = root.parent;
                }
                isLastClause = root.right === node;
            }
            return root.parent.kind === 162 /* TypeReference */ && !isLastClause;
        }
        function isPropertyAccessNamespaceReference(node) {
            var root = node;
            var isLastClause = true;
            if (root.parent.kind === 187 /* PropertyAccessExpression */) {
                while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) {
                    root = root.parent;
                }
                isLastClause = root.name === node;
            }
            if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) {
                var decl = root.parent.parent.parent;
                return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) ||
                    (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */);
            }
            return false;
        }
        function isTypeReference(node) {
            if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
                node = node.parent;
            }
            switch (node.kind) {
                case 99 /* ThisKeyword */:
                    return !ts.isExpressionNode(node);
                case 176 /* ThisType */:
                    return true;
            }
            switch (node.parent.kind) {
                case 162 /* TypeReference */:
                    return true;
                case 181 /* ImportType */:
                    return !node.parent.isTypeOf;
                case 209 /* ExpressionWithTypeArguments */:
                    return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
            }
            return false;
        }
        function isCallExpressionTarget(node) {
            return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression);
        }
        ts.isCallExpressionTarget = isCallExpressionTarget;
        function isNewExpressionTarget(node) {
            return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression);
        }
        ts.isNewExpressionTarget = isNewExpressionTarget;
        function isCallOrNewExpressionTarget(node) {
            return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression);
        }
        ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget;
        function isCallOrNewExpressionTargetWorker(node, pred) {
            var target = climbPastPropertyAccess(node);
            return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target;
        }
        function climbPastPropertyAccess(node) {
            return isRightSideOfPropertyAccess(node) ? node.parent : node;
        }
        ts.climbPastPropertyAccess = climbPastPropertyAccess;
        function getTargetLabel(referenceNode, labelName) {
            while (referenceNode) {
                if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) {
                    return referenceNode.label;
                }
                referenceNode = referenceNode.parent;
            }
            return undefined;
        }
        ts.getTargetLabel = getTargetLabel;
        function hasPropertyAccessExpressionWithName(node, funcName) {
            if (!ts.isPropertyAccessExpression(node.expression)) {
                return false;
            }
            return node.expression.name.text === funcName;
        }
        ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName;
        function isJumpStatementTarget(node) {
            return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node;
        }
        ts.isJumpStatementTarget = isJumpStatementTarget;
        function isLabelOfLabeledStatement(node) {
            return node.kind === 71 /* Identifier */ && ts.isLabeledStatement(node.parent) && node.parent.label === node;
        }
        ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
        function isLabelName(node) {
            return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
        }
        ts.isLabelName = isLabelName;
        function isRightSideOfQualifiedName(node) {
            return node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node;
        }
        ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName;
        function isRightSideOfPropertyAccess(node) {
            return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node;
        }
        ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess;
        function isNameOfModuleDeclaration(node) {
            return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node;
        }
        ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration;
        function isNameOfFunctionDeclaration(node) {
            return node.kind === 71 /* Identifier */ &&
                ts.isFunctionLike(node.parent) && node.parent.name === node;
        }
        ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration;
        function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
            switch (node.parent.kind) {
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                case 273 /* PropertyAssignment */:
                case 276 /* EnumMember */:
                case 154 /* MethodDeclaration */:
                case 153 /* MethodSignature */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 242 /* ModuleDeclaration */:
                    return ts.getNameOfDeclaration(node.parent) === node;
                case 188 /* ElementAccessExpression */:
                    return node.parent.argumentExpression === node;
                case 147 /* ComputedPropertyName */:
                    return true;
                case 180 /* LiteralType */:
                    return node.parent.parent.kind === 178 /* IndexedAccessType */;
                default:
                    return false;
            }
        }
        ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess;
        function isExpressionOfExternalModuleImportEqualsDeclaration(node) {
            return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
                ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
        }
        ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
        function getContainerNode(node) {
            if (ts.isJSDocTypeAlias(node)) {
                // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
                // node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
                // Then we get parent again in the loop.
                node = node.parent.parent;
            }
            while (true) {
                node = node.parent;
                if (!node) {
                    return undefined;
                }
                switch (node.kind) {
                    case 277 /* SourceFile */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 238 /* ClassDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 242 /* ModuleDeclaration */:
                        return node;
                }
            }
        }
        ts.getContainerNode = getContainerNode;
        function getNodeKind(node) {
            switch (node.kind) {
                case 277 /* SourceFile */:
                    return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
                case 242 /* ModuleDeclaration */:
                    return "module" /* moduleElement */;
                case 238 /* ClassDeclaration */:
                case 207 /* ClassExpression */:
                    return "class" /* classElement */;
                case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
                case 240 /* TypeAliasDeclaration */:
                case 295 /* JSDocCallbackTag */:
                case 302 /* JSDocTypedefTag */:
                    return "type" /* typeElement */;
                case 241 /* EnumDeclaration */: return "enum" /* enumElement */;
                case 235 /* VariableDeclaration */:
                    return getKindOfVariableDeclaration(node);
                case 184 /* BindingElement */:
                    return getKindOfVariableDeclaration(ts.getRootDeclaration(node));
                case 195 /* ArrowFunction */:
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                    return "function" /* functionElement */;
                case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */;
                case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */;
                case 154 /* MethodDeclaration */:
                case 153 /* MethodSignature */:
                    return "method" /* memberFunctionElement */;
                case 152 /* PropertyDeclaration */:
                case 151 /* PropertySignature */:
                    return "property" /* memberVariableElement */;
                case 160 /* IndexSignature */: return "index" /* indexSignatureElement */;
                case 159 /* ConstructSignature */: return "construct" /* constructSignatureElement */;
                case 158 /* CallSignature */: return "call" /* callSignatureElement */;
                case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */;
                case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */;
                case 276 /* EnumMember */: return "enum member" /* enumMemberElement */;
                case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */;
                case 246 /* ImportEqualsDeclaration */:
                case 251 /* ImportSpecifier */:
                case 255 /* ExportSpecifier */:
                case 249 /* NamespaceImport */:
                    return "alias" /* alias */;
                case 202 /* BinaryExpression */:
                    var kind = ts.getAssignmentDeclarationKind(node);
                    var right = node.right;
                    switch (kind) {
                        case 0 /* None */:
                            return "" /* unknown */;
                        case 1 /* ExportsProperty */:
                        case 2 /* ModuleExports */:
                            var rightKind = getNodeKind(right);
                            return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind;
                        case 3 /* PrototypeProperty */:
                            return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
                        case 4 /* ThisProperty */:
                            return "property" /* memberVariableElement */; // property
                        case 5 /* Property */:
                            // static method / property
                            return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
                        case 6 /* Prototype */:
                            return "local class" /* localClassElement */;
                        default: {
                            ts.assertType(kind);
                            return "" /* unknown */;
                        }
                    }
                case 71 /* Identifier */:
                    return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */;
                default:
                    return "" /* unknown */;
            }
            function getKindOfVariableDeclaration(v) {
                return ts.isVarConst(v)
                    ? "const" /* constElement */
                    : ts.isLet(v)
                        ? "let" /* letElement */
                        : "var" /* variableElement */;
            }
        }
        ts.getNodeKind = getNodeKind;
        function isThis(node) {
            switch (node.kind) {
                case 99 /* ThisKeyword */:
                    // case SyntaxKind.ThisType: TODO: GH#9267
                    return true;
                case 71 /* Identifier */:
                    // 'this' as a parameter
                    return ts.identifierIsThisKeyword(node) && node.parent.kind === 149 /* Parameter */;
                default:
                    return false;
            }
        }
        ts.isThis = isThis;
        // Matches the beginning of a triple slash directive
        var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
        function getLineStartPositionForPosition(position, sourceFile) {
            var lineStarts = ts.getLineStarts(sourceFile);
            var line = sourceFile.getLineAndCharacterOfPosition(position).line;
            return lineStarts[line];
        }
        ts.getLineStartPositionForPosition = getLineStartPositionForPosition;
        function rangeContainsRange(r1, r2) {
            return startEndContainsRange(r1.pos, r1.end, r2);
        }
        ts.rangeContainsRange = rangeContainsRange;
        function rangeContainsRangeExclusive(r1, r2) {
            return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end);
        }
        ts.rangeContainsRangeExclusive = rangeContainsRangeExclusive;
        function rangeContainsPosition(r, pos) {
            return r.pos <= pos && pos <= r.end;
        }
        ts.rangeContainsPosition = rangeContainsPosition;
        function rangeContainsPositionExclusive(r, pos) {
            return r.pos < pos && pos < r.end;
        }
        ts.rangeContainsPositionExclusive = rangeContainsPositionExclusive;
        function startEndContainsRange(start, end, range) {
            return start <= range.pos && end >= range.end;
        }
        ts.startEndContainsRange = startEndContainsRange;
        function rangeContainsStartEnd(range, start, end) {
            return range.pos <= start && range.end >= end;
        }
        ts.rangeContainsStartEnd = rangeContainsStartEnd;
        function rangeOverlapsWithStartEnd(r1, start, end) {
            return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
        }
        ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd;
        function nodeOverlapsWithStartEnd(node, sourceFile, start, end) {
            return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end);
        }
        ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd;
        function startEndOverlapsWithStartEnd(start1, end1, start2, end2) {
            var start = Math.max(start1, start2);
            var end = Math.min(end1, end2);
            return start < end;
        }
        ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd;
        /**
         * Assumes `candidate.start <= position` holds.
         */
        function positionBelongsToNode(candidate, position, sourceFile) {
            ts.Debug.assert(candidate.pos <= position);
            return position < candidate.end || !isCompletedNode(candidate, sourceFile);
        }
        ts.positionBelongsToNode = positionBelongsToNode;
        function isCompletedNode(n, sourceFile) {
            if (n === undefined || ts.nodeIsMissing(n)) {
                return false;
            }
            switch (n.kind) {
                case 238 /* ClassDeclaration */:
                case 239 /* InterfaceDeclaration */:
                case 241 /* EnumDeclaration */:
                case 186 /* ObjectLiteralExpression */:
                case 182 /* ObjectBindingPattern */:
                case 166 /* TypeLiteral */:
                case 216 /* Block */:
                case 243 /* ModuleBlock */:
                case 244 /* CaseBlock */:
                case 250 /* NamedImports */:
                case 254 /* NamedExports */:
                    return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile);
                case 272 /* CatchClause */:
                    return isCompletedNode(n.block, sourceFile);
                case 190 /* NewExpression */:
                    if (!n.arguments) {
                        return true;
                    }
                // falls through
                case 189 /* CallExpression */:
                case 193 /* ParenthesizedExpression */:
                case 175 /* ParenthesizedType */:
                    return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile);
                case 163 /* FunctionType */:
                case 164 /* ConstructorType */:
                    return isCompletedNode(n.type, sourceFile);
                case 155 /* Constructor */:
                case 156 /* GetAccessor */:
                case 157 /* SetAccessor */:
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                case 154 /* MethodDeclaration */:
                case 153 /* MethodSignature */:
                case 159 /* ConstructSignature */:
                case 158 /* CallSignature */:
                case 195 /* ArrowFunction */:
                    if (n.body) {
                        return isCompletedNode(n.body, sourceFile);
                    }
                    if (n.type) {
                        return isCompletedNode(n.type, sourceFile);
                    }
                    // Even though type parameters can be unclosed, we can get away with
                    // having at least a closing paren.
                    return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile);
                case 242 /* ModuleDeclaration */:
                    return !!n.body && isCompletedNode(n.body, sourceFile);
                case 220 /* IfStatement */:
                    if (n.elseStatement) {
                        return isCompletedNode(n.elseStatement, sourceFile);
                    }
                    return isCompletedNode(n.thenStatement, sourceFile);
                case 219 /* ExpressionStatement */:
                    return isCompletedNode(n.expression, sourceFile) ||
                        hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile);
                case 185 /* ArrayLiteralExpression */:
                case 183 /* ArrayBindingPattern */:
                case 188 /* ElementAccessExpression */:
                case 147 /* ComputedPropertyName */:
                case 168 /* TupleType */:
                    return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile);
                case 160 /* IndexSignature */:
                    if (n.type) {
                        return isCompletedNode(n.type, sourceFile);
                    }
                    return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile);
                case 269 /* CaseClause */:
                case 270 /* DefaultClause */:
                    // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed
                    return false;
                case 223 /* ForStatement */:
                case 224 /* ForInStatement */:
                case 225 /* ForOfStatement */:
                case 222 /* WhileStatement */:
                    return isCompletedNode(n.statement, sourceFile);
                case 221 /* DoStatement */:
                    // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
                    return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile)
                        ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile)
                        : isCompletedNode(n.statement, sourceFile);
                case 165 /* TypeQuery */:
                    return isCompletedNode(n.exprName, sourceFile);
                case 197 /* TypeOfExpression */:
                case 196 /* DeleteExpression */:
                case 198 /* VoidExpression */:
                case 205 /* YieldExpression */:
                case 206 /* SpreadElement */:
                    var unaryWordExpression = n;
                    return isCompletedNode(unaryWordExpression.expression, sourceFile);
                case 191 /* TaggedTemplateExpression */:
                    return isCompletedNode(n.template, sourceFile);
                case 204 /* TemplateExpression */:
                    var lastSpan = ts.lastOrUndefined(n.templateSpans);
                    return isCompletedNode(lastSpan, sourceFile);
                case 214 /* TemplateSpan */:
                    return ts.nodeIsPresent(n.literal);
                case 253 /* ExportDeclaration */:
                case 247 /* ImportDeclaration */:
                    return ts.nodeIsPresent(n.moduleSpecifier);
                case 200 /* PrefixUnaryExpression */:
                    return isCompletedNode(n.operand, sourceFile);
                case 202 /* BinaryExpression */:
                    return isCompletedNode(n.right, sourceFile);
                case 203 /* ConditionalExpression */:
                    return isCompletedNode(n.whenFalse, sourceFile);
                default:
                    return true;
            }
        }
        /*
         * Checks if node ends with 'expectedLastToken'.
         * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
         */
        function nodeEndsWith(n, expectedLastToken, sourceFile) {
            var children = n.getChildren(sourceFile);
            if (children.length) {
                var lastChild = ts.last(children);
                if (lastChild.kind === expectedLastToken) {
                    return true;
                }
                else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) {
                    return children[children.length - 2].kind === expectedLastToken;
                }
            }
            return false;
        }
        function findListItemInfo(node) {
            var list = findContainingList(node);
            // It is possible at this point for syntaxList to be undefined, either if
            // node.parent had no list child, or if none of its list children contained
            // the span of node. If this happens, return undefined. The caller should
            // handle this case.
            if (!list) {
                return undefined;
            }
            var children = list.getChildren();
            var listItemIndex = ts.indexOfNode(children, node);
            return {
                listItemIndex: listItemIndex,
                list: list
            };
        }
        ts.findListItemInfo = findListItemInfo;
        function hasChildOfKind(n, kind, sourceFile) {
            return !!findChildOfKind(n, kind, sourceFile);
        }
        ts.hasChildOfKind = hasChildOfKind;
        function findChildOfKind(n, kind, sourceFile) {
            return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; });
        }
        ts.findChildOfKind = findChildOfKind;
        function findContainingList(node) {
            // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will
            // be parented by the container of the SyntaxList, not the SyntaxList itself.
            // In order to find the list item index, we first need to locate SyntaxList itself and then search
            // for the position of the relevant node (or comma).
            var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
            // Either we didn't find an appropriate list, or the list must contain us.
            ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
            return syntaxList;
        }
        ts.findContainingList = findContainingList;
        /**
         * Gets the token whose text has range [start, end) and
         * position >= start and (position < end or (position === end && token is literal or keyword or identifier))
         */
        function getTouchingPropertyName(sourceFile, position) {
            return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); });
        }
        ts.getTouchingPropertyName = getTouchingPropertyName;
        /**
         * Returns the token if position is in [start, end).
         * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true
         */
        function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) {
            return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false);
        }
        ts.getTouchingToken = getTouchingToken;
        /** Returns a token if position is in [start-of-leading-trivia, end) */
        function getTokenAtPosition(sourceFile, position) {
            return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false);
        }
        ts.getTokenAtPosition = getTokenAtPosition;
        /** Get the token whose text contains the position */
        function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) {
            var current = sourceFile;
            outer: while (true) {
                // find the child that contains 'position'
                for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) {
                    var child = _a[_i];
                    var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true);
                    if (start > position) {
                        // If this child begins after position, then all subsequent children will as well.
                        break;
                    }
                    var end = child.getEnd();
                    if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) {
                        current = child;
                        continue outer;
                    }
                    else if (includePrecedingTokenAtEndPosition && end === position) {
                        var previousToken = findPrecedingToken(position, sourceFile, child);
                        if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) {
                            return previousToken;
                        }
                    }
                }
                return current;
            }
        }
        /**
         * The token on the left of the position is the token that strictly includes the position
         * or sits to the left of the cursor if it is on a boundary. For example
         *
         *   fo|o               -> will return foo
         *   foo <comment> |bar -> will return foo
         *
         */
        function findTokenOnLeftOfPosition(file, position) {
            // Ideally, getTokenAtPosition should return a token. However, it is currently
            // broken, so we do a check to make sure the result was indeed a token.
            var tokenAtPosition = getTokenAtPosition(file, position);
            if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
                return tokenAtPosition;
            }
            return findPrecedingToken(position, file);
        }
        ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
        function findNextToken(previousToken, parent, sourceFile) {
            return find(parent);
            function find(n) {
                if (ts.isToken(n) && n.pos === previousToken.end) {
                    // this is token that starts at the end of previous token - return it
                    return n;
                }
                return ts.firstDefined(n.getChildren(), function (child) {
                    var shouldDiveInChildNode = 
                    // previous token is enclosed somewhere in the child
                    (child.pos <= previousToken.pos && child.end > previousToken.end) ||
                        // previous token ends exactly at the beginning of child
                        (child.pos === previousToken.end);
                    return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined;
                });
            }
        }
        ts.findNextToken = findNextToken;
        /**
         * Finds the rightmost token satisfying `token.end <= position`,
         * excluding `JsxText` tokens containing only whitespace.
         */
        function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) {
            var result = find(startNode || sourceFile);
            ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result)));
            return result;
            function find(n) {
                if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) {
                    return n;
                }
                var children = n.getChildren(sourceFile);
                for (var i = 0; i < children.length; i++) {
                    var child = children[i];
                    // Note that the span of a node's tokens is [node.getStart(...), node.end).
                    // Given that `position < child.end` and child has constituent tokens, we distinguish these cases:
                    // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`):
                    // we need to find the last token in a previous child.
                    // 2) `position` is within the same span: we recurse on `child`.
                    if (position < child.end) {
                        var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc);
                        var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
                            !nodeHasTokens(child, sourceFile) ||
                            isWhiteSpaceOnlyJsxText(child);
                        if (lookInPreviousChild) {
                            // actual start of the node is past the position - previous token should be at the end of previous child
                            var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
                            return candidate_2 && findRightmostToken(candidate_2, sourceFile);
                        }
                        else {
                            // candidate should be in this node
                            return find(child);
                        }
                    }
                }
                ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
                // Here we know that none of child token nodes embrace the position,
                // the only known case is when position is at the end of the file.
                // Try to find the rightmost token in the file without filtering.
                // Namely we are skipping the check: 'position < node.end'
                var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
                return candidate && findRightmostToken(candidate, sourceFile);
            }
        }
        ts.findPrecedingToken = findPrecedingToken;
        function isNonWhitespaceToken(n) {
            return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n);
        }
        function findRightmostToken(n, sourceFile) {
            if (isNonWhitespaceToken(n)) {
                return n;
            }
            var children = n.getChildren(sourceFile);
            var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
            return candidate && findRightmostToken(candidate, sourceFile);
        }
        /**
         * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
         */
        function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
            for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
                var child = children[i];
                if (isWhiteSpaceOnlyJsxText(child)) {
                    ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
                }
                else if (nodeHasTokens(children[i], sourceFile)) {
                    return children[i];
                }
            }
        }
        function isInString(sourceFile, position, previousToken) {
            if (previousToken === void 0) {
                previousToken = findPrecedingToken(position, sourceFile);
            }
            if (previousToken && ts.isStringTextContainingNode(previousToken)) {
                var start = previousToken.getStart(sourceFile);
                var end = previousToken.getEnd();
                // To be "in" one of these literals, the position has to be:
                //   1. entirely within the token text.
                //   2. at the end position of an unterminated token.
                //   3. at the end of a regular expression (due to trailing flags like '/foo/g').
                if (start < position && position < end) {
                    return true;
                }
                if (position === end) {
                    return !!previousToken.isUnterminated;
                }
            }
            return false;
        }
        ts.isInString = isInString;
        /**
         * returns true if the position is in between the open and close elements of an JSX expression.
         */
        function isInsideJsxElementOrAttribute(sourceFile, position) {
            var token = getTokenAtPosition(sourceFile, position);
            if (!token) {
                return false;
            }
            if (token.kind === 10 /* JsxText */) {
                return true;
            }
            // <div>Hello |</div>
            if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) {
                return true;
            }
            // <div> { | </div> or <div a={| </div>
            if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) {
                return true;
            }
            // <div> {
            // |
            // } < /div>
            if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) {
                return true;
            }
            // <div>|</div>
            if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) {
                return true;
            }
            return false;
        }
        ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
        function isWhiteSpaceOnlyJsxText(node) {
            return ts.isJsxText(node) && node.containsOnlyWhiteSpaces;
        }
        function isInTemplateString(sourceFile, position) {
            var token = getTokenAtPosition(sourceFile, position);
            return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
        }
        ts.isInTemplateString = isInTemplateString;
        function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) {
            var tokenKind = token.kind;
            var remainingMatchingTokens = 0;
            while (true) {
                var preceding = findPrecedingToken(token.getFullStart(), sourceFile);
                if (!preceding) {
                    return undefined;
                }
                token = preceding;
                if (token.kind === matchingTokenKind) {
                    if (remainingMatchingTokens === 0) {
                        return token;
                    }
                    remainingMatchingTokens--;
                }
                else if (token.kind === tokenKind) {
                    remainingMatchingTokens++;
                }
            }
        }
        ts.findPrecedingMatchingToken = findPrecedingMatchingToken;
        function isPossiblyTypeArgumentPosition(token, sourceFile, checker) {
            var info = getPossibleTypeArgumentsInfo(token, sourceFile);
            return info !== undefined && (ts.isPartOfTypeNode(info.called) ||
                getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 ||
                isPossiblyTypeArgumentPosition(info.called, sourceFile, checker));
        }
        ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition;
        function getPossibleGenericSignatures(called, typeArgumentCount, checker) {
            var type = checker.getTypeAtLocation(called);
            var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures();
            return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; });
        }
        ts.getPossibleGenericSignatures = getPossibleGenericSignatures;
        // Get info for an expression like `f <` that may be the start of type arguments.
        function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) {
            var token = tokenIn;
            // This function determines if the node could be type argument position
            // Since during editing, when type argument list is not complete,
            // the tree could be of any shape depending on the tokens parsed before current node,
            // scanning of the previous identifier followed by "<" before current node would give us better result
            // Note that we also balance out the already provided type arguments, arrays, object literals while doing so
            var remainingLessThanTokens = 0;
            var nTypeArguments = 0;
            while (token) {
                switch (token.kind) {
                    case 27 /* LessThanToken */:
                        // Found the beginning of the generic argument expression
                        token = findPrecedingToken(token.getFullStart(), sourceFile);
                        if (!token || !ts.isIdentifier(token))
                            return undefined;
                        if (!remainingLessThanTokens) {
                            return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments };
                        }
                        remainingLessThanTokens--;
                        break;
                    case 47 /* GreaterThanGreaterThanGreaterThanToken */:
                        remainingLessThanTokens = +3;
                        break;
                    case 46 /* GreaterThanGreaterThanToken */:
                        remainingLessThanTokens = +2;
                        break;
                    case 29 /* GreaterThanToken */:
                        remainingLessThanTokens++;
                        break;
                    case 18 /* CloseBraceToken */:
                        // This can be object type, skip until we find the matching open brace token
                        // Skip until the matching open brace token
                        token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile);
                        if (!token)
                            return undefined;
                        break;
                    case 20 /* CloseParenToken */:
                        // This can be object type, skip until we find the matching open brace token
                        // Skip until the matching open brace token
                        token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile);
                        if (!token)
                            return undefined;
                        break;
                    case 22 /* CloseBracketToken */:
                        // This can be object type, skip until we find the matching open brace token
                        // Skip until the matching open brace token
                        token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile);
                        if (!token)
                            return undefined;
                        break;
                    // Valid tokens in a type name. Skip.
                    case 26 /* CommaToken */:
                        nTypeArguments++;
                        break;
                    case 36 /* EqualsGreaterThanToken */:
                    case 71 /* Identifier */:
                    case 9 /* StringLiteral */:
                    case 8 /* NumericLiteral */:
                    case 101 /* TrueKeyword */:
                    case 86 /* FalseKeyword */:
                    case 103 /* TypeOfKeyword */:
                    case 85 /* ExtendsKeyword */:
                    case 128 /* KeyOfKeyword */:
                    case 23 /* DotToken */:
                    case 49 /* BarToken */:
                    case 55 /* QuestionToken */:
                    case 56 /* ColonToken */:
                        break;
                    default:
                        if (ts.isTypeNode(token)) {
                            break;
                        }
                        // Invalid token in type
                        return undefined;
                }
                token = findPrecedingToken(token.getFullStart(), sourceFile);
            }
            return undefined;
        }
        ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo;
        /**
         * Returns true if the cursor at position in sourceFile is within a comment.
         *
         * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)
         * @param predicate Additional predicate to test on the comment range.
         */
        function isInComment(sourceFile, position, tokenAtPosition) {
            return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition);
        }
        ts.isInComment = isInComment;
        function hasDocComment(sourceFile, position) {
            var token = getTokenAtPosition(sourceFile, position);
            return !!ts.findAncestor(token, ts.isJSDoc);
        }
        ts.hasDocComment = hasDocComment;
        function nodeHasTokens(n, sourceFile) {
            // If we have a token or node that has a non-zero width, it must have tokens.
            // Note: getWidth() does not take trivia into account.
            return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
        }
        function getNodeModifiers(node) {
            var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */;
            var result = [];
            if (flags & 8 /* Private */)
                result.push("private" /* privateMemberModifier */);
            if (flags & 16 /* Protected */)
                result.push("protected" /* protectedMemberModifier */);
            if (flags & 4 /* Public */)
                result.push("public" /* publicMemberModifier */);
            if (flags & 32 /* Static */)
                result.push("static" /* staticModifier */);
            if (flags & 128 /* Abstract */)
                result.push("abstract" /* abstractModifier */);
            if (flags & 1 /* Export */)
                result.push("export" /* exportedModifier */);
            if (node.flags & 4194304 /* Ambient */)
                result.push("declare" /* ambientModifier */);
            return result.length > 0 ? result.join(",") : "" /* none */;
        }
        ts.getNodeModifiers = getNodeModifiers;
        function getTypeArgumentOrTypeParameterList(node) {
            if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) {
                return node.typeArguments;
            }
            if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) {
                return node.typeParameters;
            }
            return undefined;
        }
        ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList;
        function isComment(kind) {
            return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */;
        }
        ts.isComment = isComment;
        function isStringOrRegularExpressionOrTemplateLiteral(kind) {
            if (kind === 9 /* StringLiteral */
                || kind === 12 /* RegularExpressionLiteral */
                || ts.isTemplateLiteralKind(kind)) {
                return true;
            }
            return false;
        }
        ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral;
        function isPunctuation(kind) {
            return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */;
        }
        ts.isPunctuation = isPunctuation;
        function isInsideTemplateLiteral(node, position, sourceFile) {
            return ts.isTemplateLiteralKind(node.kind)
                && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end);
        }
        ts.isInsideTemplateLiteral = isInsideTemplateLiteral;
        function isAccessibilityModifier(kind) {
            switch (kind) {
                case 114 /* PublicKeyword */:
                case 112 /* PrivateKeyword */:
                case 113 /* ProtectedKeyword */:
                    return true;
            }
            return false;
        }
        ts.isAccessibilityModifier = isAccessibilityModifier;
        function cloneCompilerOptions(options) {
            var result = ts.clone(options);
            ts.setConfigFileInOptions(result, options && options.configFile);
            return result;
        }
        ts.cloneCompilerOptions = cloneCompilerOptions;
        function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
            if (node.kind === 185 /* ArrayLiteralExpression */ ||
                node.kind === 186 /* ObjectLiteralExpression */) {
                // [a,b,c] from:
                // [a, b, c] = someExpression;
                if (node.parent.kind === 202 /* BinaryExpression */ &&
                    node.parent.left === node &&
                    node.parent.operatorToken.kind === 58 /* EqualsToken */) {
                    return true;
                }
                // [a, b, c] from:
                // for([a, b, c] of expression)
                if (node.parent.kind === 225 /* ForOfStatement */ &&
                    node.parent.initializer === node) {
                    return true;
                }
                // [a, b, c] of
                // [x, [a, b, c] ] = someExpression
                // or
                // {x, a: {a, b, c} } = someExpression
                if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
                    return true;
                }
            }
            return false;
        }
        ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
        function isInReferenceComment(sourceFile, position) {
            return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true);
        }
        ts.isInReferenceComment = isInReferenceComment;
        function isInNonReferenceComment(sourceFile, position) {
            return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false);
        }
        ts.isInNonReferenceComment = isInNonReferenceComment;
        function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) {
            var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined);
            return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end));
        }
        function createTextSpanFromNode(node, sourceFile) {
            return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd());
        }
        ts.createTextSpanFromNode = createTextSpanFromNode;
        function createTextRangeFromNode(node, sourceFile) {
            return ts.createRange(node.getStart(sourceFile), node.end);
        }
        ts.createTextRangeFromNode = createTextRangeFromNode;
        function createTextSpanFromRange(range) {
            return ts.createTextSpanFromBounds(range.pos, range.end);
        }
        ts.createTextSpanFromRange = createTextSpanFromRange;
        function createTextRangeFromSpan(span) {
            return ts.createRange(span.start, span.start + span.length);
        }
        ts.createTextRangeFromSpan = createTextRangeFromSpan;
        function createTextChangeFromStartLength(start, length, newText) {
            return createTextChange(ts.createTextSpan(start, length), newText);
        }
        ts.createTextChangeFromStartLength = createTextChangeFromStartLength;
        function createTextChange(span, newText) {
            return { span: span, newText: newText };
        }
        ts.createTextChange = createTextChange;
        ts.typeKeywords = [
            119 /* AnyKeyword */,
            122 /* BooleanKeyword */,
            86 /* FalseKeyword */,
            128 /* KeyOfKeyword */,
            131 /* NeverKeyword */,
            95 /* NullKeyword */,
            134 /* NumberKeyword */,
            135 /* ObjectKeyword */,
            137 /* StringKeyword */,
            138 /* SymbolKeyword */,
            101 /* TrueKeyword */,
            105 /* VoidKeyword */,
            140 /* UndefinedKeyword */,
            141 /* UniqueKeyword */,
            142 /* UnknownKeyword */,
        ];
        function isTypeKeyword(kind) {
            return ts.contains(ts.typeKeywords, kind);
        }
        ts.isTypeKeyword = isTypeKeyword;
        /** True if the symbol is for an external module, as opposed to a namespace. */
        function isExternalModuleSymbol(moduleSymbol) {
            return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
        }
        ts.isExternalModuleSymbol = isExternalModuleSymbol;
        function nodeSeenTracker() {
            var seen = [];
            return function (node) {
                var id = ts.getNodeId(node);
                return !seen[id] && (seen[id] = true);
            };
        }
        ts.nodeSeenTracker = nodeSeenTracker;
        function getSnapshotText(snap) {
            return snap.getText(0, snap.getLength());
        }
        ts.getSnapshotText = getSnapshotText;
        function repeatString(str, count) {
            var result = "";
            for (var i = 0; i < count; i++) {
                result += str;
            }
            return result;
        }
        ts.repeatString = repeatString;
        function skipConstraint(type) {
            return type.isTypeParameter() ? type.getConstraint() || type : type;
        }
        ts.skipConstraint = skipConstraint;
        function getNameFromPropertyName(name) {
            return name.kind === 147 /* ComputedPropertyName */
                // treat computed property names where expression is string/numeric literal as just string/numeric literal
                ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined
                : ts.getTextOfIdentifierOrLiteral(name);
        }
        ts.getNameFromPropertyName = getNameFromPropertyName;
        function programContainsEs6Modules(program) {
            return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; });
        }
        ts.programContainsEs6Modules = programContainsEs6Modules;
        function compilerOptionsIndicateEs6Modules(compilerOptions) {
            return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit;
        }
        ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules;
        function hostUsesCaseSensitiveFileNames(host) {
            return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
        }
        ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
        function hostGetCanonicalFileName(host) {
            return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
        }
        ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
        function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) {
            return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined;
        }
        ts.makeImportIfNecessary = makeImportIfNecessary;
        function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) {
            return ts.createImportDeclaration(
            /*decorators*/ undefined, 
            /*modifiers*/ undefined, defaultImport || namedImports
                ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined)
                : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier);
        }
        ts.makeImport = makeImport;
        function makeStringLiteral(text, quotePreference) {
            return ts.createLiteral(text, quotePreference === 0 /* Single */);
        }
        ts.makeStringLiteral = makeStringLiteral;
        var QuotePreference;
        (function (QuotePreference) {
            QuotePreference[QuotePreference["Single"] = 0] = "Single";
            QuotePreference[QuotePreference["Double"] = 1] = "Double";
        })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {}));
        function quotePreferenceFromString(str, sourceFile) {
            return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */;
        }
        ts.quotePreferenceFromString = quotePreferenceFromString;
        function getQuotePreference(sourceFile, preferences) {
            if (preferences.quotePreference) {
                return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */;
            }
            else {
                var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral);
                return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */;
            }
        }
        ts.getQuotePreference = getQuotePreference;
        function getQuoteFromPreference(qp) {
            switch (qp) {
                case 0 /* Single */: return "'";
                case 1 /* Double */: return '"';
                default: return ts.Debug.assertNever(qp);
            }
        }
        ts.getQuoteFromPreference = getQuoteFromPreference;
        function symbolNameNoDefault(symbol) {
            var escaped = symbolEscapedNameNoDefault(symbol);
            return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
        }
        ts.symbolNameNoDefault = symbolNameNoDefault;
        function symbolEscapedNameNoDefault(symbol) {
            if (symbol.escapedName !== "default" /* Default */) {
                return symbol.escapedName;
            }
            return ts.firstDefined(symbol.declarations, function (decl) {
                var name = ts.getNameOfDeclaration(decl);
                return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined;
            });
        }
        ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
        function getPropertySymbolFromBindingElement(checker, bindingElement) {
            var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
            var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
            if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
                // See GH#16922
                ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
                return propSymbol.target;
            }
            return propSymbol;
        }
        ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
        /**
         * Find symbol of the given property-name and add the symbol to the given result array
         * @param symbol a symbol to start searching for the given propertyName
         * @param propertyName a name of property to search for
         * @param result an array of symbol of found property symbols
         * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
         *                                The value of previousIterationSymbol is undefined when the function is first called.
         */
        function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
            var seen = ts.createMap();
            return recur(symbol);
            function recur(symbol) {
                // Use `addToSeen` to ensure we don't infinitely recurse in this situation:
                //      interface C extends C {
                //          /*findRef*/propName: string;
                //      }
                if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol)))
                    return;
                return ts.firstDefined(symbol.declarations, function (declaration) {
                    return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) {
                        var type = checker.getTypeAtLocation(typeReference);
                        var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
                        // Visit the typeReference as well to see if it directly or indirectly uses that property
                        return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
                    });
                });
            }
        }
        ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes;
        function isMemberSymbolInBaseType(memberSymbol, checker) {
            return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false;
        }
        ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType;
        function getParentNodeInSpan(node, file, span) {
            if (!node)
                return undefined;
            while (node.parent) {
                if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) {
                    return node;
                }
                node = node.parent;
            }
        }
        ts.getParentNodeInSpan = getParentNodeInSpan;
        function spanContainsNode(span, node, file) {
            return ts.textSpanContainsPosition(span, node.getStart(file)) &&
                node.getEnd() <= ts.textSpanEnd(span);
        }
        function findModifier(node, kind) {
            return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; });
        }
        ts.findModifier = findModifier;
        /* @internal */
        function insertImport(changes, sourceFile, importDecl) {
            var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax);
            if (lastImportDeclaration) {
                changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl);
            }
            else {
                changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true);
            }
        }
        ts.insertImport = insertImport;
        function textSpansEqual(a, b) {
            return !!a && !!b && a.start === b.start && a.length === b.length;
        }
        ts.textSpansEqual = textSpansEqual;
        function documentSpansEqual(a, b) {
            return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan);
        }
        ts.documentSpansEqual = documentSpansEqual;
    })(ts || (ts = {}));
    // Display-part writer helpers
    /* @internal */
    (function (ts) {
        function isFirstDeclarationOfSymbolParameter(symbol) {
            return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 149 /* Parameter */;
        }
        ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter;
        var displayPartWriter = getDisplayPartWriter();
        function getDisplayPartWriter() {
            var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios
            var displayParts;
            var lineStart;
            var indent;
            var length;
            resetWriter();
            var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); };
            return {
                displayParts: function () {
                    var finalText = displayParts.length && displayParts[displayParts.length - 1].text;
                    if (length > absoluteMaximumLength && finalText && finalText !== "...") {
                        if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) {
                            displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space));
                        }
                        displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation));
                    }
                    return displayParts;
                },
                writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); },
                writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); },
                writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); },
                writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); },
                writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
                writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); },
                writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); },
                writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
                writeSymbol: writeSymbol,
                writeLine: writeLine,
                write: unknownWrite,
                writeTextOfNode: unknownWrite,
                getText: function () { return ""; },
                getTextPos: function () { return 0; },
                getColumn: function () { return 0; },
                getLine: function () { return 0; },
                isAtStartOfLine: function () { return false; },
                rawWrite: ts.notImplemented,
                getIndent: function () { return indent; },
                increaseIndent: function () { indent++; },
                decreaseIndent: function () { indent--; },
                clear: resetWriter,
                trackSymbol: ts.noop,
                reportInaccessibleThisError: ts.noop,
                reportInaccessibleUniqueSymbolError: ts.noop,
                reportPrivateInBaseOfClassExpression: ts.noop,
            };
            function writeIndent() {
                if (length > absoluteMaximumLength)
                    return;
                if (lineStart) {
                    var indentString = ts.getIndentString(indent);
                    if (indentString) {
                        length += indentString.length;
                        displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space));
                    }
                    lineStart = false;
                }
            }
            function writeKind(text, kind) {
                if (length > absoluteMaximumLength)
                    return;
                writeIndent();
                length += text.length;
                displayParts.push(displayPart(text, kind));
            }
            function writeSymbol(text, symbol) {
                if (length > absoluteMaximumLength)
                    return;
                writeIndent();
                length += text.length;
                displayParts.push(symbolPart(text, symbol));
            }
            function writeLine() {
                if (length > absoluteMaximumLength)
                    return;
                length += 1;
                displayParts.push(lineBreakPart());
                lineStart = true;
            }
            function resetWriter() {
                displayParts = [];
                lineStart = true;
                indent = 0;
                length = 0;
            }
        }
        function symbolPart(text, symbol) {
            return displayPart(text, displayPartKind(symbol));
            function displayPartKind(symbol) {
                var flags = symbol.flags;
                if (flags & 3 /* Variable */) {
                    return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName;
                }
                else if (flags & 4 /* Property */) {
                    return ts.SymbolDisplayPartKind.propertyName;
                }
                else if (flags & 32768 /* GetAccessor */) {
                    return ts.SymbolDisplayPartKind.propertyName;
                }
                else if (flags & 65536 /* SetAccessor */) {
                    return ts.SymbolDisplayPartKind.propertyName;
                }
                else if (flags & 8 /* EnumMember */) {
                    return ts.SymbolDisplayPartKind.enumMemberName;
                }
                else if (flags & 16 /* Function */) {
                    return ts.SymbolDisplayPartKind.functionName;
                }
                else if (flags & 32 /* Class */) {
                    return ts.SymbolDisplayPartKind.className;
                }
                else if (flags & 64 /* Interface */) {
                    return ts.SymbolDisplayPartKind.interfaceName;
                }
                else if (flags & 384 /* Enum */) {
                    return ts.SymbolDisplayPartKind.enumName;
                }
                else if (flags & 1536 /* Module */) {
                    return ts.SymbolDisplayPartKind.moduleName;
                }
                else if (flags & 8192 /* Method */) {
                    return ts.SymbolDisplayPartKind.methodName;
                }
                else if (flags & 262144 /* TypeParameter */) {
                    return ts.SymbolDisplayPartKind.typeParameterName;
                }
                else if (flags & 524288 /* TypeAlias */) {
                    return ts.SymbolDisplayPartKind.aliasName;
                }
                else if (flags & 2097152 /* Alias */) {
                    return ts.SymbolDisplayPartKind.aliasName;
                }
                return ts.SymbolDisplayPartKind.text;
            }
        }
        ts.symbolPart = symbolPart;
        function displayPart(text, kind) {
            return { text: text, kind: ts.SymbolDisplayPartKind[kind] };
        }
        ts.displayPart = displayPart;
        function spacePart() {
            return displayPart(" ", ts.SymbolDisplayPartKind.space);
        }
        ts.spacePart = spacePart;
        function keywordPart(kind) {
            return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword);
        }
        ts.keywordPart = keywordPart;
        function punctuationPart(kind) {
            return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation);
        }
        ts.punctuationPart = punctuationPart;
        function operatorPart(kind) {
            return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator);
        }
        ts.operatorPart = operatorPart;
        function textOrKeywordPart(text) {
            var kind = ts.stringToToken(text);
            return kind === undefined
                ? textPart(text)
                : keywordPart(kind);
        }
        ts.textOrKeywordPart = textOrKeywordPart;
        function textPart(text) {
            return displayPart(text, ts.SymbolDisplayPartKind.text);
        }
        ts.textPart = textPart;
        var carriageReturnLineFeed = "\r\n";
        /**
         * The default is CRLF.
         */
        function getNewLineOrDefaultFromHost(host, formatSettings) {
            return (formatSettings && formatSettings.newLineCharacter) ||
                (host.getNewLine && host.getNewLine()) ||
                carriageReturnLineFeed;
        }
        ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost;
        function lineBreakPart() {
            return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak);
        }
        ts.lineBreakPart = lineBreakPart;
        /* @internal */
        function mapToDisplayParts(writeDisplayParts) {
            try {
                writeDisplayParts(displayPartWriter);
                return displayPartWriter.displayParts();
            }
            finally {
                displayPartWriter.clear();
            }
        }
        ts.mapToDisplayParts = mapToDisplayParts;
        function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) {
            if (flags === void 0) {
                flags = 0 /* None */;
            }
            return mapToDisplayParts(function (writer) {
                typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer);
            });
        }
        ts.typeToDisplayParts = typeToDisplayParts;
        function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) {
            if (flags === void 0) {
                flags = 0 /* None */;
            }
            return mapToDisplayParts(function (writer) {
                typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer);
            });
        }
        ts.symbolToDisplayParts = symbolToDisplayParts;
        function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) {
            if (flags === void 0) {
                flags = 0 /* None */;
            }
            flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */;
            return mapToDisplayParts(function (writer) {
                typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer);
            });
        }
        ts.signatureToDisplayParts = signatureToDisplayParts;
        function isImportOrExportSpecifierName(location) {
            return !!location.parent &&
                (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) &&
                location.parent.propertyName === location;
        }
        ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
        /**
         * Strip off existed single quotes or double quotes from a given string
         *
         * @return non-quoted string
         */
        function stripQuotes(name) {
            var length = name.length;
            if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) {
                return name.substring(1, length - 1);
            }
            return name;
        }
        ts.stripQuotes = stripQuotes;
        function startsWithQuote(name) {
            return ts.isSingleOrDoubleQuote(name.charCodeAt(0));
        }
        ts.startsWithQuote = startsWithQuote;
        function scriptKindIs(fileName, host) {
            var scriptKinds = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                scriptKinds[_i - 2] = arguments[_i];
            }
            var scriptKind = getScriptKind(fileName, host);
            return ts.some(scriptKinds, function (k) { return k === scriptKind; });
        }
        ts.scriptKindIs = scriptKindIs;
        function getScriptKind(fileName, host) {
            // First check to see if the script kind was specified by the host. Chances are the host
            // may override the default script kind for the file extension.
            return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
        }
        ts.getScriptKind = getScriptKind;
        function getUniqueSymbolId(symbol, checker) {
            return ts.getSymbolId(ts.skipAlias(symbol, checker));
        }
        ts.getUniqueSymbolId = getUniqueSymbolId;
        function getFirstNonSpaceCharacterPosition(text, position) {
            while (ts.isWhiteSpaceLike(text.charCodeAt(position))) {
                position += 1;
            }
            return position;
        }
        ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition;
        /**
         * Creates a deep, memberwise clone of a node with no source map location.
         *
         * WARNING: This is an expensive operation and is only intended to be used in refactorings
         * and code fixes (because those are triggered by explicit user actions).
         */
        function getSynthesizedDeepClone(node, includeTrivia) {
            if (includeTrivia === void 0) {
                includeTrivia = true;
            }
            var clone = node && getSynthesizedDeepCloneWorker(node);
            if (clone && !includeTrivia)
                suppressLeadingAndTrailingTrivia(clone);
            return clone;
        }
        ts.getSynthesizedDeepClone = getSynthesizedDeepClone;
        function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) {
            if (includeTrivia === void 0) {
                includeTrivia = true;
            }
            var clone;
            if (ts.isIdentifier(node) && renameMap && checker) {
                var symbol = checker.getSymbolAtLocation(node);
                var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol)));
                if (renameInfo) {
                    clone = ts.createIdentifier(renameInfo.text);
                }
            }
            if (!clone) {
                clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback);
            }
            if (clone && !includeTrivia)
                suppressLeadingAndTrailingTrivia(clone);
            if (callback && clone)
                callback(node, clone);
            return clone;
        }
        ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames;
        function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) {
            var visited = (renameMap || checker || callback) ?
                ts.visitEachChild(node, wrapper, ts.nullTransformationContext) :
                ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
            if (visited === node) {
                // This only happens for leaf nodes - internal nodes always see their children change.
                var clone_7 = ts.getSynthesizedClone(node);
                if (ts.isStringLiteral(clone_7)) {
                    clone_7.textSourceNode = node;
                }
                else if (ts.isNumericLiteral(clone_7)) {
                    clone_7.numericLiteralFlags = node.numericLiteralFlags;
                }
                return ts.setTextRange(clone_7, node);
            }
            // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
            // the new node created by visitEachChild with the extra changes getSynthesizedClone
            // would have made.
            visited.parent = undefined;
            return visited;
            function wrapper(node) {
                return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback);
            }
        }
        function getSynthesizedDeepClones(nodes, includeTrivia) {
            if (includeTrivia === void 0) {
                includeTrivia = true;
            }
            return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma);
        }
        ts.getSynthesizedDeepClones = getSynthesizedDeepClones;
        /**
         * Sets EmitFlags to suppress leading and trailing trivia on the node.
         */
        /* @internal */
        function suppressLeadingAndTrailingTrivia(node) {
            suppressLeadingTrivia(node);
            suppressTrailingTrivia(node);
        }
        ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia;
        /**
         * Sets EmitFlags to suppress leading trivia on the node.
         */
        /* @internal */
        function suppressLeadingTrivia(node) {
            addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild);
        }
        ts.suppressLeadingTrivia = suppressLeadingTrivia;
        /**
         * Sets EmitFlags to suppress trailing trivia on the node.
         */
        /* @internal */
        function suppressTrailingTrivia(node) {
            addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild);
        }
        ts.suppressTrailingTrivia = suppressTrailingTrivia;
        function addEmitFlagsRecursively(node, flag, getChild) {
            ts.addEmitFlags(node, flag);
            var child = getChild(node);
            if (child)
                addEmitFlagsRecursively(child, flag, getChild);
        }
        function getFirstChild(node) {
            return node.forEachChild(function (child) { return child; });
        }
        /* @internal */
        function getUniqueName(baseName, sourceFile) {
            var nameText = baseName;
            for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) {
                nameText = baseName + "_" + i;
            }
            return nameText;
        }
        ts.getUniqueName = getUniqueName;
        /**
         * @return The index of the (only) reference to the extracted symbol.  We want the cursor
         * to be on the reference, rather than the declaration, because it's closer to where the
         * user was before extracting it.
         */
        /* @internal */
        function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
            var delta = 0;
            var lastPos = -1;
            for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
                var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
                ts.Debug.assert(fileName === renameFilename);
                for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
                    var change = textChanges_1[_b];
                    var span = change.span, newText = change.newText;
                    var index = indexInTextChange(newText, name);
                    if (index !== -1) {
                        lastPos = span.start + delta + index;
                        // If the reference comes first, return immediately.
                        if (!preferLastLocation) {
                            return lastPos;
                        }
                    }
                    delta += newText.length - span.length;
                }
            }
            // If the declaration comes first, return the position of the last occurrence.
            ts.Debug.assert(preferLastLocation);
            ts.Debug.assert(lastPos >= 0);
            return lastPos;
        }
        ts.getRenameLocation = getRenameLocation;
        function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
            ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
                if (kind === 3 /* MultiLineCommentTrivia */) {
                    // Remove leading /*
                    pos += 2;
                    // Remove trailing */
                    end -= 2;
                }
                else {
                    // Remove leading //
                    pos += 2;
                }
                ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
            });
        }
        ts.copyComments = copyComments;
        function indexInTextChange(change, name) {
            if (ts.startsWith(change, name))
                return 0;
            // Add a " " to avoid references inside words
            var idx = change.indexOf(" " + name);
            if (idx === -1)
                idx = change.indexOf("." + name);
            if (idx === -1)
                idx = change.indexOf('"' + name);
            return idx === -1 ? -1 : idx + 1;
        }
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        function createClassifier() {
            var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false);
            function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
                return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
            }
            // If there is a syntactic classifier ('syntacticClassifierAbsent' is false),
            // we will be more conservative in order to avoid conflicting with the syntactic classifier.
            function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) {
                var token = 0 /* Unknown */;
                var lastNonTriviaToken = 0 /* Unknown */;
                // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact)
                // classification on template strings. Because of the context free nature of templates,
                // the only precise way to classify a template portion would be by propagating the stack across
                // lines, just as we do with the end-of-line state. However, this is a burden for implementers,
                // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead
                // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state.
                // Situations in which this fails are
                //  1) When template strings are nested across different lines:
                //          `hello ${ `world
                //          ` }`
                //
                //     Where on the second line, you will get the closing of a template,
                //     a closing curly, and a new template.
                //
                //  2) When substitution expressions have curly braces and the curly brace falls on the next line:
                //          `hello ${ () => {
                //          return "world" } } `
                //
                //     Where on the second line, you will get the 'return' keyword,
                //     a string literal, and a template end consisting of '} } `'.
                var templateStack = [];
                var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate;
                text = prefix + text;
                var offset = prefix.length;
                if (pushTemplate) {
                    templateStack.push(14 /* TemplateHead */);
                }
                scanner.setText(text);
                var endOfLineState = 0 /* None */;
                var spans = [];
                // We can run into an unfortunate interaction between the lexical and syntactic classifier
                // when the user is typing something generic.  Consider the case where the user types:
                //
                //      Foo<number
                //
                // From the lexical classifier's perspective, 'number' is a keyword, and so the word will
                // be classified as such.  However, from the syntactic classifier's tree-based perspective
                // this is simply an expression with the identifier 'number' on the RHS of the less than
                // token.  So the classification will go back to being an identifier.  The moment the user
                // types again, number will become a keyword, then an identifier, etc. etc.
                //
                // To try to avoid this problem, we avoid classifying contextual keywords as keywords
                // when the user is potentially typing something generic.  We just can't do a good enough
                // job at the lexical level, and so well leave it up to the syntactic classifier to make
                // the determination.
                //
                // In order to determine if the user is potentially typing something generic, we use a
                // weak heuristic where we track < and > tokens.  It's a weak heuristic, but should
                // work well enough in practice.
                var angleBracketStack = 0;
                do {
                    token = scanner.scan();
                    if (!ts.isTrivia(token)) {
                        handleToken();
                        lastNonTriviaToken = token;
                    }
                    var end = scanner.getTextPos();
                    pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans);
                    if (end >= text.length) {
                        var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack));
                        if (end_1 !== undefined) {
                            endOfLineState = end_1;
                        }
                    }
                } while (token !== 1 /* EndOfFileToken */);
                function handleToken() {
                    switch (token) {
                        case 41 /* SlashToken */:
                        case 63 /* SlashEqualsToken */:
                            if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) {
                                token = 12 /* RegularExpressionLiteral */;
                            }
                            break;
                        case 27 /* LessThanToken */:
                            if (lastNonTriviaToken === 71 /* Identifier */) {
                                // Could be the start of something generic.  Keep track of that by bumping
                                // up the current count of generic contexts we may be in.
                                angleBracketStack++;
                            }
                            break;
                        case 29 /* GreaterThanToken */:
                            if (angleBracketStack > 0) {
                                // If we think we're currently in something generic, then mark that that
                                // generic entity is complete.
                                angleBracketStack--;
                            }
                            break;
                        case 119 /* AnyKeyword */:
                        case 137 /* StringKeyword */:
                        case 134 /* NumberKeyword */:
                        case 122 /* BooleanKeyword */:
                        case 138 /* SymbolKeyword */:
                            if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
                                // If it looks like we're could be in something generic, don't classify this
                                // as a keyword.  We may just get overwritten by the syntactic classifier,
                                // causing a noisy experience for the user.
                                token = 71 /* Identifier */;
                            }
                            break;
                        case 14 /* TemplateHead */:
                            templateStack.push(token);
                            break;
                        case 17 /* OpenBraceToken */:
                            // If we don't have anything on the template stack,
                            // then we aren't trying to keep track of a previously scanned template head.
                            if (templateStack.length > 0) {
                                templateStack.push(token);
                            }
                            break;
                        case 18 /* CloseBraceToken */:
                            // If we don't have anything on the template stack,
                            // then we aren't trying to keep track of a previously scanned template head.
                            if (templateStack.length > 0) {
                                var lastTemplateStackToken = ts.lastOrUndefined(templateStack);
                                if (lastTemplateStackToken === 14 /* TemplateHead */) {
                                    token = scanner.reScanTemplateToken();
                                    // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us.
                                    if (token === 16 /* TemplateTail */) {
                                        templateStack.pop();
                                    }
                                    else {
                                        ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle.");
                                    }
                                }
                                else {
                                    ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace");
                                    templateStack.pop();
                                }
                            }
                            break;
                        default:
                            if (!ts.isKeyword(token)) {
                                break;
                            }
                            if (lastNonTriviaToken === 23 /* DotToken */) {
                                token = 71 /* Identifier */;
                            }
                            else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) {
                                // We have two keywords in a row.  Only treat the second as a keyword if
                                // it's a sequence that could legally occur in the language.  Otherwise
                                // treat it as an identifier.  This way, if someone writes "private var"
                                // we recognize that 'var' is actually an identifier here.
                                token = 71 /* Identifier */;
                            }
                    }
                }
                return { endOfLineState: endOfLineState, spans: spans };
            }
            return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications };
        }
        ts.createClassifier = createClassifier;
        /// We do not have a full parser support to know when we should parse a regex or not
        /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where
        /// we have a series of divide operator. this list allows us to be more accurate by ruling out
        /// locations where a regexp cannot exist.
        var noRegexTable = ts.arrayToNumericMap([
            71 /* Identifier */,
            9 /* StringLiteral */,
            8 /* NumericLiteral */,
            12 /* RegularExpressionLiteral */,
            99 /* ThisKeyword */,
            43 /* PlusPlusToken */,
            44 /* MinusMinusToken */,
            20 /* CloseParenToken */,
            22 /* CloseBracketToken */,
            18 /* CloseBraceToken */,
            101 /* TrueKeyword */,
            86 /* FalseKeyword */,
        ], function (token) { return token; }, function () { return true; });
        function getNewEndOfLineState(scanner, token, lastOnTemplateStack) {
            switch (token) {
                case 9 /* StringLiteral */: {
                    // Check to see if we finished up on a multiline string literal.
                    if (!scanner.isUnterminated())
                        return undefined;
                    var tokenText = scanner.getTokenText();
                    var lastCharIndex = tokenText.length - 1;
                    var numBackslashes = 0;
                    while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) {
                        numBackslashes++;
                    }
                    // If we have an odd number of backslashes, then the multiline string is unclosed
                    if ((numBackslashes & 1) === 0)
                        return undefined;
                    return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */;
                }
                case 3 /* MultiLineCommentTrivia */:
                    // Check to see if the multiline comment was unclosed.
                    return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined;
                default:
                    if (ts.isTemplateLiteralKind(token)) {
                        if (!scanner.isUnterminated()) {
                            return undefined;
                        }
                        switch (token) {
                            case 16 /* TemplateTail */:
                                return 5 /* InTemplateMiddleOrTail */;
                            case 13 /* NoSubstitutionTemplateLiteral */:
                                return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
                            default:
                                return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
                        }
                    }
                    return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined;
            }
        }
        function pushEncodedClassification(start, end, offset, classification, result) {
            if (classification === 8 /* whiteSpace */) {
                // Don't bother with whitespace classifications.  They're not needed.
                return;
            }
            if (start === 0 && offset > 0) {
                // We're classifying the first token, and this was a case where we prepended text.
                // We should consider the start of this token to be at the start of the original text.
                start += offset;
            }
            var length = end - start;
            if (length > 0) {
                // All our tokens are in relation to the augmented text.  Move them back to be
                // relative to the original text.
                result.push(start - offset, length, classification);
            }
        }
        function convertClassificationsToResult(classifications, text) {
            var entries = [];
            var dense = classifications.spans;
            var lastEnd = 0;
            for (var i = 0; i < dense.length; i += 3) {
                var start = dense[i];
                var length_5 = dense[i + 1];
                var type = dense[i + 2];
                // Make a whitespace entry between the last item and this one.
                if (lastEnd >= 0) {
                    var whitespaceLength_1 = start - lastEnd;
                    if (whitespaceLength_1 > 0) {
                        entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
                    }
                }
                entries.push({ length: length_5, classification: convertClassification(type) });
                lastEnd = start + length_5;
            }
            var whitespaceLength = text.length - lastEnd;
            if (whitespaceLength > 0) {
                entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace });
            }
            return { entries: entries, finalLexState: classifications.endOfLineState };
        }
        function convertClassification(type) {
            switch (type) {
                case 1 /* comment */: return ts.TokenClass.Comment;
                case 3 /* keyword */: return ts.TokenClass.Keyword;
                case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral;
                case 5 /* operator */: return ts.TokenClass.Operator;
                case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral;
                case 8 /* whiteSpace */: return ts.TokenClass.Whitespace;
                case 10 /* punctuation */: return ts.TokenClass.Punctuation;
                case 2 /* identifier */:
                case 11 /* className */:
                case 12 /* enumName */:
                case 13 /* interfaceName */:
                case 14 /* moduleName */:
                case 15 /* typeParameterName */:
                case 16 /* typeAliasName */:
                case 9 /* text */:
                case 17 /* parameterName */:
                    return ts.TokenClass.Identifier;
                default:
                    return undefined; // TODO: GH#18217 Debug.assertNever(type);
            }
        }
        /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */
        function canFollow(keyword1, keyword2) {
            if (!ts.isAccessibilityModifier(keyword1)) {
                // Assume any other keyword combination is legal.
                // This can be refined in the future if there are more cases we want the classifier to be better at.
                return true;
            }
            switch (keyword2) {
                case 125 /* GetKeyword */:
                case 136 /* SetKeyword */:
                case 123 /* ConstructorKeyword */:
                case 115 /* StaticKeyword */:
                    return true; // Allow things like "public get", "public constructor" and "public static".
                default:
                    return false; // Any other keyword following "public" is actually an identifier, not a real keyword.
            }
        }
        function getPrefixFromLexState(lexState) {
            // If we're in a string literal, then prepend: "\
            // (and a newline).  That way when we lex we'll think we're still in a string literal.
            //
            // If we're in a multiline comment, then prepend: /*
            // (and a newline).  That way when we lex we'll think we're still in a multiline comment.
            switch (lexState) {
                case 3 /* InDoubleQuoteStringLiteral */:
                    return { prefix: "\"\\\n" };
                case 2 /* InSingleQuoteStringLiteral */:
                    return { prefix: "'\\\n" };
                case 1 /* InMultiLineCommentTrivia */:
                    return { prefix: "/*\n" };
                case 4 /* InTemplateHeadOrNoSubstitutionTemplate */:
                    return { prefix: "`\n" };
                case 5 /* InTemplateMiddleOrTail */:
                    return { prefix: "}\n", pushTemplate: true };
                case 6 /* InTemplateSubstitutionPosition */:
                    return { prefix: "", pushTemplate: true };
                case 0 /* None */:
                    return { prefix: "" };
                default:
                    return ts.Debug.assertNever(lexState);
            }
        }
        function isBinaryExpressionOperatorToken(token) {
            switch (token) {
                case 39 /* AsteriskToken */:
                case 41 /* SlashToken */:
                case 42 /* PercentToken */:
                case 37 /* PlusToken */:
                case 38 /* MinusToken */:
                case 45 /* LessThanLessThanToken */:
                case 46 /* GreaterThanGreaterThanToken */:
                case 47 /* GreaterThanGreaterThanGreaterThanToken */:
                case 27 /* LessThanToken */:
                case 29 /* GreaterThanToken */:
                case 30 /* LessThanEqualsToken */:
                case 31 /* GreaterThanEqualsToken */:
                case 93 /* InstanceOfKeyword */:
                case 92 /* InKeyword */:
                case 118 /* AsKeyword */:
                case 32 /* EqualsEqualsToken */:
                case 33 /* ExclamationEqualsToken */:
                case 34 /* EqualsEqualsEqualsToken */:
                case 35 /* ExclamationEqualsEqualsToken */:
                case 48 /* AmpersandToken */:
                case 50 /* CaretToken */:
                case 49 /* BarToken */:
                case 53 /* AmpersandAmpersandToken */:
                case 54 /* BarBarToken */:
                case 69 /* BarEqualsToken */:
                case 68 /* AmpersandEqualsToken */:
                case 70 /* CaretEqualsToken */:
                case 65 /* LessThanLessThanEqualsToken */:
                case 66 /* GreaterThanGreaterThanEqualsToken */:
                case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                case 59 /* PlusEqualsToken */:
                case 60 /* MinusEqualsToken */:
                case 61 /* AsteriskEqualsToken */:
                case 63 /* SlashEqualsToken */:
                case 64 /* PercentEqualsToken */:
                case 58 /* EqualsToken */:
                case 26 /* CommaToken */:
                    return true;
                default:
                    return false;
            }
        }
        function isPrefixUnaryExpressionOperatorToken(token) {
            switch (token) {
                case 37 /* PlusToken */:
                case 38 /* MinusToken */:
                case 52 /* TildeToken */:
                case 51 /* ExclamationToken */:
                case 43 /* PlusPlusToken */:
                case 44 /* MinusMinusToken */:
                    return true;
                default:
                    return false;
            }
        }
        function classFromKind(token) {
            if (ts.isKeyword(token)) {
                return 3 /* keyword */;
            }
            else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
                return 5 /* operator */;
            }
            else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) {
                return 10 /* punctuation */;
            }
            switch (token) {
                case 8 /* NumericLiteral */:
                    return 4 /* numericLiteral */;
                case 9 /* StringLiteral */:
                    return 6 /* stringLiteral */;
                case 12 /* RegularExpressionLiteral */:
                    return 7 /* regularExpressionLiteral */;
                case 7 /* ConflictMarkerTrivia */:
                case 3 /* MultiLineCommentTrivia */:
                case 2 /* SingleLineCommentTrivia */:
                    return 1 /* comment */;
                case 5 /* WhitespaceTrivia */:
                case 4 /* NewLineTrivia */:
                    return 8 /* whiteSpace */;
                case 71 /* Identifier */:
                default:
                    if (ts.isTemplateLiteralKind(token)) {
                        return 6 /* stringLiteral */;
                    }
                    return 2 /* identifier */;
            }
        }
        /* @internal */
        function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
            return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
        }
        ts.getSemanticClassifications = getSemanticClassifications;
        function checkForClassificationCancellation(cancellationToken, kind) {
            // We don't want to actually call back into our host on every node to find out if we've
            // been canceled.  That would be an enormous amount of chattyness, along with the all
            // the overhead of marshalling the data to/from the host.  So instead we pick a few
            // reasonable node kinds to bother checking on.  These node kinds represent high level
            // constructs that we would expect to see commonly, but just at a far less frequent
            // interval.
            //
            // For example, in checker.ts (around 750k) we only have around 600 of these constructs.
            // That means we're calling back into the host around every 1.2k of the file we process.
            // Lib.d.ts has similar numbers.
            switch (kind) {
                case 242 /* ModuleDeclaration */:
                case 238 /* ClassDeclaration */:
                case 239 /* InterfaceDeclaration */:
                case 237 /* FunctionDeclaration */:
                    cancellationToken.throwIfCancellationRequested();
            }
        }
        /* @internal */
        function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
            var spans = [];
            sourceFile.forEachChild(function cb(node) {
                // Only walk into nodes that intersect the requested span.
                if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
                    return;
                }
                checkForClassificationCancellation(cancellationToken, node.kind);
                // Only bother calling into the typechecker if this is an identifier that
                // could possibly resolve to a type name.  This makes classification run
                // in a third of the time it would normally take.
                if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) {
                    var symbol = typeChecker.getSymbolAtLocation(node);
                    var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker);
                    if (type) {
                        pushClassification(node.getStart(sourceFile), node.getEnd(), type);
                    }
                }
                node.forEachChild(cb);
            });
            return { spans: spans, endOfLineState: 0 /* None */ };
            function pushClassification(start, end, type) {
                spans.push(start);
                spans.push(end - start);
                spans.push(type);
            }
        }
        ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications;
        function classifySymbol(symbol, meaningAtPosition, checker) {
            var flags = symbol.getFlags();
            if ((flags & 2885600 /* Classifiable */) === 0 /* None */) {
                return undefined;
            }
            else if (flags & 32 /* Class */) {
                return 11 /* className */;
            }
            else if (flags & 384 /* Enum */) {
                return 12 /* enumName */;
            }
            else if (flags & 524288 /* TypeAlias */) {
                return 16 /* typeAliasName */;
            }
            else if (flags & 1536 /* Module */) {
                // Only classify a module as such if
                //  - It appears in a namespace context.
                //  - There exists a module declaration which actually impacts the value side.
                return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined;
            }
            else if (flags & 2097152 /* Alias */) {
                return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker);
            }
            else if (meaningAtPosition & 2 /* Type */) {
                return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined;
            }
            else {
                return undefined;
            }
        }
        /** Returns true if there exists a module that introduces entities on the value side. */
        function hasValueSideModule(symbol) {
            return ts.some(symbol.declarations, function (declaration) {
                return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;
            });
        }
        function getClassificationTypeName(type) {
            switch (type) {
                case 1 /* comment */: return "comment" /* comment */;
                case 2 /* identifier */: return "identifier" /* identifier */;
                case 3 /* keyword */: return "keyword" /* keyword */;
                case 4 /* numericLiteral */: return "number" /* numericLiteral */;
                case 5 /* operator */: return "operator" /* operator */;
                case 6 /* stringLiteral */: return "string" /* stringLiteral */;
                case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */;
                case 9 /* text */: return "text" /* text */;
                case 10 /* punctuation */: return "punctuation" /* punctuation */;
                case 11 /* className */: return "class name" /* className */;
                case 12 /* enumName */: return "enum name" /* enumName */;
                case 13 /* interfaceName */: return "interface name" /* interfaceName */;
                case 14 /* moduleName */: return "module name" /* moduleName */;
                case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */;
                case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */;
                case 17 /* parameterName */: return "parameter name" /* parameterName */;
                case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */;
                case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */;
                case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */;
                case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */;
                case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */;
                case 23 /* jsxText */: return "jsx text" /* jsxText */;
                case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */;
                default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type);
            }
        }
        function convertClassificationsToSpans(classifications) {
            ts.Debug.assert(classifications.spans.length % 3 === 0);
            var dense = classifications.spans;
            var result = [];
            for (var i = 0; i < dense.length; i += 3) {
                result.push({
                    textSpan: ts.createTextSpan(dense[i], dense[i + 1]),
                    classificationType: getClassificationTypeName(dense[i + 2])
                });
            }
            return result;
        }
        /* @internal */
        function getSyntacticClassifications(cancellationToken, sourceFile, span) {
            return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
        }
        ts.getSyntacticClassifications = getSyntacticClassifications;
        /* @internal */
        function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
            var spanStart = span.start;
            var spanLength = span.length;
            // Make a scanner we can get trivia from.
            var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
            var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
            var result = [];
            processElement(sourceFile);
            return { spans: result, endOfLineState: 0 /* None */ };
            function pushClassification(start, length, type) {
                result.push(start);
                result.push(length);
                result.push(type);
            }
            function classifyLeadingTriviaAndGetTokenStart(token) {
                triviaScanner.setTextPos(token.pos);
                while (true) {
                    var start = triviaScanner.getTextPos();
                    // only bother scanning if we have something that could be trivia.
                    if (!ts.couldStartTrivia(sourceFile.text, start)) {
                        return start;
                    }
                    var kind = triviaScanner.scan();
                    var end = triviaScanner.getTextPos();
                    var width = end - start;
                    // The moment we get something that isn't trivia, then stop processing.
                    if (!ts.isTrivia(kind)) {
                        return start;
                    }
                    switch (kind) {
                        case 4 /* NewLineTrivia */:
                        case 5 /* WhitespaceTrivia */:
                            // Don't bother with newlines/whitespace.
                            continue;
                        case 2 /* SingleLineCommentTrivia */:
                        case 3 /* MultiLineCommentTrivia */:
                            // Only bother with the trivia if it at least intersects the span of interest.
                            classifyComment(token, kind, start, width);
                            // Classifying a comment might cause us to reuse the trivia scanner
                            // (because of jsdoc comments).  So after we classify the comment make
                            // sure we set the scanner position back to where it needs to be.
                            triviaScanner.setTextPos(end);
                            continue;
                        case 7 /* ConflictMarkerTrivia */:
                            var text = sourceFile.text;
                            var ch = text.charCodeAt(start);
                            // for the <<<<<<< and >>>>>>> markers, we just add them in as comments
                            // in the classification stream.
                            if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
                                pushClassification(start, width, 1 /* comment */);
                                continue;
                            }
                            // for the ||||||| and ======== markers, add a comment for the first line,
                            // and then lex all subsequent lines up until the end of the conflict marker.
                            ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
                            classifyDisabledMergeCode(text, start, end);
                            break;
                        case 6 /* ShebangTrivia */:
                            // TODO: Maybe we should classify these.
                            break;
                        default:
                            ts.Debug.assertNever(kind);
                    }
                }
            }
            function classifyComment(token, kind, start, width) {
                if (kind === 3 /* MultiLineCommentTrivia */) {
                    // See if this is a doc comment.  If so, we'll classify certain portions of it
                    // specially.
                    var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width);
                    if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) {
                        // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]`
                        docCommentAndDiagnostics.jsDoc.parent = token;
                        classifyJSDocComment(docCommentAndDiagnostics.jsDoc);
                        return;
                    }
                }
                // Simple comment.  Just add as is.
                pushCommentRange(start, width);
            }
            function pushCommentRange(start, width) {
                pushClassification(start, width, 1 /* comment */);
            }
            function classifyJSDocComment(docComment) {
                var pos = docComment.pos;
                if (docComment.tags) {
                    for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) {
                        var tag = _a[_i];
                        // As we walk through each tag, classify the portion of text from the end of
                        // the last tag (or the start of the entire doc comment) as 'comment'.
                        if (tag.pos !== pos) {
                            pushCommentRange(pos, tag.pos - pos);
                        }
                        pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@"
                        pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
                        pos = tag.tagName.end;
                        switch (tag.kind) {
                            case 297 /* JSDocParameterTag */:
                                processJSDocParameterTag(tag);
                                break;
                            case 301 /* JSDocTemplateTag */:
                                processJSDocTemplateTag(tag);
                                pos = tag.end;
                                break;
                            case 300 /* JSDocTypeTag */:
                                processElement(tag.typeExpression);
                                pos = tag.end;
                                break;
                            case 298 /* JSDocReturnTag */:
                                processElement(tag.typeExpression);
                                pos = tag.end;
                                break;
                        }
                    }
                }
                if (pos !== docComment.end) {
                    pushCommentRange(pos, docComment.end - pos);
                }
                return;
                function processJSDocParameterTag(tag) {
                    if (tag.isNameFirst) {
                        pushCommentRange(pos, tag.name.pos - pos);
                        pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
                        pos = tag.name.end;
                    }
                    if (tag.typeExpression) {
                        pushCommentRange(pos, tag.typeExpression.pos - pos);
                        processElement(tag.typeExpression);
                        pos = tag.typeExpression.end;
                    }
                    if (!tag.isNameFirst) {
                        pushCommentRange(pos, tag.name.pos - pos);
                        pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
                        pos = tag.name.end;
                    }
                }
            }
            function processJSDocTemplateTag(tag) {
                for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) {
                    var child = _a[_i];
                    processElement(child);
                }
            }
            function classifyDisabledMergeCode(text, start, end) {
                // Classify the line that the ||||||| or ======= marker is on as a comment.
                // Then just lex all further tokens and add them to the result.
                var i;
                for (i = start; i < end; i++) {
                    if (ts.isLineBreak(text.charCodeAt(i))) {
                        break;
                    }
                }
                pushClassification(start, i - start, 1 /* comment */);
                mergeConflictScanner.setTextPos(i);
                while (mergeConflictScanner.getTextPos() < end) {
                    classifyDisabledCodeToken();
                }
            }
            function classifyDisabledCodeToken() {
                var start = mergeConflictScanner.getTextPos();
                var tokenKind = mergeConflictScanner.scan();
                var end = mergeConflictScanner.getTextPos();
                var type = classifyTokenType(tokenKind);
                if (type) {
                    pushClassification(start, end - start, type);
                }
            }
            /**
             * Returns true if node should be treated as classified and no further processing is required.
             * False will mean that node is not classified and traverse routine should recurse into node contents.
             */
            function tryClassifyNode(node) {
                if (ts.isJSDoc(node)) {
                    return true;
                }
                if (ts.nodeIsMissing(node)) {
                    return true;
                }
                var classifiedElementName = tryClassifyJsxElementName(node);
                if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) {
                    return false;
                }
                var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
                var tokenWidth = node.end - tokenStart;
                ts.Debug.assert(tokenWidth >= 0);
                if (tokenWidth > 0) {
                    var type = classifiedElementName || classifyTokenType(node.kind, node);
                    if (type) {
                        pushClassification(tokenStart, tokenWidth, type);
                    }
                }
                return true;
            }
            function tryClassifyJsxElementName(token) {
                switch (token.parent && token.parent.kind) {
                    case 260 /* JsxOpeningElement */:
                        if (token.parent.tagName === token) {
                            return 19 /* jsxOpenTagName */;
                        }
                        break;
                    case 261 /* JsxClosingElement */:
                        if (token.parent.tagName === token) {
                            return 20 /* jsxCloseTagName */;
                        }
                        break;
                    case 259 /* JsxSelfClosingElement */:
                        if (token.parent.tagName === token) {
                            return 21 /* jsxSelfClosingTagName */;
                        }
                        break;
                    case 265 /* JsxAttribute */:
                        if (token.parent.name === token) {
                            return 22 /* jsxAttribute */;
                        }
                        break;
                }
                return undefined;
            }
            // for accurate classification, the actual token should be passed in.  however, for
            // cases like 'disabled merge code' classification, we just get the token kind and
            // classify based on that instead.
            function classifyTokenType(tokenKind, token) {
                if (ts.isKeyword(tokenKind)) {
                    return 3 /* keyword */;
                }
                // Special case `<` and `>`: If they appear in a generic context they are punctuation,
                // not operators.
                if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) {
                    // If the node owning the token has a type argument list or type parameter list, then
                    // we can effectively assume that a '<' and '>' belong to those lists.
                    if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) {
                        return 10 /* punctuation */;
                    }
                }
                if (ts.isPunctuation(tokenKind)) {
                    if (token) {
                        var parent = token.parent;
                        if (tokenKind === 58 /* EqualsToken */) {
                            // the '=' in a variable declaration is special cased here.
                            if (parent.kind === 235 /* VariableDeclaration */ ||
                                parent.kind === 152 /* PropertyDeclaration */ ||
                                parent.kind === 149 /* Parameter */ ||
                                parent.kind === 265 /* JsxAttribute */) {
                                return 5 /* operator */;
                            }
                        }
                        if (parent.kind === 202 /* BinaryExpression */ ||
                            parent.kind === 200 /* PrefixUnaryExpression */ ||
                            parent.kind === 201 /* PostfixUnaryExpression */ ||
                            parent.kind === 203 /* ConditionalExpression */) {
                            return 5 /* operator */;
                        }
                    }
                    return 10 /* punctuation */;
                }
                else if (tokenKind === 8 /* NumericLiteral */) {
                    return 4 /* numericLiteral */;
                }
                else if (tokenKind === 9 /* StringLiteral */) {
                    // TODO: GH#18217
                    return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
                }
                else if (tokenKind === 12 /* RegularExpressionLiteral */) {
                    // TODO: we should get another classification type for these literals.
                    return 6 /* stringLiteral */;
                }
                else if (ts.isTemplateLiteralKind(tokenKind)) {
                    // TODO (drosen): we should *also* get another classification type for these literals.
                    return 6 /* stringLiteral */;
                }
                else if (tokenKind === 10 /* JsxText */) {
                    return 23 /* jsxText */;
                }
                else if (tokenKind === 71 /* Identifier */) {
                    if (token) {
                        switch (token.parent.kind) {
                            case 238 /* ClassDeclaration */:
                                if (token.parent.name === token) {
                                    return 11 /* className */;
                                }
                                return;
                            case 148 /* TypeParameter */:
                                if (token.parent.name === token) {
                                    return 15 /* typeParameterName */;
                                }
                                return;
                            case 239 /* InterfaceDeclaration */:
                                if (token.parent.name === token) {
                                    return 13 /* interfaceName */;
                                }
                                return;
                            case 241 /* EnumDeclaration */:
                                if (token.parent.name === token) {
                                    return 12 /* enumName */;
                                }
                                return;
                            case 242 /* ModuleDeclaration */:
                                if (token.parent.name === token) {
                                    return 14 /* moduleName */;
                                }
                                return;
                            case 149 /* Parameter */:
                                if (token.parent.name === token) {
                                    return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */;
                                }
                                return;
                        }
                    }
                    return 2 /* identifier */;
                }
            }
            function processElement(element) {
                if (!element) {
                    return;
                }
                // Ignore nodes that don't intersect the original span to classify.
                if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
                    checkForClassificationCancellation(cancellationToken, element.kind);
                    for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) {
                        var child = _a[_i];
                        if (!tryClassifyNode(child)) {
                            // Recurse into our child nodes.
                            processElement(child);
                        }
                    }
                }
            }
        }
        ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var Completions;
        (function (Completions) {
            var PathCompletions;
            (function (PathCompletions) {
                function nameAndKind(name, kind) {
                    return { name: name, kind: kind };
                }
                function addReplacementSpans(text, textStart, names) {
                    var span = getDirectoryFragmentTextSpan(text, textStart);
                    return names.map(function (_a) {
                        var name = _a.name, kind = _a.kind;
                        return ({ name: name, kind: kind, span: span });
                    });
                }
                function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) {
                    return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker));
                }
                PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames;
                function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) {
                    var literalValue = ts.normalizeSlashes(node.text);
                    var scriptPath = sourceFile.path;
                    var scriptDirectory = ts.getDirectoryPath(scriptPath);
                    if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) {
                        var extensions = getSupportedExtensionsForModuleResolution(compilerOptions);
                        if (compilerOptions.rootDirs) {
                            return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath);
                        }
                        else {
                            return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath);
                        }
                    }
                    else {
                        return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
                    }
                }
                function getSupportedExtensionsForModuleResolution(compilerOptions) {
                    var extensions = ts.getSupportedExtensions(compilerOptions);
                    return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
                        extensions.concat(".json" /* Json */) :
                        extensions;
                }
                /**
                 * Takes a script path and returns paths for all potential folders that could be merged with its
                 * containing folder via the "rootDirs" compiler option
                 */
                function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) {
                    // Make all paths absolute/normalized if they are not already
                    rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
                    // Determine the path to the directory containing the script relative to the root directory it is contained within
                    var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
                        return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined;
                    }); // TODO: GH#18217
                    // Now find a path for each potential directory that is to be merged with the one containing the script
                    return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
                }
                function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) {
                    var basePath = compilerOptions.project || host.getCurrentDirectory();
                    var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
                    var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase);
                    var result = [];
                    for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) {
                        var baseDirectory = baseDirectories_1[_i];
                        getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result);
                    }
                    return result;
                }
                /**
                 * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
                 */
                function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) {
                    if (result === void 0) {
                        result = [];
                    }
                    if (fragment === undefined) {
                        fragment = "";
                    }
                    fragment = ts.normalizeSlashes(fragment);
                    /**
                     * Remove the basename from the path. Note that we don't use the basename to filter completions;
                     * the client is responsible for refining completions.
                     */
                    if (!ts.hasTrailingDirectorySeparator(fragment)) {
                        fragment = ts.getDirectoryPath(fragment);
                    }
                    if (fragment === "") {
                        fragment = "." + ts.directorySeparator;
                    }
                    fragment = ts.ensureTrailingDirectorySeparator(fragment);
                    // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
                    var absolutePath = ts.resolvePath(scriptPath, fragment);
                    var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
                    var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
                    if (tryDirectoryExists(host, baseDirectory)) {
                        // Enumerate the available files if possible
                        var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]);
                        if (files) {
                            /**
                             * Multiple file entries might map to the same truncated name once we remove extensions
                             * (happens iff includeExtensions === false)so we use a set-like data structure. Eg:
                             *
                             * both foo.ts and foo.tsx become foo
                             */
                            var foundFiles = ts.createMap();
                            for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
                                var filePath = files_3[_i];
                                filePath = ts.normalizePath(filePath);
                                if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
                                    continue;
                                }
                                var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
                                if (!foundFiles.has(foundFileName)) {
                                    foundFiles.set(foundFileName, true);
                                }
                            }
                            ts.forEachKey(foundFiles, function (foundFile) {
                                result.push(nameAndKind(foundFile, "script" /* scriptElement */));
                            });
                        }
                        // If possible, get folder completion as well
                        var directories = tryGetDirectories(host, baseDirectory);
                        if (directories) {
                            for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) {
                                var directory = directories_1[_a];
                                var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
                                if (directoryName !== "@types") {
                                    result.push(nameAndKind(directoryName, "directory" /* directory */));
                                }
                            }
                        }
                        // check for a version redirect
                        var packageJsonPath = findPackageJson(baseDirectory, host);
                        if (packageJsonPath) {
                            var packageJson = ts.readJson(packageJsonPath, host);
                            var typesVersions = packageJson.typesVersions;
                            if (typeof typesVersions === "object") {
                                var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions);
                                var versionPaths = versionResult && versionResult.paths;
                                var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length);
                                if (versionPaths) {
                                    addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host);
                                }
                            }
                        }
                    }
                    return result;
                }
                function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) {
                    for (var path in paths) {
                        if (!ts.hasProperty(paths, path))
                            continue;
                        var patterns = paths[path];
                        if (patterns) {
                            var _loop_9 = function (name, kind) {
                                // Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
                                if (!result.some(function (entry) { return entry.name === name; })) {
                                    result.push(nameAndKind(name, kind));
                                }
                            };
                            for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
                                var _b = _a[_i], name = _b.name, kind = _b.kind;
                                _loop_9(name, kind);
                            }
                        }
                    }
                }
                /**
                 * Check all of the declared modules and those in node modules. Possible sources of modules:
                 *      Modules that are found by the type checker
                 *      Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option)
                 *      Modules from node_modules (i.e. those listed in package.json)
                 *          This includes all files that are found in node_modules/moduleName/ with acceptable file extensions
                 */
                function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
                    var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
                    var result = [];
                    var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions);
                    if (baseUrl) {
                        var projectDir = compilerOptions.project || host.getCurrentDirectory();
                        var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl));
                        getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result);
                        if (paths) {
                            addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host);
                        }
                    }
                    var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
                    for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) {
                        var ambientName = _a[_i];
                        result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */));
                    }
                    getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result);
                    if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) {
                        // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies.
                        // (But do if we didn't find anything, e.g. 'package.json' missing.)
                        var foundGlobal = false;
                        if (fragmentDirectory === undefined) {
                            var _loop_10 = function (moduleName) {
                                if (!result.some(function (entry) { return entry.name === moduleName; })) {
                                    foundGlobal = true;
                                    result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */));
                                }
                            };
                            for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
                                var moduleName = _c[_b];
                                _loop_10(moduleName);
                            }
                        }
                        if (!foundGlobal) {
                            ts.forEachAncestorDirectory(scriptPath, function (ancestor) {
                                var nodeModules = ts.combinePaths(ancestor, "node_modules");
                                if (tryDirectoryExists(host, nodeModules)) {
                                    getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result);
                                }
                            });
                        }
                    }
                    return result;
                }
                function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) {
                    if (!ts.endsWith(path, "*")) {
                        // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion.
                        return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray;
                    }
                    var pathPrefix = path.slice(0, path.length - 1);
                    var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix);
                    return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) {
                        return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host);
                    });
                    function justPathMappingName(name) {
                        return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray;
                    }
                }
                function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) {
                    if (!host.readDirectory) {
                        return undefined;
                    }
                    var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined;
                    if (!parsed) {
                        return undefined;
                    }
                    // The prefix has two effective parts: the directory path and the base component after the filepath that is not a
                    // full directory component. For example: directory/path/of/prefix/base*
                    var normalizedPrefix = ts.resolvePath(parsed.prefix);
                    var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
                    var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
                    var fragmentHasPath = containsSlash(fragment);
                    var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
                    // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
                    var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
                    var normalizedSuffix = ts.normalizePath(parsed.suffix);
                    // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
                    var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
                    var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase;
                    // If we have a suffix, then we need to read the directory all the way down. We could create a glob
                    // that encodes the suffix, but we would have to escape the character "?" which readDirectory
                    // doesn't support. For now, this is safer but slower
                    var includeGlob = normalizedSuffix ? "**/*" : "./*";
                    var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); });
                    var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); });
                    // Trim away prefix and suffix
                    return ts.mapDefined(ts.concatenate(matches, directories), function (_a) {
                        var name = _a.name, kind = _a.kind;
                        var normalizedMatch = ts.normalizePath(name);
                        var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix);
                        return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined;
                    });
                }
                function withoutStartAndEnd(s, start, end) {
                    return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined;
                }
                function removeLeadingDirectorySeparator(path) {
                    return path[0] === ts.directorySeparator ? path.slice(1) : path;
                }
                function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) {
                    // Get modules that the type checker picked up
                    var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); });
                    var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); });
                    // Nested modules of the form "module-name/sub" need to be adjusted to only return the string
                    // after the last '/' that appears in the fragment because that's where the replacement span
                    // starts
                    if (fragmentDirectory !== undefined) {
                        var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory);
                        return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); });
                    }
                    return nonRelativeModuleNames;
                }
                function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) {
                    var token = ts.getTokenAtPosition(sourceFile, position);
                    var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
                    var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; });
                    if (!range) {
                        return undefined;
                    }
                    var text = sourceFile.text.slice(range.pos, position);
                    var match = tripleSlashDirectiveFragmentRegex.exec(text);
                    if (!match) {
                        return undefined;
                    }
                    var prefix = match[1], kind = match[2], toComplete = match[3];
                    var scriptPath = ts.getDirectoryPath(sourceFile.path);
                    var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path)
                        : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath)
                            : undefined;
                    return names && addReplacementSpans(toComplete, range.pos + prefix.length, names);
                }
                PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion;
                function getCompletionEntriesFromTypings(host, options, scriptPath, result) {
                    if (result === void 0) {
                        result = [];
                    }
                    // Check for typings specified in compiler options
                    var seen = ts.createMap();
                    if (options.types) {
                        for (var _i = 0, _a = options.types; _i < _a.length; _i++) {
                            var typesName = _a[_i];
                            var moduleName = ts.unmangleScopedPackageName(typesName);
                            pushResult(moduleName);
                        }
                    }
                    else if (host.getDirectories) {
                        var typeRoots = void 0;
                        try {
                            typeRoots = ts.getEffectiveTypeRoots(options, host);
                        }
                        catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ }
                        if (typeRoots) {
                            for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) {
                                var root = typeRoots_2[_c];
                                getCompletionEntriesFromDirectories(root);
                            }
                        }
                        // Also get all @types typings installed in visible node_modules directories
                        for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) {
                            var packageJson = _e[_d];
                            var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types");
                            getCompletionEntriesFromDirectories(typesDir);
                        }
                    }
                    return result;
                    function getCompletionEntriesFromDirectories(directory) {
                        ts.Debug.assert(!!host.getDirectories);
                        if (tryDirectoryExists(host, directory)) {
                            var directories = tryGetDirectories(host, directory);
                            if (directories) {
                                for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) {
                                    var typeDirectory = directories_2[_i];
                                    typeDirectory = ts.normalizePath(typeDirectory);
                                    var directoryName = ts.getBaseFileName(typeDirectory);
                                    var moduleName = ts.unmangleScopedPackageName(directoryName);
                                    pushResult(moduleName);
                                }
                            }
                        }
                    }
                    function pushResult(moduleName) {
                        if (!seen.has(moduleName)) {
                            result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */));
                            seen.set(moduleName, true);
                        }
                    }
                }
                function findPackageJsons(directory, host) {
                    var paths = [];
                    ts.forEachAncestorDirectory(directory, function (ancestor) {
                        var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json");
                        if (!currentConfigPath) {
                            return true; // break out
                        }
                        paths.push(currentConfigPath);
                    });
                    return paths;
                }
                function findPackageJson(directory, host) {
                    var packageJson;
                    ts.forEachAncestorDirectory(directory, function (ancestor) {
                        if (ancestor === "node_modules")
                            return true;
                        packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json");
                        if (packageJson) {
                            return true; // break out
                        }
                    });
                    return packageJson;
                }
                function enumerateNodeModulesVisibleToScript(host, scriptPath) {
                    if (!host.readFile || !host.fileExists)
                        return ts.emptyArray;
                    var result = [];
                    for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) {
                        var packageJson = _a[_i];
                        var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined
                        // Provide completions for all non @types dependencies
                        for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) {
                            var key = nodeModulesDependencyKeys_1[_b];
                            var dependencies = contents[key];
                            if (!dependencies)
                                continue;
                            for (var dep in dependencies) {
                                if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) {
                                    result.push(dep);
                                }
                            }
                        }
                    }
                    return result;
                }
                // Replace everything after the last directory separator that appears
                function getDirectoryFragmentTextSpan(text, textStart) {
                    var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\"));
                    var offset = index !== -1 ? index + 1 : 0;
                    // If the range is an identifier, span is unnecessary.
                    var length = text.length - offset;
                    return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
                }
                // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
                function isPathRelativeToScript(path) {
                    if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) {
                        var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1;
                        var slashCharCode = path.charCodeAt(slashIndex);
                        return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */;
                    }
                    return false;
                }
                /**
                 * Matches a triple slash reference directive with an incomplete string literal for its path. Used
                 * to determine if the caret is currently within the string literal and capture the literal fragment
                 * for completions.
                 * For example, this matches
                 *
                 * /// <reference path="fragment
                 *
                 * but not
                 *
                 * /// <reference path="fragment"
                 */
                var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
                var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
                function tryGetDirectories(host, directoryName) {
                    return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || [];
                }
                function tryReadDirectory(host, path, extensions, exclude, include) {
                    return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || ts.emptyArray;
                }
                function tryFileExists(host, path) {
                    return tryIOAndConsumeErrors(host, host.fileExists, path);
                }
                function tryDirectoryExists(host, path) {
                    try {
                        return ts.directoryProbablyExists(path, host);
                    }
                    catch ( /*ignore*/_a) { /*ignore*/ }
                    return false;
                }
                function tryIOAndConsumeErrors(host, toApply) {
                    var args = [];
                    for (var _i = 2; _i < arguments.length; _i++) {
                        args[_i - 2] = arguments[_i];
                    }
                    try {
                        return toApply && toApply.apply(host, args);
                    }
                    catch ( /*ignore*/_a) { /*ignore*/ }
                    return undefined;
                }
                function containsSlash(fragment) {
                    return ts.stringContains(fragment, ts.directorySeparator);
                }
            })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {}));
        })(Completions = ts.Completions || (ts.Completions = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var Completions;
        (function (Completions) {
            var SymbolOriginInfoKind;
            (function (SymbolOriginInfoKind) {
                SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 0] = "ThisType";
                SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 1] = "SymbolMemberNoExport";
                SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 2] = "SymbolMemberExport";
                SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 3] = "Export";
            })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {}));
            function originIsSymbolMember(origin) {
                return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 1 /* SymbolMemberNoExport */;
            }
            function originIsExport(origin) {
                return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 3 /* Export */;
            }
            var KeywordCompletionFilters;
            (function (KeywordCompletionFilters) {
                KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None";
                KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All";
                KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords";
                KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords";
                KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
                KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
                KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords";
            })(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
            var GlobalsSearch;
            (function (GlobalsSearch) {
                GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue";
                GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success";
                GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail";
            })(GlobalsSearch || (GlobalsSearch = {}));
            function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) {
                var typeChecker = program.getTypeChecker();
                var compilerOptions = program.getCompilerOptions();
                if (ts.isInReferenceComment(sourceFile, position)) {
                    var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host);
                    return entries && convertPathCompletions(entries);
                }
                var contextToken = ts.findPrecedingToken(position, sourceFile);
                if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)))
                    return undefined;
                if (ts.isInString(sourceFile, position, contextToken)) {
                    return !contextToken || !ts.isStringLiteralLike(contextToken)
                        ? undefined
                        : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences);
                }
                if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent)
                    && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) {
                    return getLabelCompletionAtPosition(contextToken.parent);
                }
                var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined);
                if (!completionData) {
                    return undefined;
                }
                switch (completionData.kind) {
                    case 0 /* Data */:
                        return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences);
                    case 1 /* JsDocTagName */:
                        // If the current position is a jsDoc tag name, only tag names should be provided for completion
                        return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions());
                    case 2 /* JsDocTag */:
                        // If the current position is a jsDoc tag, only tags should be provided for completion
                        return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions());
                    case 3 /* JsDocParameterName */:
                        return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
                    default:
                        return ts.Debug.assertNever(completionData);
                }
            }
            Completions.getCompletionsAtPosition = getCompletionsAtPosition;
            function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) {
                if (completion === undefined) {
                    return undefined;
                }
                switch (completion.kind) {
                    case 0 /* Paths */:
                        return convertPathCompletions(completion.paths);
                    case 1 /* Properties */: {
                        var entries = [];
                        getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
                        return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
                    }
                    case 2 /* Types */: {
                        var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); });
                        return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
                    }
                    default:
                        return ts.Debug.assertNever(completion);
                }
            }
            function convertPathCompletions(pathCompletions) {
                var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment.
                var isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of.
                var entries = pathCompletions.map(function (_a) {
                    var name = _a.name, kind = _a.kind, span = _a.span;
                    return ({ name: name, kind: kind, kindModifiers: "" /* none */, sortText: "0", replacementSpan: span });
                });
                return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
            }
            function jsdocCompletionInfo(entries) {
                return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
            }
            function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) {
                var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer;
                if (location && location.parent && ts.isJsxClosingElement(location.parent)) {
                    // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
                    // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element.
                    // For example:
                    //     var x = <div> </ /*1*/
                    // The completion list at "1" will contain "div>" with type any
                    // And at `<div> </ /*1*/ >` (with a closing `>`), the completion list will contain "div".
                    var tagName = location.parent.parent.openingElement.tagName;
                    var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile);
                    var entry = {
                        name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"),
                        kind: "class" /* classElement */,
                        kindModifiers: undefined,
                        sortText: "0",
                    };
                    return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] };
                }
                var entries = [];
                if (isUncheckedFile(sourceFile, compilerOptions)) {
                    var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap);
                    getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217
                }
                else {
                    if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) {
                        return undefined;
                    }
                    getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap);
                }
                if (keywordFilters !== 0 /* None */) {
                    var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
                    for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) {
                        var keywordEntry = _a[_i];
                        if (!entryNames.has(keywordEntry.name)) {
                            entries.push(keywordEntry);
                        }
                    }
                }
                for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) {
                    var literal = literals_1[_b];
                    entries.push(createCompletionEntryForLiteral(literal));
                }
                return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
            }
            function isUncheckedFile(sourceFile, compilerOptions) {
                return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions);
            }
            function isMemberCompletionKind(kind) {
                switch (kind) {
                    case 0 /* ObjectPropertyDeclaration */:
                    case 3 /* MemberLike */:
                    case 2 /* PropertyAccess */:
                        return true;
                    default:
                        return false;
                }
            }
            function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) {
                ts.getNameTable(sourceFile).forEach(function (pos, name) {
                    // Skip identifiers produced only from the current location
                    if (pos === position) {
                        return;
                    }
                    var realName = ts.unescapeLeadingUnderscores(name);
                    if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) {
                        entries.push({
                            name: realName,
                            kind: "warning" /* warning */,
                            kindModifiers: "",
                            sortText: "1"
                        });
                    }
                });
            }
            var completionNameForLiteral = JSON.stringify;
            function createCompletionEntryForLiteral(literal) {
                return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" };
            }
            function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) {
                var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind);
                if (!info) {
                    return undefined;
                }
                var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess;
                var insertText;
                var replacementSpan;
                if (origin && origin.kind === 0 /* ThisType */) {
                    insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name;
                }
                // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790.
                // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro.
                else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) {
                    insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]";
                    var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile);
                    // If the text after the '.' starts with this name, write over it. Else, add new text.
                    var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end;
                    replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end);
                }
                if (isJsxInitializer) {
                    if (insertText === undefined)
                        insertText = name;
                    insertText = "{" + insertText + "}";
                    if (typeof isJsxInitializer !== "boolean") {
                        replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile);
                    }
                }
                if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) {
                    return undefined;
                }
                // TODO(drosen): Right now we just permit *all* semantic meanings when calling
                // 'getSymbolKind' which is permissible given that it is backwards compatible; but
                // really we should consider passing the meaning for the node so that we don't report
                // that a suggestion for a value is an interface.  We COULD also just do what
                // 'getSymbolModifiers' does, which is to use the first declaration.
                // Use a 'sortText' of 0' so that all symbol completion entries come before any other
                // entries (like JavaScript identifier entries).
                return {
                    name: name,
                    kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location),
                    kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
                    sortText: "0",
                    source: getSourceFromOrigin(origin),
                    hasAction: trueOrUndefined(!!origin && originIsExport(origin)),
                    isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)),
                    insertText: insertText,
                    replacementSpan: replacementSpan,
                };
            }
            function quote(text, preferences) {
                if (/^\d+$/.test(text)) {
                    return text;
                }
                var quoted = JSON.stringify(text);
                switch (preferences.quotePreference) {
                    case undefined:
                    case "double":
                        return quoted;
                    case "single":
                        return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'";
                    default:
                        return ts.Debug.assertNever(preferences.quotePreference);
                }
            }
            function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) {
                return localSymbol === recommendedCompletion ||
                    !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion;
            }
            function trueOrUndefined(b) {
                return b ? true : undefined;
            }
            function getSourceFromOrigin(origin) {
                return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined;
            }
            function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) {
                var start = ts.timestamp();
                // Tracks unique names.
                // We don't set this for global variables or completions from external module exports, because we can have multiple of those.
                // Based on the order we add things we will always see locals first, then globals, then module exports.
                // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name.
                var uniques = ts.createMap();
                for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
                    var symbol = symbols_3[_i];
                    var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined;
                    var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
                    if (!entry) {
                        continue;
                    }
                    var name = entry.name;
                    if (uniques.has(name)) {
                        continue;
                    }
                    // Latter case tests whether this is a global variable.
                    if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217
                        uniques.set(name, true);
                    }
                    entries.push(entry);
                }
                log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start));
                return uniques;
            }
            function getLabelCompletionAtPosition(node) {
                var entries = getLabelStatementCompletions(node);
                if (entries.length) {
                    return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
                }
            }
            function getLabelStatementCompletions(node) {
                var entries = [];
                var uniques = ts.createMap();
                var current = node;
                while (current) {
                    if (ts.isFunctionLike(current)) {
                        break;
                    }
                    if (ts.isLabeledStatement(current)) {
                        var name = current.label.text;
                        if (!uniques.has(name)) {
                            uniques.set(name, true);
                            entries.push({
                                name: name,
                                kindModifiers: "" /* none */,
                                kind: "label" /* label */,
                                sortText: "0"
                            });
                        }
                    }
                    current = current.parent;
                }
                return entries;
            }
            var StringLiteralCompletionKind;
            (function (StringLiteralCompletionKind) {
                StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths";
                StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties";
                StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types";
            })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {}));
            function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) {
                var parent = node.parent;
                switch (parent.kind) {
                    case 180 /* LiteralType */:
                        switch (parent.parent.kind) {
                            case 162 /* TypeReference */:
                                return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false };
                            case 178 /* IndexedAccessType */:
                                // Get all apparent property names
                                // i.e. interface Foo {
                                //          foo: string;
                                //          bar: string;
                                //      }
                                //      let x: Foo["/*completion position*/"]
                                return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType));
                            case 181 /* ImportType */:
                                return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
                            case 171 /* UnionType */: {
                                if (!ts.isTypeReferenceNode(parent.parent.parent))
                                    return undefined;
                                var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent);
                                var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); });
                                return { kind: 2 /* Types */, types: types, isNewIdentifier: false };
                            }
                            default:
                                return undefined;
                        }
                    case 273 /* PropertyAssignment */:
                        if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) {
                            // Get quoted name of properties of the object literal expression
                            // i.e. interface ConfigFiles {
                            //          'jspm:dev': string
                            //      }
                            //      let files: ConfigFiles = {
                            //          '/*completion position*/'
                            //      }
                            //
                            //      function foo(c: ConfigFiles) {}
                            //      foo({
                            //          '/*completion position*/'
                            //      });
                            return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent));
                        }
                        return fromContextualType();
                    case 188 /* ElementAccessExpression */: {
                        var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression;
                        if (node === argumentExpression) {
                            // Get all names of properties on the expression
                            // i.e. interface A {
                            //      'prop1': string
                            // }
                            // let a: A;
                            // a['/*completion position*/']
                            return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
                        }
                        return undefined;
                    }
                    case 189 /* CallExpression */:
                    case 190 /* NewExpression */:
                        if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) {
                            var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile);
                            // Get string literal completions from specialized signatures of the target
                            // i.e. declare function f(a: 'A');
                            // f("/*completion position*/")
                            return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType();
                        }
                    // falls through (is `require("")` or `import("")`)
                    case 247 /* ImportDeclaration */:
                    case 253 /* ExportDeclaration */:
                    case 257 /* ExternalModuleReference */:
                        // Get all known external module names or complete a path to a module
                        // i.e. import * as ns from "/*completion position*/";
                        //      var y = import("/*completion position*/");
                        //      import x = require("/*completion position*/");
                        //      var y = require("/*completion position*/");
                        //      export * from "/*completion position*/";
                        return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
                    default:
                        return fromContextualType();
                }
                function fromContextualType() {
                    // Get completion for string literal from string literal type
                    // i.e. var x: "hi" | "hello" = "/*completion position*/"
                    return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false };
                }
            }
            function getAlreadyUsedTypesInStringLiteralUnion(union, current) {
                return ts.mapDefined(union.types, function (type) {
                    return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined;
                });
            }
            function getStringLiteralCompletionsFromSignature(argumentInfo, checker) {
                var isNewIdentifier = false;
                var uniques = ts.createMap();
                var candidates = [];
                checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount);
                var types = ts.flatMap(candidates, function (candidate) {
                    if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length)
                        return;
                    var type = checker.getParameterType(candidate, argumentInfo.argumentIndex);
                    isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */);
                    return getStringLiteralTypes(type, uniques);
                });
                return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier };
            }
            function stringLiteralCompletionsFromProperties(type) {
                return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) };
            }
            function getStringLiteralTypes(type, uniques) {
                if (uniques === void 0) {
                    uniques = ts.createMap();
                }
                if (!type)
                    return ts.emptyArray;
                type = ts.skipConstraint(type);
                return type.isUnion()
                    ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); })
                    : type.isStringLiteral() && !(type.flags & 512 /* EnumLiteral */) && ts.addToSeen(uniques, type.value)
                        ? [type]
                        : ts.emptyArray;
            }
            function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) {
                var compilerOptions = program.getCompilerOptions();
                var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId);
                if (!completionData) {
                    return { type: "none" };
                }
                if (completionData.kind !== 0 /* Data */) {
                    return { type: "request", request: completionData };
                }
                var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer;
                var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; });
                if (literal !== undefined)
                    return { type: "literal", literal: literal };
                // Find the symbol with the matching entry name.
                // We don't need to perform character checks here because we're only comparing the
                // name against 'entryName' (which is known to be good), not building a new
                // completion entry.
                return ts.firstDefined(symbols, function (symbol) {
                    var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
                    var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind);
                    return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source
                        ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer }
                        : undefined;
                }) || { type: "none" };
            }
            function getSymbolName(symbol, origin, target) {
                return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */
                    // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase.
                    ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; })
                        || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target)
                    : symbol.name;
            }
            function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) {
                var typeChecker = program.getTypeChecker();
                var compilerOptions = program.getCompilerOptions();
                var name = entryId.name;
                var contextToken = ts.findPrecedingToken(position, sourceFile);
                if (ts.isInString(sourceFile, position, contextToken)) {
                    var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken)
                        ? undefined
                        : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host);
                    return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217
                }
                // Compute all the completion symbols again.
                var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId);
                switch (symbolCompletion.type) {
                    case "request": {
                        var request = symbolCompletion.request;
                        switch (request.kind) {
                            case 1 /* JsDocTagName */:
                                return ts.JsDoc.getJSDocTagNameCompletionDetails(name);
                            case 2 /* JsDocTag */:
                                return ts.JsDoc.getJSDocTagCompletionDetails(name);
                            case 3 /* JsDocParameterName */:
                                return ts.JsDoc.getJSDocParameterNameCompletionDetails(name);
                            default:
                                return ts.Debug.assertNever(request);
                        }
                    }
                    case "symbol": {
                        var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken;
                        var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay;
                        return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
                    }
                    case "literal": {
                        var literal = symbolCompletion.literal;
                        return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral);
                    }
                    case "none":
                        // Didn't find a symbol with this name.  See if we can find a keyword instead.
                        return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined;
                    default:
                        ts.Debug.assertNever(symbolCompletion);
                }
            }
            Completions.getCompletionEntryDetails = getCompletionEntryDetails;
            function createSimpleDetails(name, kind, kind2) {
                return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]);
            }
            function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) {
                var _a = checker.runWithCancellationToken(cancellationToken, function (checker) {
                    return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */);
                }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags;
                return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
            }
            function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) {
                switch (completion.kind) {
                    case 0 /* Paths */: {
                        var match = ts.find(completion.paths, function (p) { return p.name === name; });
                        return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]);
                    }
                    case 1 /* Properties */: {
                        var match = ts.find(completion.symbols, function (s) { return s.name === name; });
                        return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken);
                    }
                    case 2 /* Types */:
                        return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined;
                    default:
                        return ts.Debug.assertNever(completion);
                }
            }
            function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
                return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source };
            }
            function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) {
                var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
                if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) {
                    return { codeActions: undefined, sourceDisplay: undefined };
                }
                var moduleSymbol = symbolOriginInfo.moduleSymbol;
                var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker));
                var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction;
                return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] };
            }
            function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) {
                var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId);
                return completion.type === "symbol" ? completion.symbol : undefined;
            }
            Completions.getCompletionEntrySymbol = getCompletionEntrySymbol;
            var CompletionDataKind;
            (function (CompletionDataKind) {
                CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data";
                CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName";
                CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag";
                CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName";
            })(CompletionDataKind || (CompletionDataKind = {}));
            var CompletionKind;
            (function (CompletionKind) {
                CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
                CompletionKind[CompletionKind["Global"] = 1] = "Global";
                CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess";
                CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike";
                CompletionKind[CompletionKind["String"] = 4] = "String";
                CompletionKind[CompletionKind["None"] = 5] = "None";
            })(CompletionKind || (CompletionKind = {}));
            function getRecommendedCompletion(previousToken, contextualType, checker) {
                // For a union, return the first one with a recommended completion.
                return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) {
                    var symbol = type && type.symbol;
                    // Don't include make a recommended completion for an abstract class
                    return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol))
                        ? getFirstSymbolInChain(symbol, previousToken, checker)
                        : undefined;
                });
            }
            function getContextualType(previousToken, position, sourceFile, checker) {
                var parent = previousToken.parent;
                switch (previousToken.kind) {
                    case 71 /* Identifier */:
                        return getContextualTypeFromParent(previousToken, checker);
                    case 58 /* EqualsToken */:
                        switch (parent.kind) {
                            case 235 /* VariableDeclaration */:
                                return checker.getContextualType(parent.initializer); // TODO: GH#18217
                            case 202 /* BinaryExpression */:
                                return checker.getTypeAtLocation(parent.left);
                            case 265 /* JsxAttribute */:
                                return checker.getContextualTypeForJsxAttribute(parent);
                            default:
                                return undefined;
                        }
                    case 94 /* NewKeyword */:
                        return checker.getContextualType(parent);
                    case 73 /* CaseKeyword */:
                        return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker);
                    case 17 /* OpenBraceToken */:
                        return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined;
                    default:
                        var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile);
                        return argInfo
                            // At `,`, treat this as the next argument after the comma.
                            ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 26 /* CommaToken */ ? 1 : 0))
                            : isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind)
                                // completion at `x ===/**/` should be for the right side
                                ? checker.getTypeAtLocation(parent.left)
                                : checker.getContextualType(previousToken);
                }
            }
            function getContextualTypeFromParent(node, checker) {
                var parent = node.parent;
                switch (parent.kind) {
                    case 190 /* NewExpression */:
                        return checker.getContextualType(parent);
                    case 202 /* BinaryExpression */: {
                        var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
                        return isEqualityOperatorKind(operatorToken.kind)
                            ? checker.getTypeAtLocation(node === right ? left : right)
                            : checker.getContextualType(node);
                    }
                    case 269 /* CaseClause */:
                        return parent.expression === node ? getSwitchedType(parent, checker) : undefined;
                    default:
                        return checker.getContextualType(node);
                }
            }
            function getSwitchedType(caseClause, checker) {
                return checker.getTypeAtLocation(caseClause.parent.parent.expression);
            }
            function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) {
                var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false);
                if (chain)
                    return ts.first(chain);
                return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
            }
            function isModuleSymbol(symbol) {
                return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; });
            }
            function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
                var typeChecker = program.getTypeChecker();
                var start = ts.timestamp();
                var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853
                // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.)
                log("getCompletionData: Get current token: " + (ts.timestamp() - start));
                start = ts.timestamp();
                var insideComment = ts.isInComment(sourceFile, position, currentToken);
                log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
                var insideJsDocTagTypeExpression = false;
                var isInSnippetScope = false;
                if (insideComment) {
                    if (ts.hasDocComment(sourceFile, position)) {
                        if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
                            // The current position is next to the '@' sign, when no tag name being provided yet.
                            // Provide a full list of tag names
                            return { kind: 1 /* JsDocTagName */ };
                        }
                        else {
                            // When completion is requested without "@", we will have check to make sure that
                            // there are no comments prefix the request position. We will only allow "*" and space.
                            // e.g
                            //   /** |c| /*
                            //
                            //   /**
                            //     |c|
                            //    */
                            //
                            //   /**
                            //    * |c|
                            //    */
                            //
                            //   /**
                            //    *         |c|
                            //    */
                            var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
                            if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) {
                                return { kind: 2 /* JsDocTag */ };
                            }
                        }
                    }
                    // Completion should work inside certain JsDoc tags. For example:
                    //     /** @type {number | string} */
                    // Completion should work in the brackets
                    var tag = getJsDocTagAtPosition(currentToken, position);
                    if (tag) {
                        if (tag.tagName.pos <= position && position <= tag.tagName.end) {
                            return { kind: 1 /* JsDocTagName */ };
                        }
                        if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) {
                            currentToken = ts.getTokenAtPosition(sourceFile, position);
                            if (!currentToken ||
                                (!ts.isDeclarationName(currentToken) &&
                                    (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ ||
                                        currentToken.parent.name !== currentToken))) {
                                // Use as type location if inside tag's type expression
                                insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
                            }
                        }
                        if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) {
                            return { kind: 3 /* JsDocParameterName */, tag: tag };
                        }
                    }
                    if (!insideJsDocTagTypeExpression) {
                        // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal
                        // comment or the plain text part of a jsDoc comment, so no completion should be available
                        log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment.");
                        return undefined;
                    }
                }
                start = ts.timestamp();
                var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217
                log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start));
                // The decision to provide completion depends on the contextToken, which is determined through the previousToken.
                // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file
                var contextToken = previousToken;
                // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
                // Skip this partial identifier and adjust the contextToken to the token that precedes it.
                if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
                    var start_4 = ts.timestamp();
                    contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
                    log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4));
                }
                // Find the node where completion is requested on.
                // Also determine whether we are trying to complete with members of that node
                // or attributes of a JSX tag.
                var node = currentToken;
                var propertyAccessToConvert;
                var isRightOfDot = false;
                var isRightOfOpenTag = false;
                var isStartingCloseTag = false;
                var isJsxInitializer = false;
                var location = ts.getTouchingPropertyName(sourceFile, position);
                if (contextToken) {
                    // Bail out if this is a known invalid completion location
                    if (isCompletionListBlocker(contextToken)) {
                        log("Returning an empty list because completion was requested in an invalid position.");
                        return undefined;
                    }
                    var parent = contextToken.parent;
                    if (contextToken.kind === 23 /* DotToken */) {
                        isRightOfDot = true;
                        switch (parent.kind) {
                            case 187 /* PropertyAccessExpression */:
                                propertyAccessToConvert = parent;
                                node = propertyAccessToConvert.expression;
                                break;
                            case 146 /* QualifiedName */:
                                node = parent.left;
                                break;
                            case 242 /* ModuleDeclaration */:
                                node = parent.name;
                                break;
                            case 181 /* ImportType */:
                            case 212 /* MetaProperty */:
                                node = parent;
                                break;
                            default:
                                // There is nothing that precedes the dot, so this likely just a stray character
                                // or leading into a '...' token. Just bail out instead.
                                return undefined;
                        }
                    }
                    else if (sourceFile.languageVariant === 1 /* JSX */) {
                        // <UI.Test /* completion position */ />
                        // If the tagname is a property access expression, we will then walk up to the top most of property access expression.
                        // Then, try to get a JSX container and its associated attributes type.
                        if (parent && parent.kind === 187 /* PropertyAccessExpression */) {
                            contextToken = parent;
                            parent = parent.parent;
                        }
                        // Fix location
                        if (currentToken.parent === location) {
                            switch (currentToken.kind) {
                                case 29 /* GreaterThanToken */:
                                    if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) {
                                        location = currentToken;
                                    }
                                    break;
                                case 41 /* SlashToken */:
                                    if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) {
                                        location = currentToken;
                                    }
                                    break;
                            }
                        }
                        switch (parent.kind) {
                            case 261 /* JsxClosingElement */:
                                if (contextToken.kind === 41 /* SlashToken */) {
                                    isStartingCloseTag = true;
                                    location = contextToken;
                                }
                                break;
                            case 202 /* BinaryExpression */:
                                if (!binaryExpressionMayBeOpenTag(parent)) {
                                    break;
                                }
                            // falls through
                            case 259 /* JsxSelfClosingElement */:
                            case 258 /* JsxElement */:
                            case 260 /* JsxOpeningElement */:
                                if (contextToken.kind === 27 /* LessThanToken */) {
                                    isRightOfOpenTag = true;
                                    location = contextToken;
                                }
                                break;
                            case 265 /* JsxAttribute */:
                                switch (previousToken.kind) {
                                    case 58 /* EqualsToken */:
                                        isJsxInitializer = true;
                                        break;
                                    case 71 /* Identifier */:
                                        // For `<div x=[|f/**/|]`, `parent` will be `x` and `previousToken.parent` will be `f` (which is its own JsxAttribute)
                                        // Note for `<div someBool f>` we don't want to treat this as a jsx inializer, instead it's the attribute name.
                                        if (parent !== previousToken.parent &&
                                            !parent.initializer &&
                                            ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) {
                                            isJsxInitializer = previousToken;
                                        }
                                }
                                break;
                        }
                    }
                }
                var semanticStart = ts.timestamp();
                var completionKind = 5 /* None */;
                var isNewIdentifierLocation = false;
                var keywordFilters = 0 /* None */;
                var symbols = [];
                var symbolToOriginInfoMap = [];
                if (isRightOfDot) {
                    getTypeScriptMemberSymbols();
                }
                else if (isRightOfOpenTag) {
                    var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
                    tryGetGlobalSymbols();
                    symbols = tagSymbols.concat(symbols);
                    completionKind = 3 /* MemberLike */;
                    keywordFilters = 0 /* None */;
                }
                else if (isStartingCloseTag) {
                    var tagName = contextToken.parent.parent.openingElement.tagName;
                    var tagSymbol = typeChecker.getSymbolAtLocation(tagName);
                    if (tagSymbol) {
                        symbols = [tagSymbol];
                    }
                    completionKind = 3 /* MemberLike */;
                    keywordFilters = 0 /* None */;
                }
                else {
                    // For JavaScript or TypeScript, if we're not after a dot, then just try to get the
                    // global symbols in scope.  These results should be valid for either language as
                    // the set of symbols that can be referenced from this location.
                    if (!tryGetGlobalSymbols()) {
                        return undefined;
                    }
                }
                log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
                var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
                var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
                var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
                return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
                function isTagWithTypeExpression(tag) {
                    switch (tag.kind) {
                        case 297 /* JSDocParameterTag */:
                        case 303 /* JSDocPropertyTag */:
                        case 298 /* JSDocReturnTag */:
                        case 300 /* JSDocTypeTag */:
                        case 302 /* JSDocTypedefTag */:
                            return true;
                        default:
                            return false;
                    }
                }
                function getTypeScriptMemberSymbols() {
                    // Right of dot member completion list
                    completionKind = 2 /* PropertyAccess */;
                    // Since this is qualified name check its a type node location
                    var isImportType = ts.isLiteralImportTypeNode(node);
                    var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent);
                    var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node);
                    var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker));
                    if (ts.isEntityName(node) || isImportType) {
                        var isNamespaceName = ts.isModuleDeclaration(node.parent);
                        if (isNamespaceName)
                            isNewIdentifierLocation = true;
                        var symbol = typeChecker.getSymbolAtLocation(node);
                        if (symbol) {
                            symbol = ts.skipAlias(symbol, typeChecker);
                            if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) {
                                // Extract module or enum members
                                var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined");
                                var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); };
                                var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); };
                                var isValidAccess = isNamespaceName
                                    // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion.
                                    ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); }
                                    : allowTypeOrValue ?
                                        // Any kind is allowed when dotting off namespace in internal import equals declaration
                                        function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } :
                                        isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1;
                                for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) {
                                    var exportedSymbol = exportedSymbols_1[_i];
                                    if (isValidAccess(exportedSymbol)) {
                                        symbols.push(exportedSymbol);
                                    }
                                }
                                // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
                                if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 277 /* SourceFile */ && d.kind !== 242 /* ModuleDeclaration */ && d.kind !== 241 /* EnumDeclaration */; })) {
                                    addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
                                }
                                return;
                            }
                        }
                    }
                    if (ts.isMetaProperty(node) && (node.keywordToken === 94 /* NewKeyword */ || node.keywordToken === 91 /* ImportKeyword */)) {
                        var completion = (node.keywordToken === 94 /* NewKeyword */) ? "target" : "meta";
                        symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion)));
                        return;
                    }
                    if (!isTypeLocation) {
                        addTypeProperties(typeChecker.getTypeAtLocation(node));
                    }
                }
                function addTypeProperties(type) {
                    isNewIdentifierLocation = !!type.getStringIndexType();
                    if (isUncheckedFile) {
                        // In javascript files, for union types, we don't just get the members that
                        // the individual types have in common, we also include all the members that
                        // each individual type has. This is because we're going to add all identifiers
                        // anyways. So we might as well elevate the members that were at least part
                        // of the individual types to a higher status since we know what they are.
                        symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker));
                    }
                    else {
                        for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) {
                            var symbol = _a[_i];
                            if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 181 /* ImportType */ ? node : node.parent, type, symbol)) {
                                addPropertySymbol(symbol);
                            }
                        }
                    }
                }
                function addPropertySymbol(symbol) {
                    // For a computed property with an accessible name like `Symbol.iterator`,
                    // we'll add a completion for the *name* `Symbol` instead of for the property.
                    // If this is e.g. [Symbol.iterator], add a completion for `Symbol`.
                    var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); });
                    if (computedPropertyName) {
                        var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`.
                        var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName);
                        // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`.
                        var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker);
                        if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) {
                            symbols.push(firstAccessibleSymbol);
                            var moduleSymbol = firstAccessibleSymbol.parent;
                            symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] =
                                !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false };
                        }
                    }
                    else {
                        symbols.push(symbol);
                    }
                }
                /** Given 'a.b.c', returns 'a'. */
                function getLeftMostName(e) {
                    return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined;
                }
                function tryGetGlobalSymbols() {
                    var result = tryGetObjectLikeCompletionSymbols()
                        || tryGetImportOrExportClauseCompletionSymbols()
                        || tryGetConstructorCompletion()
                        || tryGetClassLikeCompletionSymbols()
                        || tryGetJsxCompletionSymbols()
                        || (getGlobalCompletions(), 1 /* Success */);
                    return result === 1 /* Success */;
                }
                function tryGetConstructorCompletion() {
                    if (!tryGetConstructorLikeCompletionContainer(contextToken))
                        return 0 /* Continue */;
                    // no members, only keywords
                    completionKind = 5 /* None */;
                    // Declaring new property/method/accessor
                    isNewIdentifierLocation = true;
                    // Has keywords for constructor parameter
                    keywordFilters = 4 /* ConstructorParameterKeywords */;
                    return 1 /* Success */;
                }
                function tryGetJsxCompletionSymbols() {
                    var jsxContainer = tryGetContainingJsxElement(contextToken);
                    // Cursor is inside a JSX self-closing element or opening element
                    var attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer);
                    if (!attrsType)
                        return 0 /* Continue */;
                    symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties);
                    completionKind = 3 /* MemberLike */;
                    isNewIdentifierLocation = false;
                    return 1 /* Success */;
                }
                function getGlobalCompletions() {
                    keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
                    // Get all entities in the current scope.
                    completionKind = 1 /* Global */;
                    isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
                    if (previousToken !== contextToken) {
                        ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
                    }
                    // We need to find the node that will give us an appropriate scope to begin
                    // aggregating completion candidates. This is achieved in 'getScopeNode'
                    // by finding the first node that encompasses a position, accounting for whether a node
                    // is "complete" to decide whether a position belongs to the node.
                    //
                    // However, at the end of an identifier, we are interested in the scope of the identifier
                    // itself, but fall outside of the identifier. For instance:
                    //
                    //      xyz => x$
                    //
                    // the cursor is outside of both the 'x' and the arrow function 'xyz => x',
                    // so 'xyz' is not returned in our results.
                    //
                    // We define 'adjustedPosition' so that we may appropriately account for
                    // being at the end of an identifier. The intention is that if requesting completion
                    // at the end of an identifier, it should be effectively equivalent to requesting completion
                    // anywhere inside/at the beginning of the identifier. So in the previous case, the
                    // 'adjustedPosition' will work as if requesting completion in the following:
                    //
                    //      xyz => $x
                    //
                    // If previousToken !== contextToken, then
                    //   - 'contextToken' was adjusted to the token prior to 'previousToken'
                    //      because we were at the end of an identifier.
                    //   - 'previousToken' is defined.
                    var adjustedPosition = previousToken !== contextToken ?
                        previousToken.getStart() :
                        position;
                    var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
                    isInSnippetScope = isSnippetScope(scopeNode);
                    var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */;
                    symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
                    // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
                    if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) {
                        var thisType = typeChecker.tryGetThisTypeAt(scopeNode);
                        if (thisType) {
                            for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
                                var symbol = _a[_i];
                                symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ };
                                symbols.push(symbol);
                            }
                        }
                    }
                    if (shouldOfferImportCompletions()) {
                        getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", program.getCompilerOptions().target);
                    }
                    filterGlobalCompletion(symbols);
                }
                function shouldOfferImportCompletions() {
                    // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs)
                    if (!preferences.includeCompletionsForModuleExports)
                        return false;
                    // If already using ES6 modules, OK to continue using them.
                    if (sourceFile.externalModuleIndicator)
                        return true;
                    // If already using commonjs, don't introduce ES6.
                    if (sourceFile.commonJsModuleIndicator)
                        return false;
                    // For JS, stay on the safe side.
                    if (isUncheckedFile)
                        return false;
                    // If some file is using ES6 modules, assume that it's OK to add more.
                    if (ts.programContainsEs6Modules(program))
                        return true;
                    // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK.
                    return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions());
                }
                function isSnippetScope(scopeNode) {
                    switch (scopeNode.kind) {
                        case 277 /* SourceFile */:
                        case 204 /* TemplateExpression */:
                        case 268 /* JsxExpression */:
                        case 216 /* Block */:
                            return true;
                        default:
                            return ts.isStatement(scopeNode);
                    }
                }
                function filterGlobalCompletion(symbols) {
                    var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
                    var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
                    if (isTypeOnlyCompletion)
                        keywordFilters = 6 /* TypeKeywords */;
                    ts.filterMutate(symbols, function (symbol) {
                        if (!ts.isSourceFile(location)) {
                            // export = /**/ here we want to get all meanings, so any symbol is ok
                            if (ts.isExportAssignment(location.parent)) {
                                return true;
                            }
                            symbol = ts.skipAlias(symbol, typeChecker);
                            // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace)
                            if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) {
                                return !!(symbol.flags & 1920 /* Namespace */);
                            }
                            if (allowTypes) {
                                // Its a type, but you can reach it by namespace.type as well
                                var symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol);
                                if (symbolAllowedAsType || isTypeOnlyCompletion) {
                                    return symbolAllowedAsType;
                                }
                            }
                        }
                        // expressions are value space (which includes the value namespaces)
                        return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */);
                    });
                }
                function isContextTokenValueLocation(contextToken) {
                    return contextToken &&
                        contextToken.kind === 103 /* TypeOfKeyword */ &&
                        (contextToken.parent.kind === 165 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent));
                }
                function isContextTokenTypeLocation(contextToken) {
                    if (contextToken) {
                        var parentKind = contextToken.parent.kind;
                        switch (contextToken.kind) {
                            case 56 /* ColonToken */:
                                return parentKind === 152 /* PropertyDeclaration */ ||
                                    parentKind === 151 /* PropertySignature */ ||
                                    parentKind === 149 /* Parameter */ ||
                                    parentKind === 235 /* VariableDeclaration */ ||
                                    ts.isFunctionLikeKind(parentKind);
                            case 58 /* EqualsToken */:
                                return parentKind === 240 /* TypeAliasDeclaration */;
                            case 118 /* AsKeyword */:
                                return parentKind === 210 /* AsExpression */;
                        }
                    }
                    return false;
                }
                function symbolCanBeReferencedAtTypeLocation(symbol) {
                    symbol = symbol.exportSymbol || symbol;
                    // This is an alias, follow what it aliases
                    symbol = ts.skipAlias(symbol, typeChecker);
                    if (symbol.flags & 67897832 /* Type */) {
                        return true;
                    }
                    if (symbol.flags & 1536 /* Module */) {
                        var exportedSymbols = typeChecker.getExportsOfModule(symbol);
                        // If the exported symbols contains type,
                        // symbol can be referenced at locations where type is allowed
                        return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation);
                    }
                    return false;
                }
                function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) {
                    var tokenTextLowerCase = tokenText.toLowerCase();
                    var seenResolvedModules = ts.createMap();
                    ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, program.getSourceFiles(), function (moduleSymbol) {
                        // Perf -- ignore other modules if this is a request for details
                        if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) {
                            return;
                        }
                        var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol);
                        // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one.
                        if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) {
                            return;
                        }
                        if (resolvedModuleSymbol !== moduleSymbol &&
                            // Don't add another completion for `export =` of a symbol that's already global.
                            // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`.
                            ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) {
                            symbols.push(resolvedModuleSymbol);
                            symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false };
                        }
                        for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) {
                            var symbol = _a[_i];
                            // Don't add a completion for a re-export, only for the original.
                            // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details.
                            // This is just to avoid adding duplicate completion entries.
                            //
                            // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols.
                            // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check).
                            if (typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol
                                || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) {
                                continue;
                            }
                            var isDefaultExport = symbol.name === "default" /* Default */;
                            if (isDefaultExport) {
                                symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol;
                            }
                            var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport };
                            if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) {
                                symbols.push(symbol);
                                symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin;
                            }
                        }
                    });
                }
                /**
                 * True if you could remove some characters in `a` to get `b`.
                 * E.g., true for "abcdef" and "bdf".
                 * But not true for "abcdef" and "dbf".
                 */
                function stringContainsCharactersInOrder(str, characters) {
                    if (characters.length === 0) {
                        return true;
                    }
                    var characterIndex = 0;
                    for (var strIndex = 0; strIndex < str.length; strIndex++) {
                        if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) {
                            characterIndex++;
                            if (characterIndex === characters.length) {
                                return true;
                            }
                        }
                    }
                    // Did not find all characters
                    return false;
                }
                /**
                 * Finds the first node that "embraces" the position, so that one may
                 * accurately aggregate locals from the closest containing scope.
                 */
                function getScopeNode(initialToken, position, sourceFile) {
                    var scope = initialToken;
                    while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) {
                        scope = scope.parent;
                    }
                    return scope;
                }
                function isCompletionListBlocker(contextToken) {
                    var start = ts.timestamp();
                    var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
                        isSolelyIdentifierDefinitionLocation(contextToken) ||
                        isDotOfNumericLiteral(contextToken) ||
                        isInJsxText(contextToken);
                    log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start));
                    return result;
                }
                function isInJsxText(contextToken) {
                    if (contextToken.kind === 10 /* JsxText */) {
                        return true;
                    }
                    if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) {
                        if (contextToken.parent.kind === 260 /* JsxOpeningElement */) {
                            return true;
                        }
                        if (contextToken.parent.kind === 261 /* JsxClosingElement */ || contextToken.parent.kind === 259 /* JsxSelfClosingElement */) {
                            return !!contextToken.parent.parent && contextToken.parent.parent.kind === 258 /* JsxElement */;
                        }
                    }
                    return false;
                }
                function isNewIdentifierDefinitionLocation(previousToken) {
                    if (previousToken) {
                        var containingNodeKind = previousToken.parent.kind;
                        // Previous token may have been a keyword that was converted to an identifier.
                        switch (keywordForNode(previousToken)) {
                            case 26 /* CommaToken */:
                                return containingNodeKind === 189 /* CallExpression */ // func( a, |
                                    || containingNodeKind === 155 /* Constructor */ // constructor( a, |   /* public, protected, private keywords are allowed here, so show completion */
                                    || containingNodeKind === 190 /* NewExpression */ // new C(a, |
                                    || containingNodeKind === 185 /* ArrayLiteralExpression */ // [a, |
                                    || containingNodeKind === 202 /* BinaryExpression */ // const x = (a, |
                                    || containingNodeKind === 163 /* FunctionType */; // var x: (s: string, list|
                            case 19 /* OpenParenToken */:
                                return containingNodeKind === 189 /* CallExpression */ // func( |
                                    || containingNodeKind === 155 /* Constructor */ // constructor( |
                                    || containingNodeKind === 190 /* NewExpression */ // new C(a|
                                    || containingNodeKind === 193 /* ParenthesizedExpression */ // const x = (a|
                                    || containingNodeKind === 175 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
                            case 21 /* OpenBracketToken */:
                                return containingNodeKind === 185 /* ArrayLiteralExpression */ // [ |
                                    || containingNodeKind === 160 /* IndexSignature */ // [ | : string ]
                                    || containingNodeKind === 147 /* ComputedPropertyName */; // [ |    /* this can become an index signature */
                            case 129 /* ModuleKeyword */: // module |
                            case 130 /* NamespaceKeyword */: // namespace |
                                return true;
                            case 23 /* DotToken */:
                                return containingNodeKind === 242 /* ModuleDeclaration */; // module A.|
                            case 17 /* OpenBraceToken */:
                                return containingNodeKind === 238 /* ClassDeclaration */; // class A{ |
                            case 58 /* EqualsToken */:
                                return containingNodeKind === 235 /* VariableDeclaration */ // const x = a|
                                    || containingNodeKind === 202 /* BinaryExpression */; // x = a|
                            case 14 /* TemplateHead */:
                                return containingNodeKind === 204 /* TemplateExpression */; // `aa ${|
                            case 15 /* TemplateMiddle */:
                                return containingNodeKind === 214 /* TemplateSpan */; // `aa ${10} dd ${|
                            case 114 /* PublicKeyword */:
                            case 112 /* PrivateKeyword */:
                            case 113 /* ProtectedKeyword */:
                                return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public |
                        }
                    }
                    return false;
                }
                function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) {
                    // To be "in" one of these literals, the position has to be:
                    //   1. entirely within the token text.
                    //   2. at the end position of an unterminated token.
                    //   3. at the end of a regular expression (due to trailing flags like '/foo/g').
                    return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) ||
                        position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken)));
                }
                /**
                 * Aggregates relevant symbols for completion in object literals and object binding patterns.
                 * Relevant symbols are stored in the captured 'symbols' variable.
                 *
                 * @returns true if 'symbols' was successfully populated; false otherwise.
                 */
                function tryGetObjectLikeCompletionSymbols() {
                    var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
                    if (!objectLikeContainer)
                        return 0 /* Continue */;
                    // We're looking up possible property names from contextual/inferred/declared type.
                    completionKind = 0 /* ObjectPropertyDeclaration */;
                    var typeMembers;
                    var existingMembers;
                    if (objectLikeContainer.kind === 186 /* ObjectLiteralExpression */) {
                        var typeForObject = typeChecker.getContextualType(objectLikeContainer);
                        if (!typeForObject)
                            return 2 /* Fail */;
                        isNewIdentifierLocation = hasIndexSignature(typeForObject);
                        typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker);
                        existingMembers = objectLikeContainer.properties;
                    }
                    else {
                        ts.Debug.assert(objectLikeContainer.kind === 182 /* ObjectBindingPattern */);
                        // We are *only* completing on properties from the type being destructured.
                        isNewIdentifierLocation = false;
                        var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
                        if (!ts.isVariableLike(rootDeclaration))
                            return ts.Debug.fail("Root declaration is not variable-like.");
                        // We don't want to complete using the type acquired by the shape
                        // of the binding pattern; we are only interested in types acquired
                        // through type declaration or inference.
                        // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed -
                        // type of parameter will flow in from the contextual type of the function
                        var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 225 /* ForOfStatement */;
                        if (!canGetType && rootDeclaration.kind === 149 /* Parameter */) {
                            if (ts.isExpression(rootDeclaration.parent)) {
                                canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
                            }
                            else if (rootDeclaration.parent.kind === 154 /* MethodDeclaration */ || rootDeclaration.parent.kind === 157 /* SetAccessor */) {
                                canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent);
                            }
                        }
                        if (canGetType) {
                            var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
                            if (!typeForObject)
                                return 2 /* Fail */;
                            // In a binding pattern, get only known properties. Everywhere else we will get all possible properties.
                            typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); });
                            existingMembers = objectLikeContainer.elements;
                        }
                    }
                    if (typeMembers && typeMembers.length > 0) {
                        // Add filtered items to the completion list
                        symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers));
                    }
                    return 1 /* Success */;
                }
                /**
                 * Aggregates relevant symbols for completion in import clauses and export clauses
                 * whose declarations have a module specifier; for instance, symbols will be aggregated for
                 *
                 *      import { | } from "moduleName";
                 *      export { a as foo, | } from "moduleName";
                 *
                 * but not for
                 *
                 *      export { | };
                 *
                 * Relevant symbols are stored in the captured 'symbols' variable.
                 *
                 * @returns true if 'symbols' was successfully populated; false otherwise.
                 */
                function tryGetImportOrExportClauseCompletionSymbols() {
                    // `import { |` or `import { a as 0, | }`
                    var namedImportsOrExports = contextToken && (contextToken.kind === 17 /* OpenBraceToken */ || contextToken.kind === 26 /* CommaToken */)
                        ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined;
                    if (!namedImportsOrExports)
                        return 0 /* Continue */;
                    // cursor is in an import clause
                    // try to show exported member for imported module
                    var moduleSpecifier = (namedImportsOrExports.kind === 250 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier;
                    var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217
                    if (!moduleSpecifierSymbol)
                        return 2 /* Fail */;
                    completionKind = 3 /* MemberLike */;
                    isNewIdentifierLocation = false;
                    var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
                    var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; });
                    symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); });
                    return 1 /* Success */;
                }
                /**
                 * Aggregates relevant symbols for completion in class declaration
                 * Relevant symbols are stored in the captured 'symbols' variable.
                 */
                function tryGetClassLikeCompletionSymbols() {
                    var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location);
                    if (!decl)
                        return 0 /* Continue */;
                    // We're looking up possible property names from parent type.
                    completionKind = 3 /* MemberLike */;
                    // Declaring new property/method/accessor
                    isNewIdentifierLocation = true;
                    keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ :
                        ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */;
                    // If you're in an interface you don't want to repeat things from super-interface. So just stop here.
                    if (!ts.isClassLike(decl))
                        return 1 /* Success */;
                    var classElement = contextToken.parent;
                    var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */;
                    // If this is context token is not something we are editing now, consider if this would lead to be modifier
                    if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) {
                        switch (contextToken.getText()) {
                            case "private":
                                classElementModifierFlags = classElementModifierFlags | 8 /* Private */;
                                break;
                            case "static":
                                classElementModifierFlags = classElementModifierFlags | 32 /* Static */;
                                break;
                        }
                    }
                    // No member list for private methods
                    if (!(classElementModifierFlags & 8 /* Private */)) {
                        // List of property symbols of base type that are not private and already implemented
                        var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) {
                            var type = typeChecker.getTypeAtLocation(baseTypeNode);
                            return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type);
                        });
                        symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags);
                    }
                    return 1 /* Success */;
                }
                /**
                 * Returns the immediate owning object literal or binding pattern of a context token,
                 * on the condition that one exists and that the context implies completion should be given.
                 */
                function tryGetObjectLikeCompletionContainer(contextToken) {
                    if (contextToken) {
                        var parent = contextToken.parent;
                        switch (contextToken.kind) {
                            case 17 /* OpenBraceToken */: // const x = { |
                            case 26 /* CommaToken */: // const x = { a: 0, |
                                if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
                                    return parent;
                                }
                                break;
                            case 39 /* AsteriskToken */:
                                return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined;
                        }
                    }
                    return undefined;
                }
                function isConstructorParameterCompletion(node) {
                    return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent)
                        && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node));
                }
                /**
                 * Returns the immediate owning class declaration of a context token,
                 * on the condition that one exists and that the context implies completion should be given.
                 */
                function tryGetConstructorLikeCompletionContainer(contextToken) {
                    if (contextToken) {
                        var parent = contextToken.parent;
                        switch (contextToken.kind) {
                            case 19 /* OpenParenToken */:
                            case 26 /* CommaToken */:
                                return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined;
                            default:
                                if (isConstructorParameterCompletion(contextToken)) {
                                    return parent.parent;
                                }
                        }
                    }
                    return undefined;
                }
                function tryGetFunctionLikeBodyCompletionContainer(contextToken) {
                    if (contextToken) {
                        var prev_1;
                        var container = ts.findAncestor(contextToken.parent, function (node) {
                            if (ts.isClassLike(node)) {
                                return "quit";
                            }
                            if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) {
                                return true;
                            }
                            prev_1 = node;
                            return false;
                        });
                        return container && container;
                    }
                }
                function tryGetContainingJsxElement(contextToken) {
                    if (contextToken) {
                        var parent = contextToken.parent;
                        switch (contextToken.kind) {
                            case 28 /* LessThanSlashToken */:
                            case 41 /* SlashToken */:
                            case 71 /* Identifier */:
                            case 187 /* PropertyAccessExpression */:
                            case 266 /* JsxAttributes */:
                            case 265 /* JsxAttribute */:
                            case 267 /* JsxSpreadAttribute */:
                                if (parent && (parent.kind === 259 /* JsxSelfClosingElement */ || parent.kind === 260 /* JsxOpeningElement */)) {
                                    return parent;
                                }
                                else if (parent.kind === 265 /* JsxAttribute */) {
                                    // Currently we parse JsxOpeningLikeElement as:
                                    //      JsxOpeningLikeElement
                                    //          attributes: JsxAttributes
                                    //             properties: NodeArray<JsxAttributeLike>
                                    return parent.parent.parent;
                                }
                                break;
                            // The context token is the closing } or " of an attribute, which means
                            // its parent is a JsxExpression, whose parent is a JsxAttribute,
                            // whose parent is a JsxOpeningLikeElement
                            case 9 /* StringLiteral */:
                                if (parent && ((parent.kind === 265 /* JsxAttribute */) || (parent.kind === 267 /* JsxSpreadAttribute */))) {
                                    // Currently we parse JsxOpeningLikeElement as:
                                    //      JsxOpeningLikeElement
                                    //          attributes: JsxAttributes
                                    //             properties: NodeArray<JsxAttributeLike>
                                    return parent.parent.parent;
                                }
                                break;
                            case 18 /* CloseBraceToken */:
                                if (parent &&
                                    parent.kind === 268 /* JsxExpression */ &&
                                    parent.parent && parent.parent.kind === 265 /* JsxAttribute */) {
                                    // Currently we parse JsxOpeningLikeElement as:
                                    //      JsxOpeningLikeElement
                                    //          attributes: JsxAttributes
                                    //             properties: NodeArray<JsxAttributeLike>
                                    //                  each JsxAttribute can have initializer as JsxExpression
                                    return parent.parent.parent.parent;
                                }
                                if (parent && parent.kind === 267 /* JsxSpreadAttribute */) {
                                    // Currently we parse JsxOpeningLikeElement as:
                                    //      JsxOpeningLikeElement
                                    //          attributes: JsxAttributes
                                    //             properties: NodeArray<JsxAttributeLike>
                                    return parent.parent.parent;
                                }
                                break;
                        }
                    }
                    return undefined;
                }
                /**
                 * @returns true if we are certain that the currently edited location must define a new location; false otherwise.
                 */
                function isSolelyIdentifierDefinitionLocation(contextToken) {
                    var parent = contextToken.parent;
                    var containingNodeKind = parent.kind;
                    switch (contextToken.kind) {
                        case 26 /* CommaToken */:
                            return containingNodeKind === 235 /* VariableDeclaration */ ||
                                containingNodeKind === 236 /* VariableDeclarationList */ ||
                                containingNodeKind === 217 /* VariableStatement */ ||
                                containingNodeKind === 241 /* EnumDeclaration */ || // enum a { foo, |
                                isFunctionLikeButNotConstructor(containingNodeKind) ||
                                containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A<T, |
                                containingNodeKind === 183 /* ArrayBindingPattern */ || // var [x, y|
                                containingNodeKind === 240 /* TypeAliasDeclaration */ || // type Map, K, |
                                // class A<T, |
                                // var C = class D<T, |
                                (ts.isClassLike(parent) &&
                                    !!parent.typeParameters &&
                                    parent.typeParameters.end >= contextToken.pos);
                        case 23 /* DotToken */:
                            return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.|
                        case 56 /* ColonToken */:
                            return containingNodeKind === 184 /* BindingElement */; // var {x :html|
                        case 21 /* OpenBracketToken */:
                            return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x|
                        case 19 /* OpenParenToken */:
                            return containingNodeKind === 272 /* CatchClause */ ||
                                isFunctionLikeButNotConstructor(containingNodeKind);
                        case 17 /* OpenBraceToken */:
                            return containingNodeKind === 241 /* EnumDeclaration */; // enum a { |
                        case 27 /* LessThanToken */:
                            return containingNodeKind === 238 /* ClassDeclaration */ || // class A< |
                                containingNodeKind === 207 /* ClassExpression */ || // var C = class D< |
                                containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< |
                                containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< |
                                ts.isFunctionLikeKind(containingNodeKind);
                        case 115 /* StaticKeyword */:
                            return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent);
                        case 24 /* DotDotDotToken */:
                            return containingNodeKind === 149 /* Parameter */ ||
                                (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z|
                        case 114 /* PublicKeyword */:
                        case 112 /* PrivateKeyword */:
                        case 113 /* ProtectedKeyword */:
                            return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent);
                        case 118 /* AsKeyword */:
                            return containingNodeKind === 251 /* ImportSpecifier */ ||
                                containingNodeKind === 255 /* ExportSpecifier */ ||
                                containingNodeKind === 249 /* NamespaceImport */;
                        case 125 /* GetKeyword */:
                        case 136 /* SetKeyword */:
                            return !isFromObjectTypeDeclaration(contextToken);
                        case 75 /* ClassKeyword */:
                        case 83 /* EnumKeyword */:
                        case 109 /* InterfaceKeyword */:
                        case 89 /* FunctionKeyword */:
                        case 104 /* VarKeyword */:
                        case 91 /* ImportKeyword */:
                        case 110 /* LetKeyword */:
                        case 76 /* ConstKeyword */:
                        case 116 /* YieldKeyword */:
                        case 139 /* TypeKeyword */: // type htm|
                            return true;
                        case 39 /* AsteriskToken */:
                            return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent);
                    }
                    // If the previous token is keyword correspoding to class member completion keyword
                    // there will be completion available here
                    if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) {
                        return false;
                    }
                    if (isConstructorParameterCompletion(contextToken)) {
                        // constructor parameter completion is available only if
                        // - its modifier of the constructor parameter or
                        // - its name of the parameter and not being edited
                        // eg. constructor(a |<- this shouldnt show completion
                        if (!ts.isIdentifier(contextToken) ||
                            ts.isParameterPropertyModifier(keywordForNode(contextToken)) ||
                            isCurrentlyEditingNode(contextToken)) {
                            return false;
                        }
                    }
                    // Previous token may have been a keyword that was converted to an identifier.
                    switch (keywordForNode(contextToken)) {
                        case 117 /* AbstractKeyword */:
                        case 120 /* AsyncKeyword */:
                        case 75 /* ClassKeyword */:
                        case 76 /* ConstKeyword */:
                        case 124 /* DeclareKeyword */:
                        case 83 /* EnumKeyword */:
                        case 89 /* FunctionKeyword */:
                        case 109 /* InterfaceKeyword */:
                        case 110 /* LetKeyword */:
                        case 112 /* PrivateKeyword */:
                        case 113 /* ProtectedKeyword */:
                        case 114 /* PublicKeyword */:
                        case 115 /* StaticKeyword */:
                        case 104 /* VarKeyword */:
                        case 116 /* YieldKeyword */:
                            return true;
                    }
                    return ts.isDeclarationName(contextToken)
                        && !ts.isJsxAttribute(contextToken.parent)
                        // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`.
                        // If `contextToken !== previousToken`, this is `class C ex/**/`.
                        && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end));
                }
                function isFunctionLikeButNotConstructor(kind) {
                    return ts.isFunctionLikeKind(kind) && kind !== 155 /* Constructor */;
                }
                function isDotOfNumericLiteral(contextToken) {
                    if (contextToken.kind === 8 /* NumericLiteral */) {
                        var text = contextToken.getFullText();
                        return text.charAt(text.length - 1) === ".";
                    }
                    return false;
                }
                /**
                 * Filters out completion suggestions for named imports or exports.
                 *
                 * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
                 *          do not occur at the current position and have not otherwise been typed.
                 */
                function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
                    if (existingMembers.length === 0) {
                        return contextualMemberSymbols;
                    }
                    var existingMemberNames = ts.createUnderscoreEscapedMap();
                    for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
                        var m = existingMembers_1[_i];
                        // Ignore omitted expressions for missing members
                        if (m.kind !== 273 /* PropertyAssignment */ &&
                            m.kind !== 274 /* ShorthandPropertyAssignment */ &&
                            m.kind !== 184 /* BindingElement */ &&
                            m.kind !== 154 /* MethodDeclaration */ &&
                            m.kind !== 156 /* GetAccessor */ &&
                            m.kind !== 157 /* SetAccessor */) {
                            continue;
                        }
                        // If this is the current item we are editing right now, do not filter it out
                        if (isCurrentlyEditingNode(m)) {
                            continue;
                        }
                        var existingName = void 0;
                        if (ts.isBindingElement(m) && m.propertyName) {
                            // include only identifiers in completion list
                            if (m.propertyName.kind === 71 /* Identifier */) {
                                existingName = m.propertyName.escapedText;
                            }
                        }
                        else {
                            // TODO: Account for computed property name
                            // NOTE: if one only performs this step when m.name is an identifier,
                            // things like '__proto__' are not filtered out.
                            var name = ts.getNameOfDeclaration(m);
                            existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
                        }
                        existingMemberNames.set(existingName, true); // TODO: GH#18217
                    }
                    return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); });
                }
                /**
                 * Filters out completion suggestions for class elements.
                 *
                 * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags
                 */
                function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) {
                    var existingMemberNames = ts.createUnderscoreEscapedMap();
                    for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) {
                        var m = existingMembers_2[_i];
                        // Ignore omitted expressions for missing members
                        if (m.kind !== 152 /* PropertyDeclaration */ &&
                            m.kind !== 154 /* MethodDeclaration */ &&
                            m.kind !== 156 /* GetAccessor */ &&
                            m.kind !== 157 /* SetAccessor */) {
                            continue;
                        }
                        // If this is the current item we are editing right now, do not filter it out
                        if (isCurrentlyEditingNode(m)) {
                            continue;
                        }
                        // Dont filter member even if the name matches if it is declared private in the list
                        if (ts.hasModifier(m, 8 /* Private */)) {
                            continue;
                        }
                        // do not filter it out if the static presence doesnt match
                        if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) {
                            continue;
                        }
                        var existingName = ts.getPropertyNameForPropertyNameNode(m.name);
                        if (existingName) {
                            existingMemberNames.set(existingName, true);
                        }
                    }
                    return baseSymbols.filter(function (propertySymbol) {
                        return !existingMemberNames.has(propertySymbol.escapedName) &&
                            !!propertySymbol.declarations &&
                            !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */);
                    });
                }
                /**
                 * Filters out completion suggestions from 'symbols' according to existing JSX attributes.
                 *
                 * @returns Symbols to be suggested in a JSX element, barring those whose attributes
                 *          do not occur at the current position and have not otherwise been typed.
                 */
                function filterJsxAttributes(symbols, attributes) {
                    var seenNames = ts.createUnderscoreEscapedMap();
                    for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {
                        var attr = attributes_1[_i];
                        // If this is the current item we are editing right now, do not filter it out
                        if (isCurrentlyEditingNode(attr)) {
                            continue;
                        }
                        if (attr.kind === 265 /* JsxAttribute */) {
                            seenNames.set(attr.name.escapedText, true);
                        }
                    }
                    return symbols.filter(function (a) { return !seenNames.get(a.escapedName); });
                }
                function isCurrentlyEditingNode(node) {
                    return node.getStart(sourceFile) <= position && position <= node.getEnd();
                }
            }
            function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) {
                var name = getSymbolName(symbol, origin, target);
                if (name === undefined
                    // If the symbol is external module, don't show it in the completion list
                    // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there)
                    || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name)
                    // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@"
                    || ts.isKnownSymbol(symbol)) {
                    return undefined;
                }
                var validIdentiferResult = { name: name, needsConvertPropertyAccess: false };
                if (ts.isIdentifierText(name, target))
                    return validIdentiferResult;
                switch (kind) {
                    case 3 /* MemberLike */:
                        return undefined;
                    case 0 /* ObjectPropertyDeclaration */:
                        // TODO: GH#18169
                        return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
                    case 2 /* PropertyAccess */:
                    case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name.
                        // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547
                        return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true };
                    case 5 /* None */:
                    case 4 /* String */:
                        return validIdentiferResult;
                    default:
                        ts.Debug.assertNever(kind);
                }
            }
            // A cache of completion entries for keywords, these do not change between sessions
            var _keywordCompletions = [];
            var allKeywordsCompletions = ts.memoize(function () {
                var res = [];
                for (var i = 72 /* FirstKeyword */; i <= 145 /* LastKeyword */; i++) {
                    res.push({
                        name: ts.tokenToString(i),
                        kind: "keyword" /* keyword */,
                        kindModifiers: "" /* none */,
                        sortText: "0"
                    });
                }
                return res;
            });
            function getKeywordCompletions(keywordFilter) {
                return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
                    var kind = ts.stringToToken(entry.name);
                    switch (keywordFilter) {
                        case 0 /* None */:
                            return false;
                        case 1 /* All */:
                            return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */
                                || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */;
                        case 2 /* ClassElementKeywords */:
                            return isClassMemberCompletionKeyword(kind);
                        case 3 /* InterfaceElementKeywords */:
                            return isInterfaceOrTypeLiteralCompletionKeyword(kind);
                        case 4 /* ConstructorParameterKeywords */:
                            return ts.isParameterPropertyModifier(kind);
                        case 5 /* FunctionLikeBodyKeywords */:
                            return isFunctionLikeBodyKeyword(kind);
                        case 6 /* TypeKeywords */:
                            return ts.isTypeKeyword(kind);
                        default:
                            return ts.Debug.assertNever(keywordFilter);
                    }
                }));
            }
            function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
                return kind === 132 /* ReadonlyKeyword */;
            }
            function isClassMemberCompletionKeyword(kind) {
                switch (kind) {
                    case 117 /* AbstractKeyword */:
                    case 123 /* ConstructorKeyword */:
                    case 125 /* GetKeyword */:
                    case 136 /* SetKeyword */:
                    case 120 /* AsyncKeyword */:
                        return true;
                    default:
                        return ts.isClassMemberModifier(kind);
                }
            }
            function isFunctionLikeBodyKeyword(kind) {
                return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
            }
            function keywordForNode(node) {
                return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind;
            }
            function isEqualityOperatorKind(kind) {
                switch (kind) {
                    case 34 /* EqualsEqualsEqualsToken */:
                    case 32 /* EqualsEqualsToken */:
                    case 35 /* ExclamationEqualsEqualsToken */:
                    case 33 /* ExclamationEqualsToken */:
                        return true;
                    default:
                        return false;
                }
            }
            /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */
            function getJsDocTagAtPosition(node, position) {
                var jsdoc = ts.findAncestor(node, ts.isJSDoc);
                return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined);
            }
            function getPropertiesForObjectExpression(contextualType, obj, checker) {
                return contextualType.isUnion()
                    ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) {
                        // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals.
                        return !(memberType.flags & 32764 /* Primitive */ ||
                            checker.isArrayLikeType(memberType) ||
                            ts.typeHasCallOrConstructSignatures(memberType, checker) ||
                            checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj));
                    }))
                    : contextualType.getApparentProperties();
            }
            /**
             * Gets all properties on a type, but if that type is a union of several types,
             * excludes array-like types or callable/constructable types.
             */
            function getPropertiesForCompletion(type, checker) {
                return type.isUnion()
                    ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
                    : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
            }
            /**
             * Returns the immediate owning class declaration of a context token,
             * on the condition that one exists and that the context implies completion should be given.
             */
            function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
                // class c { method() { } | method2() { } }
                switch (location.kind) {
                    case 304 /* SyntaxList */:
                        return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
                    case 1 /* EndOfFileToken */:
                        var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
                        if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) {
                            return cls;
                        }
                }
                if (!contextToken)
                    return undefined;
                switch (contextToken.kind) {
                    case 25 /* SemicolonToken */: // class c {getValue(): number; | }
                    case 18 /* CloseBraceToken */: // class c { method() { } | }
                        // class c { method() { } b| }
                        return isFromObjectTypeDeclaration(location) && location.parent.name === location
                            ? location.parent.parent
                            : ts.tryCast(location, ts.isObjectTypeDeclaration);
                    case 17 /* OpenBraceToken */: // class c { |
                    case 26 /* CommaToken */: // class c {getValue(): number, | }
                        return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration);
                    default:
                        if (!isFromObjectTypeDeclaration(contextToken))
                            return undefined;
                        var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword;
                        return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217
                            ? contextToken.parent.parent : undefined;
                }
            }
            // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes
            function isFromObjectTypeDeclaration(node) {
                return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent);
            }
            function hasIndexSignature(type) {
                return !!type.getStringIndexType() || !!type.getNumberIndexType();
            }
            function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
                switch (triggerCharacter) {
                    case ".":
                    case "@":
                        return true;
                    case '"':
                    case "'":
                    case "`":
                        // Only automatically bring up completions if this is an opening quote.
                        return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1;
                    case "<":
                        // Opening JSX tag
                        return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent));
                    case "/":
                        return ts.isStringLiteralLike(contextToken)
                            ? !!ts.tryGetImportFromModuleSpecifier(contextToken)
                            : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent);
                    default:
                        return ts.Debug.assertNever(triggerCharacter);
                }
            }
            function binaryExpressionMayBeOpenTag(_a) {
                var left = _a.left;
                return ts.nodeIsMissing(left);
            }
            function isStringLiteralOrTemplate(node) {
                switch (node.kind) {
                    case 9 /* StringLiteral */:
                    case 13 /* NoSubstitutionTemplateLiteral */:
                    case 204 /* TemplateExpression */:
                    case 191 /* TaggedTemplateExpression */:
                        return true;
                    default:
                        return false;
                }
            }
        })(Completions = ts.Completions || (ts.Completions = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var DocumentHighlights;
        (function (DocumentHighlights) {
            function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) {
                var node = ts.getTouchingPropertyName(sourceFile, position);
                if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) {
                    // For a JSX element, just highlight the matching tag, not all references.
                    var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
                    var highlightSpans = [openingElement, closingElement].map(function (_a) {
                        var tagName = _a.tagName;
                        return getHighlightSpanForNode(tagName, sourceFile);
                    });
                    return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
                }
                return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile);
            }
            DocumentHighlights.getDocumentHighlights = getDocumentHighlights;
            function getHighlightSpanForNode(node, sourceFile) {
                return {
                    fileName: sourceFile.fileName,
                    textSpan: ts.createTextSpanFromNode(node, sourceFile),
                    kind: "none" /* none */
                };
            }
            function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
                var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; });
                var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet);
                if (!referenceEntries)
                    return undefined;
                var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; });
                return ts.arrayFrom(map.entries(), function (_a) {
                    var fileName = _a[0], highlightSpans = _a[1];
                    if (!sourceFilesSet.has(fileName)) {
                        ts.Debug.assert(program.redirectTargetsMap.has(fileName));
                        var redirectTarget_1 = program.getSourceFile(fileName);
                        var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; });
                        fileName = redirect.fileName;
                        ts.Debug.assert(sourceFilesSet.has(fileName));
                    }
                    return { fileName: fileName, highlightSpans: highlightSpans };
                });
            }
            function getSyntacticDocumentHighlights(node, sourceFile) {
                var highlightSpans = getHighlightSpans(node, sourceFile);
                return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
            }
            function getHighlightSpans(node, sourceFile) {
                switch (node.kind) {
                    case 90 /* IfKeyword */:
                    case 82 /* ElseKeyword */:
                        return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined;
                    case 96 /* ReturnKeyword */:
                        return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences);
                    case 100 /* ThrowKeyword */:
                        return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences);
                    case 102 /* TryKeyword */:
                    case 74 /* CatchKeyword */:
                    case 87 /* FinallyKeyword */:
                        var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent;
                        return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences);
                    case 98 /* SwitchKeyword */:
                        return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
                    case 73 /* CaseKeyword */:
                    case 79 /* DefaultKeyword */:
                        return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
                    case 72 /* BreakKeyword */:
                    case 77 /* ContinueKeyword */:
                        return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences);
                    case 88 /* ForKeyword */:
                    case 106 /* WhileKeyword */:
                    case 81 /* DoKeyword */:
                        return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences);
                    case 123 /* ConstructorKeyword */:
                        return getFromAllDeclarations(ts.isConstructorDeclaration, [123 /* ConstructorKeyword */]);
                    case 125 /* GetKeyword */:
                    case 136 /* SetKeyword */:
                        return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]);
                    case 121 /* AwaitKeyword */:
                        return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
                    case 120 /* AsyncKeyword */:
                        return highlightSpans(getAsyncAndAwaitOccurrences(node));
                    case 116 /* YieldKeyword */:
                        return highlightSpans(getYieldOccurrences(node));
                    default:
                        return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
                            ? highlightSpans(getModifierOccurrences(node.kind, node.parent))
                            : undefined;
                }
                function getFromAllDeclarations(nodeTest, keywords) {
                    return useParent(node.parent, nodeTest, function (decl) {
                        return ts.mapDefined(decl.symbol.declarations, function (d) {
                            return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined;
                        });
                    });
                }
                function useParent(node, nodeTest, getNodes) {
                    return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined;
                }
                function highlightSpans(nodes) {
                    return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); });
                }
            }
            /**
             * Aggregates all throw-statements within this node *without* crossing
             * into function boundaries and try-blocks with catch-clauses.
             */
            function aggregateOwnedThrowStatements(node) {
                if (ts.isThrowStatement(node)) {
                    return [node];
                }
                else if (ts.isTryStatement(node)) {
                    // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context.
                    return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock));
                }
                // Do not cross function boundaries.
                return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements);
            }
            /**
             * For lack of a better name, this function takes a throw statement and returns the
             * nearest ancestor that is a try-block (whose try statement has a catch clause),
             * function-block, or source file.
             */
            function getThrowStatementOwner(throwStatement) {
                var child = throwStatement;
                while (child.parent) {
                    var parent = child.parent;
                    if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) {
                        return parent;
                    }
                    // A throw-statement is only owned by a try-statement if the try-statement has
                    // a catch clause, and if the throw-statement occurs within the try block.
                    if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
                        return child;
                    }
                    child = parent;
                }
                return undefined;
            }
            function aggregateAllBreakAndContinueStatements(node) {
                return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements);
            }
            function flatMapChildren(node, cb) {
                var result = [];
                node.forEachChild(function (child) {
                    var value = cb(child);
                    if (value !== undefined) {
                        result.push.apply(result, ts.toArray(value));
                    }
                });
                return result;
            }
            function ownsBreakOrContinueStatement(owner, statement) {
                var actualOwner = getBreakOrContinueOwner(statement);
                return !!actualOwner && actualOwner === owner;
            }
            function getBreakOrContinueOwner(statement) {
                return ts.findAncestor(statement, function (node) {
                    switch (node.kind) {
                        case 230 /* SwitchStatement */:
                            if (statement.kind === 226 /* ContinueStatement */) {
                                return false;
                            }
                        // falls through
                        case 223 /* ForStatement */:
                        case 224 /* ForInStatement */:
                        case 225 /* ForOfStatement */:
                        case 222 /* WhileStatement */:
                        case 221 /* DoStatement */:
                            return !statement.label || isLabeledBy(node, statement.label.escapedText);
                        default:
                            // Don't cross function boundaries.
                            // TODO: GH#20090
                            return ts.isFunctionLike(node) && "quit";
                    }
                });
            }
            function getModifierOccurrences(modifier, declaration) {
                return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); });
            }
            function getNodesToSearchForModifier(declaration, modifierFlag) {
                // Types of node whose children might have modifiers.
                var container = declaration.parent;
                switch (container.kind) {
                    case 243 /* ModuleBlock */:
                    case 277 /* SourceFile */:
                    case 216 /* Block */:
                    case 269 /* CaseClause */:
                    case 270 /* DefaultClause */:
                        // Container is either a class declaration or the declaration is a classDeclaration
                        if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) {
                            return declaration.members.concat([declaration]);
                        }
                        else {
                            return container.statements;
                        }
                    case 155 /* Constructor */:
                    case 154 /* MethodDeclaration */:
                    case 237 /* FunctionDeclaration */:
                        return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : []));
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                        var nodes = container.members;
                        // If we're an accessibility modifier, we're in an instance member and should search
                        // the constructor's parameter list for instance members as well.
                        if (modifierFlag & 28 /* AccessibilityModifier */) {
                            var constructor = ts.find(container.members, ts.isConstructorDeclaration);
                            if (constructor) {
                                return nodes.concat(constructor.parameters);
                            }
                        }
                        else if (modifierFlag & 128 /* Abstract */) {
                            return nodes.concat([container]);
                        }
                        return nodes;
                    default:
                        ts.Debug.assertNever(container, "Invalid container kind.");
                }
            }
            function pushKeywordIf(keywordList, token) {
                var expected = [];
                for (var _i = 2; _i < arguments.length; _i++) {
                    expected[_i - 2] = arguments[_i];
                }
                if (token && ts.contains(expected, token.kind)) {
                    keywordList.push(token);
                    return true;
                }
                return false;
            }
            function getLoopBreakContinueOccurrences(loopNode) {
                var keywords = [];
                if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) {
                    // If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
                    if (loopNode.kind === 221 /* DoStatement */) {
                        var loopTokens = loopNode.getChildren();
                        for (var i = loopTokens.length - 1; i >= 0; i--) {
                            if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) {
                                break;
                            }
                        }
                    }
                }
                ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) {
                    if (ownsBreakOrContinueStatement(loopNode, statement)) {
                        pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */, 77 /* ContinueKeyword */);
                    }
                });
                return keywords;
            }
            function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
                var owner = getBreakOrContinueOwner(breakOrContinueStatement);
                if (owner) {
                    switch (owner.kind) {
                        case 223 /* ForStatement */:
                        case 224 /* ForInStatement */:
                        case 225 /* ForOfStatement */:
                        case 221 /* DoStatement */:
                        case 222 /* WhileStatement */:
                            return getLoopBreakContinueOccurrences(owner);
                        case 230 /* SwitchStatement */:
                            return getSwitchCaseDefaultOccurrences(owner);
                    }
                }
                return undefined;
            }
            function getSwitchCaseDefaultOccurrences(switchStatement) {
                var keywords = [];
                pushKeywordIf(keywords, switchStatement.getFirstToken(), 98 /* SwitchKeyword */);
                // Go through each clause in the switch statement, collecting the 'case'/'default' keywords.
                ts.forEach(switchStatement.caseBlock.clauses, function (clause) {
                    pushKeywordIf(keywords, clause.getFirstToken(), 73 /* CaseKeyword */, 79 /* DefaultKeyword */);
                    ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) {
                        if (ownsBreakOrContinueStatement(switchStatement, statement)) {
                            pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */);
                        }
                    });
                });
                return keywords;
            }
            function getTryCatchFinallyOccurrences(tryStatement, sourceFile) {
                var keywords = [];
                pushKeywordIf(keywords, tryStatement.getFirstToken(), 102 /* TryKeyword */);
                if (tryStatement.catchClause) {
                    pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 74 /* CatchKeyword */);
                }
                if (tryStatement.finallyBlock) {
                    var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile);
                    pushKeywordIf(keywords, finallyKeyword, 87 /* FinallyKeyword */);
                }
                return keywords;
            }
            function getThrowOccurrences(throwStatement, sourceFile) {
                var owner = getThrowStatementOwner(throwStatement);
                if (!owner) {
                    return undefined;
                }
                var keywords = [];
                ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) {
                    keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile));
                });
                // If the "owner" is a function, then we equate 'return' and 'throw' statements in their
                // ability to "jump out" of the function, and include occurrences for both.
                if (ts.isFunctionBlock(owner)) {
                    ts.forEachReturnStatement(owner, function (returnStatement) {
                        keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile));
                    });
                }
                return keywords;
            }
            function getReturnOccurrences(returnStatement, sourceFile) {
                var func = ts.getContainingFunction(returnStatement);
                if (!func) {
                    return undefined;
                }
                var keywords = [];
                ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) {
                    keywords.push(ts.findChildOfKind(returnStatement, 96 /* ReturnKeyword */, sourceFile));
                });
                // Include 'throw' statements that do not occur within a try block.
                ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) {
                    keywords.push(ts.findChildOfKind(throwStatement, 100 /* ThrowKeyword */, sourceFile));
                });
                return keywords;
            }
            function getAsyncAndAwaitOccurrences(node) {
                var func = ts.getContainingFunction(node);
                if (!func) {
                    return undefined;
                }
                var keywords = [];
                if (func.modifiers) {
                    func.modifiers.forEach(function (modifier) {
                        pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */);
                    });
                }
                ts.forEachChild(func, function (child) {
                    traverseWithoutCrossingFunction(child, function (node) {
                        if (ts.isAwaitExpression(node)) {
                            pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */);
                        }
                    });
                });
                return keywords;
            }
            function getYieldOccurrences(node) {
                var func = ts.getContainingFunction(node);
                if (!func) {
                    return undefined;
                }
                var keywords = [];
                ts.forEachChild(func, function (child) {
                    traverseWithoutCrossingFunction(child, function (node) {
                        if (ts.isYieldExpression(node)) {
                            pushKeywordIf(keywords, node.getFirstToken(), 116 /* YieldKeyword */);
                        }
                    });
                });
                return keywords;
            }
            // Do not cross function/class/interface/module/type boundaries.
            function traverseWithoutCrossingFunction(node, cb) {
                cb(node);
                if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
                    ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); });
                }
            }
            function getIfElseOccurrences(ifStatement, sourceFile) {
                var keywords = getIfElseKeywords(ifStatement, sourceFile);
                var result = [];
                // We'd like to highlight else/ifs together if they are only separated by whitespace
                // (i.e. the keywords are separated by no comments, no newlines).
                for (var i = 0; i < keywords.length; i++) {
                    if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) {
                        var elseKeyword = keywords[i];
                        var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword.
                        var shouldCombineElseAndIf = true;
                        // Avoid recalculating getStart() by iterating backwards.
                        for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) {
                            if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
                                shouldCombineElseAndIf = false;
                                break;
                            }
                        }
                        if (shouldCombineElseAndIf) {
                            result.push({
                                fileName: sourceFile.fileName,
                                textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
                                kind: "reference" /* reference */
                            });
                            i++; // skip the next keyword
                            continue;
                        }
                    }
                    // Ordinary case: just highlight the keyword.
                    result.push(getHighlightSpanForNode(keywords[i], sourceFile));
                }
                return result;
            }
            function getIfElseKeywords(ifStatement, sourceFile) {
                var keywords = [];
                // Traverse upwards through all parent if-statements linked by their else-branches.
                while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) {
                    ifStatement = ifStatement.parent;
                }
                // Now traverse back down through the else branches, aggregating if/else keywords of if-statements.
                while (true) {
                    var children = ifStatement.getChildren(sourceFile);
                    pushKeywordIf(keywords, children[0], 90 /* IfKeyword */);
                    // Generally the 'else' keyword is second-to-last, so we traverse backwards.
                    for (var i = children.length - 1; i >= 0; i--) {
                        if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) {
                            break;
                        }
                    }
                    if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) {
                        break;
                    }
                    ifStatement = ifStatement.elseStatement;
                }
                return keywords;
            }
            /**
             * Whether or not a 'node' is preceded by a label of the given string.
             * Note: 'node' cannot be a SourceFile.
             */
            function isLabeledBy(node, labelName) {
                return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; });
            }
        })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {}));
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) {
            return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory);
        }
        ts.createDocumentRegistry = createDocumentRegistry;
        /*@internal*/
        function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) {
            if (currentDirectory === void 0) {
                currentDirectory = "";
            }
            // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
            // for those settings.
            var buckets = ts.createMap();
            var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames);
            function getBucketForCompilationSettings(key, createIfMissing) {
                var bucket = buckets.get(key);
                if (!bucket && createIfMissing) {
                    buckets.set(key, bucket = ts.createMap());
                }
                return bucket; // TODO: GH#18217
            }
            function reportStats() {
                var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) {
                    var entries = buckets.get(name);
                    var sourceFiles = [];
                    entries.forEach(function (entry, name) {
                        sourceFiles.push({
                            name: name,
                            refCount: entry.languageServiceRefCount
                        });
                    });
                    sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; });
                    return {
                        bucket: name,
                        sourceFiles: sourceFiles
                    };
                });
                return JSON.stringify(bucketInfoArray, undefined, 2);
            }
            function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
                var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
                var key = getKeyForCompilationSettings(compilationSettings);
                return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
            }
            function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
                return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind);
            }
            function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
                var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
                var key = getKeyForCompilationSettings(compilationSettings);
                return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
            }
            function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
                return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind);
            }
            function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
                var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
                var entry = bucket.get(path);
                var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */;
                if (!entry && externalCache) {
                    var sourceFile = externalCache.getDocument(key, path);
                    if (sourceFile) {
                        ts.Debug.assert(acquiring);
                        entry = {
                            sourceFile: sourceFile,
                            languageServiceRefCount: 0
                        };
                        bucket.set(path, entry);
                    }
                }
                if (!entry) {
                    // Have never seen this file with these settings.  Create a new source file for it.
                    var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
                    if (externalCache) {
                        externalCache.setDocument(key, path, sourceFile);
                    }
                    entry = {
                        sourceFile: sourceFile,
                        languageServiceRefCount: 1,
                    };
                    bucket.set(path, entry);
                }
                else {
                    // We have an entry for this file.  However, it may be for a different version of
                    // the script snapshot.  If so, update it appropriately.  Otherwise, we can just
                    // return it as is.
                    if (entry.sourceFile.version !== version) {
                        entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217
                        if (externalCache) {
                            externalCache.setDocument(key, path, entry.sourceFile);
                        }
                    }
                    // If we're acquiring, then this is the first time this LS is asking for this document.
                    // Increase our ref count so we know there's another LS using the document.  If we're
                    // not acquiring, then that means the LS is 'updating' the file instead, and that means
                    // it has already acquired the document previously.  As such, we do not need to increase
                    // the ref count.
                    if (acquiring) {
                        entry.languageServiceRefCount++;
                    }
                }
                ts.Debug.assert(entry.languageServiceRefCount !== 0);
                return entry.sourceFile;
            }
            function releaseDocument(fileName, compilationSettings) {
                var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
                var key = getKeyForCompilationSettings(compilationSettings);
                return releaseDocumentWithKey(path, key);
            }
            function releaseDocumentWithKey(path, key) {
                var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false);
                ts.Debug.assert(bucket !== undefined);
                var entry = bucket.get(path);
                entry.languageServiceRefCount--;
                ts.Debug.assert(entry.languageServiceRefCount >= 0);
                if (entry.languageServiceRefCount === 0) {
                    bucket.delete(path);
                }
            }
            function getLanguageServiceRefCounts(path) {
                return ts.arrayFrom(buckets.entries(), function (_a) {
                    var key = _a[0], bucket = _a[1];
                    var entry = bucket.get(path);
                    return [key, entry && entry.languageServiceRefCount];
                });
            }
            return {
                acquireDocument: acquireDocument,
                acquireDocumentWithKey: acquireDocumentWithKey,
                updateDocument: updateDocument,
                updateDocumentWithKey: updateDocumentWithKey,
                releaseDocument: releaseDocument,
                releaseDocumentWithKey: releaseDocumentWithKey,
                getLanguageServiceRefCounts: getLanguageServiceRefCounts,
                reportStats: reportStats,
                getKeyForCompilationSettings: getKeyForCompilationSettings
            };
        }
        ts.createDocumentRegistryInternal = createDocumentRegistryInternal;
        function getKeyForCompilationSettings(settings) {
            return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|");
        }
    })(ts || (ts = {}));
    /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */
    /* @internal */
    var ts;
    (function (ts) {
        var FindAllReferences;
        (function (FindAllReferences) {
            /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily.  */
            function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) {
                var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
                return function (exportSymbol, exportInfo, isForRename) {
                    var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers;
                    return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename));
                };
            }
            FindAllReferences.createImportTracker = createImportTracker;
            var ExportKind;
            (function (ExportKind) {
                ExportKind[ExportKind["Named"] = 0] = "Named";
                ExportKind[ExportKind["Default"] = 1] = "Default";
                ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals";
            })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {}));
            var ImportExport;
            (function (ImportExport) {
                ImportExport[ImportExport["Import"] = 0] = "Import";
                ImportExport[ImportExport["Export"] = 1] = "Export";
            })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {}));
            /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */
            function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) {
                var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind;
                var markSeenDirectImport = ts.nodeSeenTracker();
                var markSeenIndirectUser = ts.nodeSeenTracker();
                var directImports = [];
                var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports;
                var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : [];
                handleDirectImports(exportingModuleSymbol);
                return { directImports: directImports, indirectUsers: getIndirectUsers() };
                function getIndirectUsers() {
                    if (isAvailableThroughGlobal) {
                        // It has `export as namespace`, so anything could potentially use it.
                        return sourceFiles;
                    }
                    // Module augmentations may use this module's exports without importing it.
                    for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
                            addIndirectUser(decl);
                        }
                    }
                    // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that.
                    return indirectUserDeclarations.map(ts.getSourceFileOfNode);
                }
                function handleDirectImports(exportingModuleSymbol) {
                    var theseDirectImports = getDirectImports(exportingModuleSymbol);
                    if (theseDirectImports) {
                        for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) {
                            var direct = theseDirectImports_1[_i];
                            if (!markSeenDirectImport(direct)) {
                                continue;
                            }
                            if (cancellationToken)
                                cancellationToken.throwIfCancellationRequested();
                            switch (direct.kind) {
                                case 189 /* CallExpression */:
                                    if (!isAvailableThroughGlobal) {
                                        var parent = direct.parent;
                                        if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) {
                                            var name = parent.name;
                                            if (name.kind === 71 /* Identifier */) {
                                                directImports.push(name);
                                                break;
                                            }
                                        }
                                        // Don't support re-exporting 'require()' calls, so just add a single indirect user.
                                        addIndirectUser(direct.getSourceFile());
                                    }
                                    break;
                                case 71 /* Identifier */: // for 'const x = require("y");
                                    break; // TODO: GH#23879
                                case 246 /* ImportEqualsDeclaration */:
                                    handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false);
                                    break;
                                case 247 /* ImportDeclaration */:
                                    directImports.push(direct);
                                    var namedBindings = direct.importClause && direct.importClause.namedBindings;
                                    if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) {
                                        handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true);
                                    }
                                    else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) {
                                        addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports
                                    }
                                    break;
                                case 253 /* ExportDeclaration */:
                                    if (!direct.exportClause) {
                                        // This is `export * from "foo"`, so imports of this module may import the export too.
                                        handleDirectImports(getContainingModuleSymbol(direct, checker));
                                    }
                                    else {
                                        // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports.
                                        directImports.push(direct);
                                    }
                                    break;
                                case 181 /* ImportType */:
                                    directImports.push(direct);
                                    break;
                                default:
                                    ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct));
                            }
                        }
                    }
                }
                function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) {
                    if (exportKind === 2 /* ExportEquals */) {
                        // This is a direct import, not import-as-namespace.
                        if (!alreadyAddedDirect)
                            directImports.push(importDeclaration);
                    }
                    else if (!isAvailableThroughGlobal) {
                        var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
                        ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */);
                        if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
                            addIndirectUsers(sourceFileLike);
                        }
                        else {
                            addIndirectUser(sourceFileLike);
                        }
                    }
                }
                function addIndirectUser(sourceFileLike) {
                    ts.Debug.assert(!isAvailableThroughGlobal);
                    var isNew = markSeenIndirectUser(sourceFileLike);
                    if (isNew) {
                        indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217
                    }
                    return isNew;
                }
                /** Adds a module and all of its transitive dependencies as possible indirect users. */
                function addIndirectUsers(sourceFileLike) {
                    if (!addIndirectUser(sourceFileLike)) {
                        return;
                    }
                    var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
                    ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
                    var directImports = getDirectImports(moduleSymbol);
                    if (directImports) {
                        for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) {
                            var directImport = directImports_1[_i];
                            addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport));
                        }
                    }
                }
                function getDirectImports(moduleSymbol) {
                    return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString());
                }
            }
            /**
             * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol.
             * The returned `importSearches` will result in the entire source file being searched.
             * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced.
             */
            function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) {
                var importSearches = [];
                var singleReferences = [];
                function addSearch(location, symbol) {
                    importSearches.push([location, symbol]);
                }
                if (directImports) {
                    for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) {
                        var decl = directImports_2[_i];
                        handleImport(decl);
                    }
                }
                return { importSearches: importSearches, singleReferences: singleReferences };
                function handleImport(decl) {
                    if (decl.kind === 246 /* ImportEqualsDeclaration */) {
                        if (isExternalModuleImportEquals(decl)) {
                            handleNamespaceImportLike(decl.name);
                        }
                        return;
                    }
                    if (decl.kind === 71 /* Identifier */) {
                        handleNamespaceImportLike(decl);
                        return;
                    }
                    if (decl.kind === 181 /* ImportType */) {
                        if (decl.qualifier) {
                            if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) {
                                singleReferences.push(decl.qualifier);
                            }
                        }
                        else if (exportKind === 2 /* ExportEquals */) {
                            singleReferences.push(decl.argument.literal);
                        }
                        return;
                    }
                    // Ignore if there's a grammar error
                    if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) {
                        return;
                    }
                    if (decl.kind === 253 /* ExportDeclaration */) {
                        searchForNamedImport(decl.exportClause);
                        return;
                    }
                    var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings;
                    if (namedBindings) {
                        switch (namedBindings.kind) {
                            case 249 /* NamespaceImport */:
                                handleNamespaceImportLike(namedBindings.name);
                                break;
                            case 250 /* NamedImports */:
                                // 'default' might be accessed as a named import `{ default as foo }`.
                                if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) {
                                    searchForNamedImport(namedBindings);
                                }
                                break;
                            default:
                                ts.Debug.assertNever(namedBindings);
                        }
                    }
                    // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals.
                    // If a default import has the same name as the default export, allow to rename it.
                    // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
                    if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
                        var defaultImportAlias = checker.getSymbolAtLocation(name);
                        addSearch(name, defaultImportAlias);
                    }
                }
                /**
                 * `import x = require("./x") or `import * as x from "./x"`.
                 * An `export =` may be imported by this syntax, so it may be a direct import.
                 * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
                 */
                function handleNamespaceImportLike(importName) {
                    // Don't rename an import that already has a different name than the export.
                    if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) {
                        addSearch(importName, checker.getSymbolAtLocation(importName));
                    }
                }
                function searchForNamedImport(namedBindings) {
                    if (!namedBindings) {
                        return;
                    }
                    for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
                        var element = _a[_i];
                        var name = element.name, propertyName = element.propertyName;
                        if (!isNameMatch((propertyName || name).escapedText)) {
                            continue;
                        }
                        if (propertyName) {
                            // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference.
                            singleReferences.push(propertyName);
                            // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`.
                            // But do rename `foo` in ` { default as foo }` if that's the original export name.
                            if (!isForRename || name.escapedText === exportSymbol.escapedName) {
                                // Search locally for `bar`.
                                addSearch(name, checker.getSymbolAtLocation(name));
                            }
                        }
                        else {
                            var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName
                                ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
                                : checker.getSymbolAtLocation(name);
                            addSearch(name, localSymbol);
                        }
                    }
                }
                function isNameMatch(name) {
                    // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports
                    return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */;
                }
            }
            /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */
            function findNamespaceReExports(sourceFileLike, name, checker) {
                var namespaceImportSymbol = checker.getSymbolAtLocation(name);
                return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
                    if (!ts.isExportDeclaration(statement))
                        return;
                    var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
                    return !moduleSpecifier && exportClause &&
                        exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
                });
            }
            function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
                var refs = [];
                var checker = program.getTypeChecker();
                for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
                    var referencingFile = sourceFiles_3[_i];
                    var searchSourceFile = searchModuleSymbol.valueDeclaration;
                    if (searchSourceFile.kind === 277 /* SourceFile */) {
                        for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
                            var ref = _b[_a];
                            if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
                                refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
                            }
                        }
                        for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) {
                            var ref = _d[_c];
                            var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName);
                            if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) {
                                refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
                            }
                        }
                    }
                    forEachImport(referencingFile, function (_importDecl, moduleSpecifier) {
                        var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
                        if (moduleSymbol === searchModuleSymbol) {
                            refs.push({ kind: "import", literal: moduleSpecifier });
                        }
                    });
                }
                return refs;
            }
            FindAllReferences.findModuleReferences = findModuleReferences;
            /** Returns a map from a module symbol Id to all import statements that directly reference the module. */
            function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
                var map = ts.createMap();
                for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
                    var sourceFile = sourceFiles_4[_i];
                    if (cancellationToken)
                        cancellationToken.throwIfCancellationRequested();
                    forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
                        var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
                        if (moduleSymbol) {
                            var id = ts.getSymbolId(moduleSymbol).toString();
                            var imports = map.get(id);
                            if (!imports) {
                                map.set(id, imports = []);
                            }
                            imports.push(importDecl);
                        }
                    });
                }
                return map;
            }
            /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
            function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
                return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
                    return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
                });
            }
            /** Calls `action` for each import, re-export, or require() in a file. */
            function forEachImport(sourceFile, action) {
                if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) {
                    for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
                        var i = _a[_i];
                        action(ts.importFromModuleSpecifier(i), i);
                    }
                }
                else {
                    forEachPossibleImportOrExportStatement(sourceFile, function (statement) {
                        switch (statement.kind) {
                            case 253 /* ExportDeclaration */:
                            case 247 /* ImportDeclaration */: {
                                var decl = statement;
                                if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) {
                                    action(decl, decl.moduleSpecifier);
                                }
                                break;
                            }
                            case 246 /* ImportEqualsDeclaration */: {
                                var decl = statement;
                                if (isExternalModuleImportEquals(decl)) {
                                    action(decl, decl.moduleReference.expression);
                                }
                                break;
                            }
                        }
                    });
                }
            }
            /**
             * Given a local reference, we might notice that it's an import/export and recursively search for references of that.
             * If at an import, look locally for the symbol it imports.
             * If an an export, look for all imports of it.
             * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`.
             * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here.
             */
            function getImportOrExportSymbol(node, symbol, checker, comingFromExport) {
                return comingFromExport ? getExport() : getExport() || getImport();
                function getExport() {
                    var parent = node.parent;
                    var grandParent = parent.parent;
                    if (symbol.exportSymbol) {
                        if (parent.kind === 187 /* PropertyAccessExpression */) {
                            // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use.
                            // So check that we are at the declaration.
                            return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent)
                                ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false)
                                : undefined;
                        }
                        else {
                            return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent));
                        }
                    }
                    else {
                        var exportNode = getExportNode(parent, node);
                        if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) {
                            if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) {
                                // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement.
                                if (comingFromExport) {
                                    return undefined;
                                }
                                var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
                                return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false };
                            }
                            else {
                                return exportInfo(symbol, getExportKindForDeclaration(exportNode));
                            }
                        }
                        // If we are in `export = a;` or `export default a;`, `parent` is the export assignment.
                        else if (ts.isExportAssignment(parent)) {
                            return getExportAssignmentExport(parent);
                        }
                        // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment.
                        else if (ts.isExportAssignment(grandParent)) {
                            return getExportAssignmentExport(grandParent);
                        }
                        // Similar for `module.exports =` and `exports.A =`.
                        else if (ts.isBinaryExpression(parent)) {
                            return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
                        }
                        else if (ts.isBinaryExpression(grandParent)) {
                            return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true);
                        }
                        else if (ts.isJSDocTypedefTag(parent)) {
                            return exportInfo(symbol, 0 /* Named */);
                        }
                    }
                    function getExportAssignmentExport(ex) {
                        // Get the symbol for the `export =` node; its parent is the module it's the export of.
                        var exportingModuleSymbol = ts.Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent");
                        var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */;
                        return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } };
                    }
                    function getSpecialPropertyExport(node, useLhsSymbol) {
                        var kind;
                        switch (ts.getAssignmentDeclarationKind(node)) {
                            case 1 /* ExportsProperty */:
                                kind = 0 /* Named */;
                                break;
                            case 2 /* ModuleExports */:
                                kind = 2 /* ExportEquals */;
                                break;
                            default:
                                return undefined;
                        }
                        var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.cast(node.left, ts.isPropertyAccessExpression).name) : symbol;
                        // Better detection for GH#20803
                        if (sym && !(checker.getMergedSymbol(sym.parent).flags & 1536 /* Module */)) {
                            ts.Debug.fail("Special property assignment kind does not have a module as its parent. Assignment is " + ts.Debug.showSymbol(sym) + ", parent is " + ts.Debug.showSymbol(sym.parent));
                        }
                        return sym && exportInfo(sym, kind);
                    }
                }
                function getImport() {
                    var isImport = isNodeImport(node);
                    if (!isImport)
                        return undefined;
                    // A symbol being imported is always an alias. So get what that aliases to find the local symbol.
                    var importedSymbol = checker.getImmediateAliasedSymbol(symbol);
                    if (!importedSymbol)
                        return undefined;
                    // Search on the local symbol in the exporting module, not the exported symbol.
                    importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker);
                    // Similarly, skip past the symbol for 'export ='
                    if (importedSymbol.escapedName === "export=") {
                        importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker);
                    }
                    // If the import has a different name than the export, do not continue searching.
                    // If `importedName` is undefined, do continue searching as the export is anonymous.
                    // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
                    var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
                    if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
                        return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
                    }
                }
                function exportInfo(symbol, kind) {
                    var exportInfo = getExportInfo(symbol, kind, checker);
                    return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo };
                }
                // Not meant for use with export specifiers or export assignment.
                function getExportKindForDeclaration(node) {
                    return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */;
                }
            }
            FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol;
            function getExportEqualsLocalSymbol(importedSymbol, checker) {
                if (importedSymbol.flags & 2097152 /* Alias */) {
                    return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol));
                }
                var decl = importedSymbol.valueDeclaration;
                if (ts.isExportAssignment(decl)) { // `export = class {}`
                    return ts.Debug.assertDefined(decl.expression.symbol);
                }
                else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}`
                    return ts.Debug.assertDefined(decl.right.symbol);
                }
                else if (ts.isSourceFile(decl)) { // json module
                    return ts.Debug.assertDefined(decl.symbol);
                }
                return ts.Debug.fail();
            }
            // If a reference is a class expression, the exported node would be its parent.
            // If a reference is a variable declaration, the exported node would be the variable statement.
            function getExportNode(parent, node) {
                if (parent.kind === 235 /* VariableDeclaration */) {
                    var p = parent;
                    return p.name !== node ? undefined :
                        p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined;
                }
                else {
                    return parent;
                }
            }
            function isNodeImport(node) {
                var parent = node.parent;
                switch (parent.kind) {
                    case 246 /* ImportEqualsDeclaration */:
                        return parent.name === node && isExternalModuleImportEquals(parent)
                            ? { isNamedImport: false }
                            : undefined;
                    case 251 /* ImportSpecifier */:
                        // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
                        return parent.propertyName ? undefined : { isNamedImport: true };
                    case 248 /* ImportClause */:
                    case 249 /* NamespaceImport */:
                        ts.Debug.assert(parent.name === node);
                        return { isNamedImport: false };
                    default:
                        return undefined;
                }
            }
            function getExportInfo(exportSymbol, exportKind, checker) {
                var moduleSymbol = exportSymbol.parent;
                if (!moduleSymbol)
                    return undefined; // This can happen if an `export` is not at the top-level (which is a compile error).
                var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation.
                // `export` may appear in a namespace. In that case, just rely on global search.
                return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
            }
            FindAllReferences.getExportInfo = getExportInfo;
            /** If at an export specifier, go to the symbol it refers to. */
            function skipExportSpecifierSymbol(symbol, checker) {
                // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
                if (symbol.declarations) {
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var declaration = _a[_i];
                        if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) {
                            return checker.getExportSpecifierLocalTargetSymbol(declaration);
                        }
                    }
                }
                return symbol;
            }
            function getContainingModuleSymbol(importer, checker) {
                return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
            }
            function getSourceFileLikeForImportDeclaration(node) {
                if (node.kind === 189 /* CallExpression */) {
                    return node.getSourceFile();
                }
                var parent = node.parent;
                if (parent.kind === 277 /* SourceFile */) {
                    return parent;
                }
                ts.Debug.assert(parent.kind === 243 /* ModuleBlock */);
                return ts.cast(parent.parent, isAmbientModuleDeclaration);
            }
            function isAmbientModuleDeclaration(node) {
                return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */;
            }
            function isExternalModuleImportEquals(eq) {
                return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */;
            }
        })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var FindAllReferences;
        (function (FindAllReferences) {
            var DefinitionKind;
            (function (DefinitionKind) {
                DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol";
                DefinitionKind[DefinitionKind["Label"] = 1] = "Label";
                DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword";
                DefinitionKind[DefinitionKind["This"] = 3] = "This";
                DefinitionKind[DefinitionKind["String"] = 4] = "String";
            })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {}));
            function nodeEntry(node, isInString) {
                return { type: "node", node: node.name || node, isInString: isInString };
            }
            FindAllReferences.nodeEntry = nodeEntry;
            function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
                var node = ts.getTouchingPropertyName(sourceFile, position);
                var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken);
                var checker = program.getTypeChecker();
                return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
                    var definition = _a.definition, references = _a.references;
                    // Only include referenced symbols that have a valid definition.
                    return definition && {
                        definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }),
                        references: references.map(toReferenceEntry)
                    };
                });
            }
            FindAllReferences.findReferencedSymbols = findReferencedSymbols;
            function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) {
                var node = ts.getTouchingPropertyName(sourceFile, position);
                var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position);
                var checker = program.getTypeChecker();
                return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); });
            }
            FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
            function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
                if (node.kind === 277 /* SourceFile */) {
                    return undefined;
                }
                var checker = program.getTypeChecker();
                // If invoked directly on a shorthand property assignment, then return
                // the declaration of the symbol being assigned (not the symbol being assigned to).
                if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) {
                    var result_7 = [];
                    FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); });
                    return result_7;
                }
                else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
                    // References to and accesses on the super keyword only have one possible implementation, so no
                    // need to "Find all References"
                    var symbol = checker.getSymbolAtLocation(node);
                    return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
                }
                else {
                    // Perform "Find all References" and retrieve only those that are implementations
                    return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true });
                }
            }
            function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) {
                return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry);
            }
            FindAllReferences.findReferencedEntries = findReferencedEntries;
            function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
                if (options === void 0) {
                    options = {};
                }
                if (sourceFilesSet === void 0) {
                    sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; });
                }
                return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
            }
            FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
            function flattenEntries(referenceSymbols) {
                return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
            }
            function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
                var info = (function () {
                    switch (def.type) {
                        case 0 /* Symbol */: {
                            var symbol = def.symbol;
                            var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
                            var name_3 = displayParts_1.map(function (p) { return p.text; }).join("");
                            return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 };
                        }
                        case 1 /* Label */: {
                            var node_3 = def.node;
                            return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
                        }
                        case 2 /* Keyword */: {
                            var node_4 = def.node;
                            var name_4 = ts.tokenToString(node_4.kind);
                            return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] };
                        }
                        case 3 /* This */: {
                            var node_5 = def.node;
                            var symbol = checker.getSymbolAtLocation(node_5);
                            var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
                            return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
                        }
                        case 4 /* String */: {
                            var node_6 = def.node;
                            return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
                        }
                        default:
                            return ts.Debug.assertNever(def);
                    }
                })();
                var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts;
                var sourceFile = node.getSourceFile();
                return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile), displayParts: displayParts };
            }
            function getDefinitionKindAndDisplayParts(symbol, checker, node) {
                var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol);
                var enclosingDeclaration = ts.firstOrUndefined(symbol.declarations) || node;
                var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
                return { displayParts: displayParts, kind: symbolKind };
            }
            function toReferenceEntry(entry) {
                if (entry.type === "span") {
                    return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false };
                }
                var node = entry.node, isInString = entry.isInString;
                var sourceFile = node.getSourceFile();
                return {
                    fileName: sourceFile.fileName,
                    textSpan: getTextSpan(node, sourceFile),
                    isWriteAccess: isWriteAccessForReference(node),
                    isDefinition: node.kind === 79 /* DefaultKeyword */
                        || !!ts.getDeclarationFromName(node)
                        || ts.isLiteralComputedPropertyDeclarationName(node),
                    isInString: isInString,
                };
            }
            function toImplementationLocation(entry, checker) {
                if (entry.type === "node") {
                    var node = entry.node;
                    var sourceFile = node.getSourceFile();
                    return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker));
                }
                else {
                    var textSpan = entry.textSpan, fileName = entry.fileName;
                    return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] };
                }
            }
            function implementationKindDisplayParts(node, checker) {
                var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
                if (symbol) {
                    return getDefinitionKindAndDisplayParts(symbol, checker, node);
                }
                else if (node.kind === 186 /* ObjectLiteralExpression */) {
                    return {
                        kind: "interface" /* interfaceElement */,
                        displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)]
                    };
                }
                else if (node.kind === 207 /* ClassExpression */) {
                    return {
                        kind: "local class" /* localClassElement */,
                        displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)]
                    };
                }
                else {
                    return { kind: ts.getNodeKind(node), displayParts: [] };
                }
            }
            function toHighlightSpan(entry) {
                if (entry.type === "span") {
                    var fileName = entry.fileName, textSpan = entry.textSpan;
                    return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } };
                }
                var node = entry.node, isInString = entry.isInString;
                var sourceFile = node.getSourceFile();
                var writeAccess = isWriteAccessForReference(node);
                var span = {
                    textSpan: getTextSpan(node, sourceFile),
                    kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */,
                    isInString: isInString
                };
                return { fileName: sourceFile.fileName, span: span };
            }
            FindAllReferences.toHighlightSpan = toHighlightSpan;
            function getTextSpan(node, sourceFile) {
                var start = node.getStart(sourceFile);
                var end = node.getEnd();
                if (node.kind === 9 /* StringLiteral */) {
                    start += 1;
                    end -= 1;
                }
                return ts.createTextSpanFromBounds(start, end);
            }
            /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
            function isWriteAccessForReference(node) {
                var decl = ts.getDeclarationFromName(node);
                return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node);
            }
            /**
             * True if 'decl' provides a value, as in `function f() {}`;
             * false if 'decl' is just a location for a future write, as in 'let x;'
             */
            function declarationIsWriteAccess(decl) {
                // Consider anything in an ambient declaration to be a write access since it may be coming from JS.
                if (!!(decl.flags & 4194304 /* Ambient */))
                    return true;
                switch (decl.kind) {
                    case 202 /* BinaryExpression */:
                    case 184 /* BindingElement */:
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                    case 79 /* DefaultKeyword */:
                    case 241 /* EnumDeclaration */:
                    case 276 /* EnumMember */:
                    case 255 /* ExportSpecifier */:
                    case 248 /* ImportClause */: // default import
                    case 246 /* ImportEqualsDeclaration */:
                    case 251 /* ImportSpecifier */:
                    case 239 /* InterfaceDeclaration */:
                    case 295 /* JSDocCallbackTag */:
                    case 302 /* JSDocTypedefTag */:
                    case 265 /* JsxAttribute */:
                    case 242 /* ModuleDeclaration */:
                    case 245 /* NamespaceExportDeclaration */:
                    case 249 /* NamespaceImport */:
                    case 149 /* Parameter */:
                    case 274 /* ShorthandPropertyAssignment */:
                    case 240 /* TypeAliasDeclaration */:
                    case 148 /* TypeParameter */:
                        return true;
                    case 273 /* PropertyAssignment */:
                        // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.)
                        return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent);
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 155 /* Constructor */:
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return !!decl.body;
                    case 235 /* VariableDeclaration */:
                    case 152 /* PropertyDeclaration */:
                        return !!decl.initializer || ts.isCatchClause(decl.parent);
                    case 153 /* MethodSignature */:
                    case 151 /* PropertySignature */:
                    case 303 /* JSDocPropertyTag */:
                    case 297 /* JSDocParameterTag */:
                        return false;
                    default:
                        return ts.Debug.failBadSyntaxKind(decl);
                }
            }
        })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
    })(ts || (ts = {}));
    /** Encapsulates the core find-all-references algorithm. */
    /* @internal */
    (function (ts) {
        var FindAllReferences;
        (function (FindAllReferences) {
            var Core;
            (function (Core) {
                /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
                function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
                    if (options === void 0) {
                        options = {};
                    }
                    if (sourceFilesSet === void 0) {
                        sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; });
                    }
                    if (ts.isSourceFile(node)) {
                        var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
                        var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol);
                        return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
                    }
                    if (!options.implementations) {
                        var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
                        if (special) {
                            return special;
                        }
                    }
                    var checker = program.getTypeChecker();
                    var symbol = checker.getSymbolAtLocation(node);
                    // Could not find a symbol e.g. unknown identifier
                    if (!symbol) {
                        // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
                        return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
                    }
                    var moduleReferences = ts.emptyArray;
                    var moduleSourceFile = isModuleSymbol(symbol);
                    var referencedNode = node;
                    if (moduleSourceFile) {
                        var exportEquals = symbol.exports.get("export=" /* ExportEquals */);
                        // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
                        moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
                        if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
                            return moduleReferences;
                        // Continue to get references to 'export ='.
                        symbol = ts.skipAlias(exportEquals, checker);
                        referencedNode = undefined;
                    }
                    return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
                }
                Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
                function isModuleSymbol(symbol) {
                    return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined;
                }
                function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
                    ts.Debug.assert(!!symbol.valueDeclaration);
                    var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) {
                        if (reference.kind === "import") {
                            var parent = reference.literal.parent;
                            if (ts.isLiteralTypeNode(parent)) {
                                var importType = ts.cast(parent.parent, ts.isImportTypeNode);
                                if (excludeImportTypeOfExportEquals && !importType.qualifier) {
                                    return undefined;
                                }
                            }
                            // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway.
                            return { type: "node", node: reference.literal };
                        }
                        else {
                            return {
                                type: "span",
                                fileName: reference.referencingFile.fileName,
                                textSpan: ts.createTextSpanFromRange(reference.ref),
                            };
                        }
                    });
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        switch (decl.kind) {
                            case 277 /* SourceFile */:
                                // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
                                break;
                            case 242 /* ModuleDeclaration */:
                                if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
                                    references.push({ type: "node", node: decl.name });
                                }
                                break;
                            default:
                                // This may be merged with something.
                                ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
                        }
                    }
                    return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray;
                }
                /** getReferencedSymbols for special node kinds. */
                function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
                    if (ts.isTypeKeyword(node.kind)) {
                        return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken);
                    }
                    // Labels
                    if (ts.isJumpStatementTarget(node)) {
                        var labelDefinition = ts.getTargetLabel(node.parent, node.text);
                        // if we have a label definition, look within its statement for references, if not, then
                        // the label is undefined and we have no results..
                        return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
                    }
                    else if (ts.isLabelOfLabeledStatement(node)) {
                        // it is a label definition and not a target, search within the parent labeledStatement
                        return getLabelReferencesInNode(node.parent, node);
                    }
                    if (ts.isThis(node)) {
                        return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
                    }
                    if (node.kind === 97 /* SuperKeyword */) {
                        return getReferencesForSuperKeyword(node);
                    }
                    return undefined;
                }
                /** Core find-all-references algorithm for a normal symbol. */
                function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
                    symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
                    // Compute the meaning from the location and the symbol it references
                    var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
                    var result = [];
                    var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
                    if (node && node.kind === 79 /* DefaultKeyword */) {
                        addReference(node, symbol, state);
                        searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
                    }
                    else {
                        var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] });
                        // Try to get the smallest valid scope that we can limit our search to;
                        // otherwise we'll need to search globally (i.e. include each file).
                        var scope = getSymbolScope(symbol);
                        if (scope) {
                            getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope)));
                        }
                        else {
                            // Global search
                            for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) {
                                var sourceFile = _a[_i];
                                state.cancellationToken.throwIfCancellationRequested();
                                searchForName(sourceFile, search, state);
                            }
                        }
                    }
                    return result;
                }
                function getSpecialSearchKind(node) {
                    switch (node.kind) {
                        case 123 /* ConstructorKeyword */:
                            return 1 /* Constructor */;
                        case 71 /* Identifier */:
                            if (ts.isClassLike(node.parent)) {
                                ts.Debug.assert(node.parent.name === node);
                                return 2 /* Class */;
                            }
                        // falls through
                        default:
                            return 0 /* None */;
                    }
                }
                /** Handle a few special cases relating to export/import specifiers. */
                function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) {
                    var parent = node.parent;
                    if (ts.isExportSpecifier(parent)) {
                        return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
                    }
                    if (ts.isImportSpecifier(parent) && parent.propertyName === node) {
                        // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import.
                        return checker.getImmediateAliasedSymbol(symbol);
                    }
                    // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
                    return ts.firstDefined(symbol.declarations, function (decl) {
                        if (!decl.parent) {
                            // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
                            ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol));
                        }
                        return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
                            ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name)
                            : undefined;
                    });
                }
                var SpecialSearchKind;
                (function (SpecialSearchKind) {
                    SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None";
                    SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor";
                    SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class";
                })(SpecialSearchKind || (SpecialSearchKind = {}));
                /**
                 * Holds all state needed for the finding references.
                 * Unlike `Search`, there is only one `State`.
                 */
                var State = /** @class */ (function () {
                    function State(sourceFiles, sourceFilesSet, 
                    /** True if we're searching for constructor references. */
                    specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
                        this.sourceFiles = sourceFiles;
                        this.sourceFilesSet = sourceFilesSet;
                        this.specialSearchKind = specialSearchKind;
                        this.checker = checker;
                        this.cancellationToken = cancellationToken;
                        this.searchMeaning = searchMeaning;
                        this.options = options;
                        this.result = result;
                        /** Cache for `explicitlyinheritsFrom`. */
                        this.inheritsFromCache = ts.createMap();
                        /**
                         * Type nodes can contain multiple references to the same type. For example:
                         *      let x: Foo & (Foo & Bar) = ...
                         * Because we are returning the implementation locations and not the identifier locations,
                         * duplicate entries would be returned here as each of the type references is part of
                         * the same implementation. For that reason, check before we add a new entry.
                         */
                        this.markSeenContainingTypeReference = ts.nodeSeenTracker();
                        /**
                         * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
                         * For example:
                         *     // b.ts
                         *     export { foo as bar } from "./a";
                         *     import { bar } from "./b";
                         *
                         * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local).
                         * But another reference to it may appear in the same source file.
                         * See `tests/cases/fourslash/transitiveExportImports3.ts`.
                         */
                        this.markSeenReExportRHS = ts.nodeSeenTracker();
                        this.symbolIdToReferences = [];
                        // Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
                        this.sourceFileToSeenSymbols = [];
                    }
                    State.prototype.includesSourceFile = function (sourceFile) {
                        return this.sourceFilesSet.has(sourceFile.fileName);
                    };
                    /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
                    State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
                        if (!this.importTracker)
                            this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
                        return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename);
                    };
                    /** @param allSearchSymbols set of additional symbols for use by `includes`. */
                    State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) {
                        if (searchOptions === void 0) {
                            searchOptions = {};
                        }
                        // Note: if this is an external module symbol, the name doesn't include quotes.
                        // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`.
                        // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
                        // here appears to be intentional).
                        var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b;
                        var escapedText = ts.escapeLeadingUnderscores(text);
                        var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined;
                        return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } };
                    };
                    /**
                     * Callback to add references for a particular searched symbol.
                     * This initializes a reference group, so only call this if you will add at least one reference.
                     */
                    State.prototype.referenceAdder = function (searchSymbol) {
                        var symbolId = ts.getSymbolId(searchSymbol);
                        var references = this.symbolIdToReferences[symbolId];
                        if (!references) {
                            references = this.symbolIdToReferences[symbolId] = [];
                            this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references });
                        }
                        return function (node) { return references.push(FindAllReferences.nodeEntry(node)); };
                    };
                    /** Add a reference with no associated definition. */
                    State.prototype.addStringOrCommentReference = function (fileName, textSpan) {
                        this.result.push({
                            definition: undefined,
                            references: [{ type: "span", fileName: fileName, textSpan: textSpan }]
                        });
                    };
                    /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
                    State.prototype.markSearchedSymbols = function (sourceFile, symbols) {
                        var sourceId = ts.getNodeId(sourceFile);
                        var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
                        var anyNewSymbols = false;
                        for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
                            var sym = symbols_4[_i];
                            anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
                        }
                        return anyNewSymbols;
                    };
                    return State;
                }());
                /** Search for all imports of a given exported symbol using `State.getImportSearches`. */
                function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
                    var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
                    // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
                    if (singleReferences.length) {
                        var addRef = state.referenceAdder(exportSymbol);
                        for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
                            var singleRef = singleReferences_1[_i];
                            if (shouldAddSingleReference(singleRef, state))
                                addRef(singleRef);
                        }
                    }
                    // For each import, find all references to that import in its source file.
                    for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) {
                        var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1];
                        getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state);
                    }
                    if (indirectUsers.length) {
                        var indirectSearch = void 0;
                        switch (exportInfo.exportKind) {
                            case 0 /* Named */:
                                indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */);
                                break;
                            case 1 /* Default */:
                                // Search for a property access to '.default'. This can't be renamed.
                                indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" });
                                break;
                            case 2 /* ExportEquals */:
                                break;
                        }
                        if (indirectSearch) {
                            for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) {
                                var indirectUser = indirectUsers_1[_d];
                                searchForName(indirectUser, indirectSearch, state);
                            }
                        }
                    }
                }
                function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) {
                    var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken);
                    var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers;
                    for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) {
                        var importLocation = importSearches_2[_i][0];
                        cb(importLocation);
                    }
                    for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) {
                        var indirectUser = indirectUsers_2[_b];
                        for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
                            var node = _d[_c];
                            if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) {
                                cb(node);
                            }
                        }
                    }
                }
                Core.eachExportReference = eachExportReference;
                function shouldAddSingleReference(singleRef, state) {
                    if (!hasMatchingMeaning(singleRef, state))
                        return false;
                    if (!state.options.isForRename)
                        return true;
                    // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;`
                    if (!ts.isIdentifier(singleRef))
                        return false;
                    // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
                    return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
                }
                // Go to the symbol we imported from and find references for it.
                function searchForImportedSymbol(symbol, state) {
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var declaration = _a[_i];
                        var exportingFile = declaration.getSourceFile();
                        // Need to search in the file even if it's not in the search-file set, because it might export the symbol.
                        getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile));
                    }
                }
                /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
                function searchForName(sourceFile, search, state) {
                    if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) {
                        getReferencesInSourceFile(sourceFile, search, state);
                    }
                }
                function getPropertySymbolOfDestructuringAssignment(location, checker) {
                    return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent)
                        ? checker.getPropertySymbolOfDestructuringAssignment(location)
                        : undefined;
                }
                function getObjectBindingElementWithoutPropertyName(symbol) {
                    var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */);
                    if (bindingElement &&
                        bindingElement.parent.kind === 182 /* ObjectBindingPattern */ &&
                        ts.isIdentifier(bindingElement.name) &&
                        !bindingElement.propertyName) {
                        return bindingElement;
                    }
                }
                function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
                    var bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
                    return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement);
                }
                /**
                 * Determines the smallest scope in which a symbol may have named references.
                 * Note that not every construct has been accounted for. This function can
                 * probably be improved.
                 *
                 * @returns undefined if the scope cannot be determined, implying that
                 * a reference to a symbol can occur anywhere.
                 */
                function getSymbolScope(symbol) {
                    // If this is the symbol of a named function expression or named class expression,
                    // then named references are limited to its own scope.
                    var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration;
                    if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) {
                        return valueDeclaration;
                    }
                    if (!declarations) {
                        return undefined;
                    }
                    // If this is private property or method, the scope is the containing class
                    if (flags & (4 /* Property */ | 8192 /* Method */)) {
                        var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); });
                        if (privateDeclaration) {
                            return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */);
                        }
                        // Else this is a public property and could be accessed from anywhere.
                        return undefined;
                    }
                    // If symbol is of object binding pattern element without property name we would want to
                    // look for property too and that could be anywhere
                    if (getObjectBindingElementWithoutPropertyName(symbol)) {
                        return undefined;
                    }
                    /*
                    If the symbol has a parent, it's globally visible unless:
                    - It's a private property (handled above).
                    - It's a type parameter.
                    - The parent is an external module: then we should only search in the module (and recurse on the export later).
                      - But if the parent has `export as namespace`, the symbol is globally visible through that namespace.
                    */
                    var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */);
                    if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) {
                        return undefined;
                    }
                    var scope;
                    for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
                        var declaration = declarations_11[_i];
                        var container = ts.getContainerNode(declaration);
                        if (scope && scope !== container) {
                            // Different declarations have different containers, bail out
                            return undefined;
                        }
                        if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
                            // This is a global variable and not an external module, any declaration defined
                            // within this scope is visible outside the file
                            return undefined;
                        }
                        // The search scope is the container node
                        scope = container;
                    }
                    // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.)
                    // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.:
                    //     declare module "a" { export type T = number; }
                    //     declare module "b" { import { T } from "a"; export const x: T; }
                    // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
                    return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217
                }
                /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
                function isSymbolReferencedInFile(definition, checker, sourceFile) {
                    return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false;
                }
                Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
                function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) {
                    var symbol = checker.getSymbolAtLocation(definition);
                    if (!symbol)
                        return undefined;
                    for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) {
                        var token = _a[_i];
                        if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText)
                            continue;
                        var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary
                        if (referenceSymbol === symbol
                            || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol
                            || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) {
                            var res = cb(token);
                            if (res)
                                return res;
                        }
                    }
                }
                Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
                function eachSignatureCall(signature, sourceFiles, checker, cb) {
                    if (!signature.name || !ts.isIdentifier(signature.name))
                        return;
                    var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
                    for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
                        var sourceFile = sourceFiles_5[_i];
                        for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
                            var name = _b[_a];
                            if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
                                continue;
                            var called = ts.climbPastPropertyAccess(name);
                            var call = called.parent;
                            if (!ts.isCallExpression(call) || call.expression !== called)
                                continue;
                            var referenceSymbol = checker.getSymbolAtLocation(name);
                            if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) {
                                cb(call);
                            }
                        }
                    }
                }
                Core.eachSignatureCall = eachSignatureCall;
                function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) {
                    if (container === void 0) {
                        container = sourceFile;
                    }
                    return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); });
                }
                function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
                    if (container === void 0) {
                        container = sourceFile;
                    }
                    var positions = [];
                    /// TODO: Cache symbol existence for files to save text search
                    // Also, need to make this work for unicode escapes.
                    // Be resilient in the face of a symbol with no name or zero length name
                    if (!symbolName || !symbolName.length) {
                        return positions;
                    }
                    var text = sourceFile.text;
                    var sourceLength = text.length;
                    var symbolNameLength = symbolName.length;
                    var position = text.indexOf(symbolName, container.pos);
                    while (position >= 0) {
                        // If we are past the end, stop looking
                        if (position > container.end)
                            break;
                        // We found a match.  Make sure it's not part of a larger word (i.e. the char
                        // before and after it have to be a non-identifier char).
                        var endPosition = position + symbolNameLength;
                        if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) &&
                            (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) {
                            // Found a real match.  Keep searching.
                            positions.push(position);
                        }
                        position = text.indexOf(symbolName, position + symbolNameLength + 1);
                    }
                    return positions;
                }
                function getLabelReferencesInNode(container, targetLabel) {
                    var sourceFile = container.getSourceFile();
                    var labelName = targetLabel.text;
                    var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) {
                        // Only pick labels that are either the target label, or have a target that is the target label
                        return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined;
                    });
                    return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }];
                }
                function isValidReferencePosition(node, searchSymbolName) {
                    // Compare the length so we filter out strict superstrings of the symbol we are looking for
                    switch (node.kind) {
                        case 71 /* Identifier */:
                            return node.text.length === searchSymbolName.length;
                        case 9 /* StringLiteral */: {
                            var str = node;
                            return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) &&
                                str.text.length === searchSymbolName.length;
                        }
                        case 8 /* NumericLiteral */:
                            return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length;
                        case 79 /* DefaultKeyword */:
                            return "default".length === searchSymbolName.length;
                        default:
                            return false;
                    }
                }
                function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) {
                    var references = ts.flatMap(sourceFiles, function (sourceFile) {
                        cancellationToken.throwIfCancellationRequested();
                        return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) {
                            return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined;
                        });
                    });
                    return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined;
                }
                function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) {
                    if (addReferencesHere === void 0) {
                        addReferencesHere = true;
                    }
                    state.cancellationToken.throwIfCancellationRequested();
                    return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere);
                }
                /**
                 * Search within node "container" for references for a search value, where the search value is defined as a
                 * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
                 * searchLocation: a node where the search value
                 */
                function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) {
                    if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) {
                        return;
                    }
                    for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) {
                        var position = _a[_i];
                        getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
                    }
                }
                function hasMatchingMeaning(referenceLocation, state) {
                    return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
                }
                function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
                    var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
                    if (!isValidReferencePosition(referenceLocation, search.text)) {
                        // This wasn't the start of a token.  Check to see if it might be a
                        // match in a comment or string if that's what the caller is asking
                        // for.
                        if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) {
                            // In the case where we're looking inside comments/strings, we don't have
                            // an actual definition.  So just use 'undefined' here.  Features like
                            // 'Rename' won't care (as they ignore the definitions), and features like
                            // 'FindReferences' will just filter out these results.
                            state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length));
                        }
                        return;
                    }
                    if (!hasMatchingMeaning(referenceLocation, state))
                        return;
                    var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
                    if (!referenceSymbol) {
                        return;
                    }
                    var parent = referenceLocation.parent;
                    if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) {
                        // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again.
                        return;
                    }
                    if (ts.isExportSpecifier(parent)) {
                        ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */);
                        getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere);
                        return;
                    }
                    var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
                    if (!relatedSymbol) {
                        getReferenceForShorthandProperty(referenceSymbol, search, state);
                        return;
                    }
                    switch (state.specialSearchKind) {
                        case 0 /* None */:
                            if (addReferencesHere)
                                addReference(referenceLocation, relatedSymbol, state);
                            break;
                        case 1 /* Constructor */:
                            addConstructorReferences(referenceLocation, sourceFile, search, state);
                            break;
                        case 2 /* Class */:
                            addClassStaticThisReferences(referenceLocation, search, state);
                            break;
                        default:
                            ts.Debug.assertNever(state.specialSearchKind);
                    }
                    getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
                }
                function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) {
                    var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
                    var exportDeclaration = parent.parent;
                    var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
                    if (!search.includes(localSymbol)) {
                        return;
                    }
                    if (!propertyName) {
                        // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
                        if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) {
                            addRef();
                        }
                    }
                    else if (referenceLocation === propertyName) {
                        // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export.
                        // For `export { foo as bar };`, where `foo` is a local, so add it now.
                        if (!exportDeclaration.moduleSpecifier) {
                            addRef();
                        }
                        if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) {
                            addReference(name, referenceSymbol, state);
                        }
                    }
                    else {
                        if (state.markSeenReExportRHS(referenceLocation)) {
                            addRef();
                        }
                    }
                    // For `export { foo as bar }`, rename `foo`, but not `bar`.
                    if (!(referenceLocation === propertyName && state.options.isForRename)) {
                        var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
                        var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker);
                        if (!exportInfo)
                            return ts.Debug.fail();
                        searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state);
                    }
                    // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
                    if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) {
                        var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
                        if (imported)
                            searchForImportedSymbol(imported, state);
                    }
                    function addRef() {
                        if (addReferencesHere)
                            addReference(referenceLocation, localSymbol, state);
                    }
                }
                function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
                    return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol;
                }
                function isExportSpecifierAlias(referenceLocation, exportSpecifier) {
                    var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
                    ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation);
                    if (propertyName) {
                        // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol.
                        return propertyName === referenceLocation;
                    }
                    else {
                        // `export { foo } from "foo"` is a re-export.
                        // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`.
                        return !parent.parent.moduleSpecifier;
                    }
                }
                function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) {
                    var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */);
                    if (!importOrExport)
                        return;
                    var symbol = importOrExport.symbol;
                    if (importOrExport.kind === 0 /* Import */) {
                        if (!state.options.isForRename || importOrExport.isNamedImport) {
                            searchForImportedSymbol(symbol, state);
                        }
                    }
                    else {
                        // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching.
                        searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
                    }
                }
                function getReferenceForShorthandProperty(_a, search, state) {
                    var flags = _a.flags, valueDeclaration = _a.valueDeclaration;
                    var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
                    var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration);
                    /*
                     * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
                     * has two meanings: property name and property value. Therefore when we do findAllReference at the position where
                     * an identifier is declared, the language service should return the position of the variable declaration as well as
                     * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the
                     * position of property accessing, the referenceEntry of such position will be handled in the first case.
                     */
                    if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) {
                        addReference(name, shorthandValueSymbol, state);
                    }
                }
                function addReference(referenceLocation, relatedSymbol, state) {
                    var addRef = state.referenceAdder(relatedSymbol);
                    if (state.options.implementations) {
                        addImplementationReferences(referenceLocation, addRef, state);
                    }
                    else {
                        addRef(referenceLocation);
                    }
                }
                /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses.  */
                function addConstructorReferences(referenceLocation, sourceFile, search, state) {
                    if (ts.isNewExpressionTarget(referenceLocation)) {
                        addReference(referenceLocation, search.symbol, state);
                    }
                    var pusher = function () { return state.referenceAdder(search.symbol); };
                    if (ts.isClassLike(referenceLocation.parent)) {
                        ts.Debug.assert(referenceLocation.kind === 79 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
                        // This is the class declaration containing the constructor.
                        findOwnConstructorReferences(search.symbol, sourceFile, pusher());
                    }
                    else {
                        // If this class appears in `extends C`, then the extending class' "super" calls are references.
                        var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
                        if (classExtending) {
                            findSuperConstructorAccesses(classExtending, pusher());
                        }
                    }
                }
                function addClassStaticThisReferences(referenceLocation, search, state) {
                    addReference(referenceLocation, search.symbol, state);
                    var classLike = referenceLocation.parent;
                    if (state.options.isForRename || !ts.isClassLike(classLike))
                        return;
                    ts.Debug.assert(classLike.name === referenceLocation);
                    var addRef = state.referenceAdder(search.symbol);
                    for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) {
                        var member = _a[_i];
                        if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) {
                            continue;
                        }
                        if (member.body) {
                            member.body.forEachChild(function cb(node) {
                                if (node.kind === 99 /* ThisKeyword */) {
                                    addRef(node);
                                }
                                else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
                                    node.forEachChild(cb);
                                }
                            });
                        }
                    }
                }
                /**
                 * `classSymbol` is the class where the constructor was defined.
                 * Reference the constructor and all calls to `new this()`.
                 */
                function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
                    for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile);
                        ts.Debug.assert(decl.kind === 155 /* Constructor */ && !!ctrKeyword);
                        addNode(ctrKeyword);
                    }
                    classSymbol.exports.forEach(function (member) {
                        var decl = member.valueDeclaration;
                        if (decl && decl.kind === 154 /* MethodDeclaration */) {
                            var body = decl.body;
                            if (body) {
                                forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) {
                                    if (ts.isNewExpressionTarget(thisKeyword)) {
                                        addNode(thisKeyword);
                                    }
                                });
                            }
                        }
                    });
                }
                /** Find references to `super` in the constructor of an extending class.  */
                function findSuperConstructorAccesses(cls, addNode) {
                    var ctr = cls.symbol.members.get("__constructor" /* Constructor */);
                    if (!ctr) {
                        return;
                    }
                    for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        ts.Debug.assert(decl.kind === 155 /* Constructor */);
                        var body = decl.body;
                        if (body) {
                            forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) {
                                if (ts.isCallExpressionTarget(node)) {
                                    addNode(node);
                                }
                            });
                        }
                    }
                }
                function addImplementationReferences(refNode, addReference, state) {
                    // Check if we found a function/propertyAssignment/method with an implementation or initializer
                    if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
                        addReference(refNode);
                        return;
                    }
                    if (refNode.kind !== 71 /* Identifier */) {
                        return;
                    }
                    if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) {
                        // Go ahead and dereference the shorthand assignment by going to its definition
                        getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference);
                    }
                    // Check if the node is within an extends or implements clause
                    var containingClass = getContainingClassIfInHeritageClause(refNode);
                    if (containingClass) {
                        addReference(containingClass);
                        return;
                    }
                    // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface
                    // Find the first node whose parent isn't a type node -- i.e., the highest type node.
                    var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); });
                    var typeHavingNode = typeNode.parent;
                    if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) {
                        if (ts.hasInitializer(typeHavingNode)) {
                            addIfImplementation(typeHavingNode.initializer);
                        }
                        else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) {
                            var body = typeHavingNode.body;
                            if (body.kind === 216 /* Block */) {
                                ts.forEachReturnStatement(body, function (returnStatement) {
                                    if (returnStatement.expression)
                                        addIfImplementation(returnStatement.expression);
                                });
                            }
                            else {
                                addIfImplementation(body);
                            }
                        }
                        else if (ts.isAssertionExpression(typeHavingNode)) {
                            addIfImplementation(typeHavingNode.expression);
                        }
                    }
                    function addIfImplementation(e) {
                        if (isImplementationExpression(e))
                            addReference(e);
                    }
                }
                function getContainingClassIfInHeritageClause(node) {
                    return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent)
                        : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined;
                }
                /**
                 * Returns true if this is an expression that can be considered an implementation
                 */
                function isImplementationExpression(node) {
                    switch (node.kind) {
                        case 193 /* ParenthesizedExpression */:
                            return isImplementationExpression(node.expression);
                        case 195 /* ArrowFunction */:
                        case 194 /* FunctionExpression */:
                        case 186 /* ObjectLiteralExpression */:
                        case 207 /* ClassExpression */:
                        case 185 /* ArrayLiteralExpression */:
                            return true;
                        default:
                            return false;
                    }
                }
                /**
                 * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol
                 * is an interface, determines if some ancestor of the child symbol extends or inherits from it.
                 * Also takes in a cache of previous results which makes this slightly more efficient and is
                 * necessary to avoid potential loops like so:
                 *     class A extends B { }
                 *     class B extends A { }
                 *
                 * We traverse the AST rather than using the type checker because users are typically only interested
                 * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling
                 * implementations of types that share a common ancestor with the type whose implementation we are
                 * searching for need to be filtered out of the results. The type checker doesn't let us make the
                 * distinction between structurally compatible implementations and explicit implementations, so we
                 * must use the AST.
                 *
                 * @param symbol         A class or interface Symbol
                 * @param parent        Another class or interface Symbol
                 * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results
                 */
                function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) {
                    if (symbol === parent) {
                        return true;
                    }
                    var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent);
                    var cached = cachedResults.get(key);
                    if (cached !== undefined) {
                        return cached;
                    }
                    // Set the key so that we don't infinitely recurse
                    cachedResults.set(key, false);
                    var inherits = symbol.declarations.some(function (declaration) {
                        return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) {
                            var type = checker.getTypeAtLocation(typeReference);
                            return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker);
                        });
                    });
                    cachedResults.set(key, inherits);
                    return inherits;
                }
                function getReferencesForSuperKeyword(superKeyword) {
                    var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false);
                    if (!searchSpaceNode) {
                        return undefined;
                    }
                    // Whether 'super' occurs in a static context within a class.
                    var staticFlag = 32 /* Static */;
                    switch (searchSpaceNode.kind) {
                        case 152 /* PropertyDeclaration */:
                        case 151 /* PropertySignature */:
                        case 154 /* MethodDeclaration */:
                        case 153 /* MethodSignature */:
                        case 155 /* Constructor */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            staticFlag &= ts.getModifierFlags(searchSpaceNode);
                            searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
                            break;
                        default:
                            return undefined;
                    }
                    var sourceFile = searchSpaceNode.getSourceFile();
                    var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) {
                        if (node.kind !== 97 /* SuperKeyword */) {
                            return;
                        }
                        var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
                        // If we have a 'super' container, we must have an enclosing class.
                        // Now make sure the owning class is the same as the search-space
                        // and has the same static qualifier as the original 'super's owner.
                        return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined;
                    });
                    return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }];
                }
                function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
                    var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
                    // Whether 'this' occurs in a static context within a class.
                    var staticFlag = 32 /* Static */;
                    switch (searchSpaceNode.kind) {
                        case 154 /* MethodDeclaration */:
                        case 153 /* MethodSignature */:
                            if (ts.isObjectLiteralMethod(searchSpaceNode)) {
                                break;
                            }
                        // falls through
                        case 152 /* PropertyDeclaration */:
                        case 151 /* PropertySignature */:
                        case 155 /* Constructor */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            staticFlag &= ts.getModifierFlags(searchSpaceNode);
                            searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
                            break;
                        case 277 /* SourceFile */:
                            if (ts.isExternalModule(searchSpaceNode)) {
                                return undefined;
                            }
                        // falls through
                        case 237 /* FunctionDeclaration */:
                        case 194 /* FunctionExpression */:
                            break;
                        // Computed properties in classes are not handled here because references to this are illegal,
                        // so there is no point finding references to them.
                        default:
                            return undefined;
                    }
                    var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
                        cancellationToken.throwIfCancellationRequested();
                        return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
                            if (!ts.isThis(node)) {
                                return false;
                            }
                            var container = ts.getThisContainer(node, /* includeArrowFunctions */ false);
                            switch (searchSpaceNode.kind) {
                                case 194 /* FunctionExpression */:
                                case 237 /* FunctionDeclaration */:
                                    return searchSpaceNode.symbol === container.symbol;
                                case 154 /* MethodDeclaration */:
                                case 153 /* MethodSignature */:
                                    return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol;
                                case 207 /* ClassExpression */:
                                case 238 /* ClassDeclaration */:
                                    // Make sure the container belongs to the same class
                                    // and has the appropriate static modifier from the original container.
                                    return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
                                case 277 /* SourceFile */:
                                    return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container);
                            }
                        });
                    }).map(function (n) { return FindAllReferences.nodeEntry(n); });
                    var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; });
                    return [{
                            definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword },
                            references: references
                        }];
                }
                function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
                    var references = ts.flatMap(sourceFiles, function (sourceFile) {
                        cancellationToken.throwIfCancellationRequested();
                        return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) {
                            return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined;
                        });
                    });
                    return [{
                            definition: { type: 4 /* String */, node: node },
                            references: references
                        }];
                }
                // For certain symbol kinds, we need to include other symbols in the search set.
                // This is not needed when searching for re-exports.
                function populateSearchSymbolSet(symbol, location, checker, implementations) {
                    var result = [];
                    forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, 
                    /*allowBaseTypes*/ function () { return !implementations; });
                    return result;
                }
                function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) {
                    var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location);
                    if (containingObjectLiteralElement) {
                        // If the location is in a context sensitive location (i.e. in an object literal) try
                        // to get a contextual type for it, and add the property symbol from the contextual
                        // type to the search set
                        var contextualType = checker.getContextualType(containingObjectLiteralElement.parent);
                        var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot);
                        if (res_1)
                            return res_1;
                        // If the location is name of property symbol from object literal destructuring pattern
                        // Search the property symbol
                        //      for ( { property: p2 } of elems) { }
                        var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker);
                        var res1 = propertySymbol && cbSymbol(propertySymbol);
                        if (res1)
                            return res1;
                        /* Because in short-hand property assignment, location has two meaning : property name and as value of the property
                         * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of
                         * property name and variable declaration of the identifier.
                         * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service
                         * should show both 'name' in 'obj' and 'name' in variable declaration
                         *      const name = "Foo";
                         *      const obj = { name };
                         * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment
                         * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration
                         * will be included correctly.
                         */
                        var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent);
                        var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol);
                        if (res2)
                            return res2;
                    }
                    var res = fromRoot(symbol);
                    if (res)
                        return res;
                    if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) {
                        // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property).
                        var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name);
                        ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property]
                        return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]);
                    }
                    // If this is symbol of binding element without propertyName declaration in Object binding pattern
                    // Include the property in the search
                    var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
                    return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol);
                    function fromRoot(sym) {
                        // If this is a union property:
                        //   - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types.
                        //   - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search.
                        // If the symbol is an instantiation from a another symbol (e.g. widened symbol):
                        //   - In populateSearchSymbolsSet, add the root the list
                        //   - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.)
                        return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) {
                            return cbSymbol(sym, rootSymbol)
                                // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
                                || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol)
                                    ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); })
                                    : undefined);
                        });
                    }
                }
                function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) {
                    var checker = state.checker;
                    return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) {
                        return search.includes(baseSymbol || rootSymbol || sym)
                            // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol.
                            ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym
                            : undefined;
                    }, 
                    /*allowBaseTypes*/ function (rootSymbol) {
                        return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); }));
                    });
                }
                /**
                 * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations
                 * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class
                 * then we need to widen the search to include type positions as well.
                 * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated
                 * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
                 * do not intersect in any of the three spaces.
                 */
                function getIntersectingMeaningFromDeclarations(node, symbol) {
                    var meaning = ts.getMeaningFromLocation(node);
                    var declarations = symbol.declarations;
                    if (declarations) {
                        var lastIterationMeaning = void 0;
                        do {
                            // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module]
                            // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module
                            // intersects with the class in the value space.
                            // To achieve that we will keep iterating until the result stabilizes.
                            // Remember the last meaning
                            lastIterationMeaning = meaning;
                            for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
                                var declaration = declarations_12[_i];
                                var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
                                if (declarationMeaning & meaning) {
                                    meaning |= declarationMeaning;
                                }
                            }
                        } while (meaning !== lastIterationMeaning);
                    }
                    return meaning;
                }
                Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
                function isImplementation(node) {
                    return !!(node.flags & 4194304 /* Ambient */)
                        || (ts.isVariableLike(node) ? ts.hasInitializer(node)
                            : ts.isFunctionLikeDeclaration(node) ? !!node.body
                                : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node));
                }
                function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) {
                    var refSymbol = checker.getSymbolAtLocation(node);
                    var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
                    if (shorthandSymbol) {
                        for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) {
                            var declaration = _a[_i];
                            if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) {
                                addReference(declaration);
                            }
                        }
                    }
                }
                Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
                function forEachDescendantOfKind(node, kind, action) {
                    ts.forEachChild(node, function (child) {
                        if (child.kind === kind) {
                            action(child);
                        }
                        forEachDescendantOfKind(child, kind, action);
                    });
                }
                /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */
                function tryGetClassByExtendingIdentifier(node) {
                    return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent);
                }
                /**
                 * If we are just looking for implementations and this is a property access expression, we need to get the
                 * symbol of the local type of the symbol the property is being accessed on. This is because our search
                 * symbol may have a different parent symbol if the local type's symbol does not declare the property
                 * being accessed (i.e. it is declared in some parent class or interface)
                 */
                function getParentSymbolsOfPropertyAccess(location, symbol, checker) {
                    var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined;
                    var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression);
                    var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) {
                        return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined;
                    });
                    return res.length === 0 ? undefined : res;
                }
            })(Core = FindAllReferences.Core || (FindAllReferences.Core = {}));
        })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) {
            var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
            var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
            var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper);
            var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
            return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
                updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames);
                updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
            });
        }
        ts.getEditsForFileRename = getEditsForFileRename;
        // exported for tests
        function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) {
            var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath);
            return function (path) {
                var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 });
                var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path);
                return originalPath
                    ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName)
                    : updatedPath;
            };
            function getUpdatedPath(pathToUpdate) {
                if (getCanonicalFileName(pathToUpdate) === canonicalOldPath)
                    return newFileOrDirPath;
                var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName);
                return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix;
            }
        }
        ts.getPathUpdater = getPathUpdater;
        // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1.
        function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) {
            var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName);
            return combinePathsSafe(ts.getDirectoryPath(a1), rel);
        }
        function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) {
            var configFile = program.getCompilerOptions().configFile;
            if (!configFile)
                return;
            var configDir = ts.getDirectoryPath(configFile.fileName);
            var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
            if (!jsonObjectLiteral)
                return;
            forEachProperty(jsonObjectLiteral, function (property, propertyName) {
                switch (propertyName) {
                    case "files":
                    case "include":
                    case "exclude": {
                        var foundExactMatch = updatePaths(property);
                        if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) {
                            var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; });
                            var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory);
                            // If there isn't some include for this, add a new one.
                            if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) {
                                changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath)));
                            }
                        }
                        break;
                    }
                    case "compilerOptions":
                        forEachProperty(property.initializer, function (property, propertyName) {
                            var option = ts.getOptionFromName(propertyName);
                            if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { // tslint:disable-line no-unnecessary-type-assertion
                                updatePaths(property);
                            }
                            else if (propertyName === "paths") {
                                forEachProperty(property.initializer, function (pathsProperty) {
                                    if (!ts.isArrayLiteralExpression(pathsProperty.initializer))
                                        return;
                                    for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) {
                                        var e = _a[_i];
                                        tryUpdateString(e);
                                    }
                                });
                            }
                        });
                        break;
                }
            });
            function updatePaths(property) {
                // Type annotation needed due to #7294
                var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
                var foundExactMatch = false;
                for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) {
                    var element = elements_5[_i];
                    foundExactMatch = tryUpdateString(element) || foundExactMatch;
                }
                return foundExactMatch;
            }
            function tryUpdateString(element) {
                if (!ts.isStringLiteral(element))
                    return false;
                var elementFileName = combinePathsSafe(configDir, element.text);
                var updated = oldToNew(elementFileName);
                if (updated !== undefined) {
                    changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated));
                    return true;
                }
                return false;
            }
            function relativePath(path) {
                return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames);
            }
        }
        function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
            var allFiles = program.getSourceFiles();
            var _loop_11 = function (sourceFile) {
                var newFromOld = oldToNew(sourceFile.path);
                var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
                var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
                var oldFromNew = newToOld(sourceFile.fileName);
                var oldImportFromPath = oldFromNew || sourceFile.fileName;
                var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath);
                var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined;
                updateImportsWorker(sourceFile, changeTracker, function (referenceText) {
                    if (!ts.pathIsRelative(referenceText))
                        return undefined;
                    var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText);
                    var newAbsolute = oldToNew(oldAbsolute);
                    return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName));
                }, function (importLiteral) {
                    var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
                    // No need to update if it's an ambient module^M
                    if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); }))
                        return undefined;
                    var toImport = oldFromNew !== undefined
                        // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
                        // TODO:GH#18217
                        ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host)
                        : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
                    // Need an update if the imported file moved, or the importing file moved and was using a relative path.
                    return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text)))
                        ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text)
                        : undefined;
                });
            };
            for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
                var sourceFile = allFiles_1[_i];
                _loop_11(sourceFile);
            }
        }
        function combineNormal(pathA, pathB) {
            return ts.normalizePath(ts.combinePaths(pathA, pathB));
        }
        function combinePathsSafe(pathA, pathB) {
            return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB));
        }
        function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) {
            if (importedModuleSymbol) {
                // `find` should succeed because we checked for ambient modules before calling this function.
                var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName;
                var newFileName = oldToNew(oldFileName);
                return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true };
            }
            else {
                var resolved = host.resolveModuleNames
                    ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName)
                    : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName);
                return getSourceFileToImportFromResolved(resolved, oldToNew, host);
            }
        }
        function getSourceFileToImportFromResolved(resolved, oldToNew, host) {
            // Search through all locations looking for a moved file, and only then test already existing files.
            // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location.
            return tryEach(tryGetNewFile) || tryEach(tryGetOldFile);
            function tryEach(cb) {
                return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb));
            }
            function tryGetNewFile(oldFileName) {
                var newFileName = oldToNew(oldFileName);
                return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217
            }
            function tryGetOldFile(oldFileName) {
                var newFileName = oldToNew(oldFileName);
                return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217
            }
        }
        function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) {
            for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162
                var ref = _a[_i];
                var updated = updateRef(ref.fileName);
                if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end))
                    changeTracker.replaceRangeWithText(sourceFile, ref, updated);
            }
            for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) {
                var importStringLiteral = _c[_b];
                var updated = updateImport(importStringLiteral);
                if (updated !== undefined && updated !== importStringLiteral.text)
                    changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated);
            }
        }
        function createStringRange(node, sourceFile) {
            return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1);
        }
        function forEachProperty(objectLiteral, cb) {
            if (!ts.isObjectLiteralExpression(objectLiteral))
                return;
            for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) {
                var property = _a[_i];
                if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) {
                    cb(property, property.name.text);
                }
            }
        }
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var GoToDefinition;
        (function (GoToDefinition) {
            function getDefinitionAtPosition(program, sourceFile, position) {
                var reference = getReferenceAtPosition(sourceFile, position, program);
                if (reference) {
                    return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)];
                }
                var node = ts.getTouchingPropertyName(sourceFile, position);
                if (node === sourceFile) {
                    return undefined;
                }
                var parent = node.parent;
                // Labels
                if (ts.isJumpStatementTarget(node)) {
                    var label = ts.getTargetLabel(node.parent, node.text);
                    return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217
                }
                var typeChecker = program.getTypeChecker();
                var symbol = getSymbol(node, typeChecker);
                // Could not find a symbol e.g. node is string or number keyword,
                // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol
                if (!symbol) {
                    return getDefinitionInfoForIndexSignatures(node, typeChecker);
                }
                var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
                // Don't go to the component constructor definition for a JSX element, just go to the component definition.
                if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) {
                    var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
                    // For a function, if this is the original function definition, return just sigInfo.
                    // If this is the original constructor definition, parent is the class.
                    if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) ||
                        // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias
                        symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) {
                        return [sigInfo];
                    }
                    else {
                        var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray;
                        // For a 'super()' call, put the signature first, else put the variable first.
                        return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]);
                    }
                }
                // Because name in short-hand property assignment has two different meanings: property name and property value,
                // using go-to-definition at such position should go to the variable declaration of the property value rather than
                // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition
                // is performed at the location of property access, we would like to go to definition of the property in the short-hand
                // assignment. This case and others are handled by the following code.
                if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) {
                    var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
                    return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : [];
                }
                // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the
                // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern
                // and return the property declaration for the referenced property.
                // For example:
                //      import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo"
                //
                //      function bar<T>(onfulfilled: (value: T) => void) { //....}
                //      interface Test {
                //          pr/*destination*/op1: number
                //      }
                //      bar<Test>(({pr/*goto*/op1})=>{});
                if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
                    (node === (parent.propertyName || parent.name))) {
                    var name_5 = ts.getNameFromPropertyName(node);
                    var type = typeChecker.getTypeAtLocation(parent.parent);
                    return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
                        var prop = t.getProperty(name_5);
                        return prop && getDefinitionFromSymbol(typeChecker, prop, node);
                    });
                }
                // If the current location we want to find its definition is in an object literal, try to get the contextual type for the
                // object literal, lookup the property symbol in the contextual type, and use this for goto-definition.
                // For example
                //      interface Props{
                //          /*first*/prop1: number
                //          prop2: boolean
                //      }
                //      function Foo(arg: Props) {}
                //      Foo( { pr/*1*/op1: 10, prop2: true })
                var element = ts.getContainingObjectLiteralElement(node);
                if (element) {
                    var contextualType = element && typeChecker.getContextualType(element.parent);
                    if (contextualType) {
                        return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) {
                            return getDefinitionFromSymbol(typeChecker, propertySymbol, node);
                        });
                    }
                }
                return getDefinitionFromSymbol(typeChecker, symbol, node);
            }
            GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition;
            /**
             * True if we should not add definitions for both the signature symbol and the definition symbol.
             * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`.
             */
            function symbolMatchesSignature(s, calledDeclaration) {
                return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent ||
                    !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol;
            }
            function getReferenceAtPosition(sourceFile, position, program) {
                var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
                if (referencePath) {
                    var file = ts.tryResolveScriptReference(program, sourceFile, referencePath);
                    return file && { fileName: referencePath.fileName, file: file };
                }
                var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
                if (typeReferenceDirective) {
                    var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
                    var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217
                    return file && { fileName: typeReferenceDirective.fileName, file: file };
                }
                var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position);
                if (libReferenceDirective) {
                    var file = program.getLibFileFromReference(libReferenceDirective);
                    return file && { fileName: libReferenceDirective.fileName, file: file };
                }
                return undefined;
            }
            GoToDefinition.getReferenceAtPosition = getReferenceAtPosition;
            /// Goto type
            function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) {
                var node = ts.getTouchingPropertyName(sourceFile, position);
                if (node === sourceFile) {
                    return undefined;
                }
                var symbol = typeChecker.getSymbolAtLocation(node);
                if (!symbol)
                    return undefined;
                var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
                var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker);
                var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node);
                // If a function returns 'void' or some other type with no definition, just return the function definition.
                return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node);
            }
            GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition;
            function definitionFromType(type, checker, node) {
                return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) {
                    return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node);
                });
            }
            function tryGetReturnTypeOfFunction(symbol, type, checker) {
                // If the type is just a function's inferred type,
                // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway.
                if (type.symbol === symbol ||
                    // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}`
                    symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) {
                    var sigs = type.getCallSignatures();
                    if (sigs.length === 1)
                        return checker.getReturnTypeOfSignature(ts.first(sigs));
                }
                return undefined;
            }
            function getDefinitionAndBoundSpan(program, sourceFile, position) {
                var definitions = getDefinitionAtPosition(program, sourceFile, position);
                if (!definitions || definitions.length === 0) {
                    return undefined;
                }
                // Check if position is on triple slash reference.
                var comment = findReferenceInPosition(sourceFile.referencedFiles, position) ||
                    findReferenceInPosition(sourceFile.typeReferenceDirectives, position) ||
                    findReferenceInPosition(sourceFile.libReferenceDirectives, position);
                if (comment) {
                    return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) };
                }
                var node = ts.getTouchingPropertyName(sourceFile, position);
                var textSpan = ts.createTextSpan(node.getStart(), node.getWidth());
                return { definitions: definitions, textSpan: textSpan };
            }
            GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan;
            // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations.
            function getDefinitionInfoForIndexSignatures(node, checker) {
                if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node)
                    return;
                var type = checker.getTypeAtLocation(node.parent.expression);
                return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) {
                    var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */);
                    return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration);
                });
            }
            function getSymbol(node, checker) {
                var symbol = checker.getSymbolAtLocation(node);
                // If this is an alias, and the request came at the declaration location
                // get the aliased symbol instead. This allows for goto def on an import e.g.
                //   import {A, B} from "mod";
                // to jump to the implementation directly.
                if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) {
                    var aliased = checker.getAliasedSymbol(symbol);
                    if (aliased.declarations) {
                        return aliased;
                    }
                }
                return symbol;
            }
            // Go to the original declaration for cases:
            //
            //   (1) when the aliased symbol was declared in the location(parent).
            //   (2) when the aliased symbol is originating from an import.
            //
            function shouldSkipAlias(node, declaration) {
                if (node.kind !== 71 /* Identifier */) {
                    return false;
                }
                if (node.parent === declaration) {
                    return true;
                }
                switch (declaration.kind) {
                    case 248 /* ImportClause */:
                    case 246 /* ImportEqualsDeclaration */:
                        return true;
                    case 251 /* ImportSpecifier */:
                        return declaration.parent.kind === 250 /* NamedImports */;
                    default:
                        return false;
                }
            }
            function getDefinitionFromSymbol(typeChecker, symbol, node) {
                return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); });
                function getConstructSignatureDefinition() {
                    // Applicable only if we are in a new expression, or we are on a constructor declaration
                    // and in either case the symbol has a construct signature definition, i.e. class
                    if (symbol.flags & 32 /* Class */ && (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */)) {
                        var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration");
                        return getSignatureDefinition(cls.members, /*selectConstructors*/ true);
                    }
                }
                function getCallSignatureDefinition() {
                    return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node)
                        ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false)
                        : undefined;
                }
                function getSignatureDefinition(signatureDeclarations, selectConstructors) {
                    if (!signatureDeclarations) {
                        return undefined;
                    }
                    var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike);
                    return declarations.length
                        ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), typeChecker, symbol, node)]
                        : undefined;
                }
            }
            /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */
            function createDefinitionInfo(declaration, checker, symbol, node) {
                var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
                var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node);
                var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : "";
                return createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName);
            }
            /** Creates a DefinitionInfo directly from the name of a declaration. */
            function createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName) {
                var name = ts.getNameOfDeclaration(declaration) || declaration;
                var sourceFile = name.getSourceFile();
                return {
                    fileName: sourceFile.fileName,
                    textSpan: ts.createTextSpanFromNode(name, sourceFile),
                    kind: symbolKind,
                    name: symbolName,
                    containerKind: undefined,
                    containerName: containerName
                };
            }
            function createDefinitionFromSignatureDeclaration(typeChecker, decl) {
                return createDefinitionInfo(decl, typeChecker, decl.symbol, decl);
            }
            function findReferenceInPosition(refs, pos) {
                return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); });
            }
            GoToDefinition.findReferenceInPosition = findReferenceInPosition;
            function getDefinitionInfoForFileReference(name, targetFileName) {
                return {
                    fileName: targetFileName,
                    textSpan: ts.createTextSpanFromBounds(0, 0),
                    kind: "script" /* scriptElement */,
                    name: name,
                    containerName: undefined,
                    containerKind: undefined,
                };
            }
            /** Returns a CallLikeExpression where `node` is the target being invoked. */
            function getAncestorCallLikeExpression(node) {
                var target = climbPastManyPropertyAccesses(node);
                var callLike = target.parent;
                return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined;
            }
            function climbPastManyPropertyAccesses(node) {
                return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node;
            }
            function tryGetSignatureDeclaration(typeChecker, node) {
                var callLike = getAncestorCallLikeExpression(node);
                var signature = callLike && typeChecker.getResolvedSignature(callLike);
                // Don't go to a function type, go to the value having that type.
                return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); });
            }
            function isConstructorLike(node) {
                switch (node.kind) {
                    case 155 /* Constructor */:
                    case 164 /* ConstructorType */:
                    case 159 /* ConstructSignature */:
                        return true;
                    default:
                        return false;
                }
            }
        })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var JsDoc;
        (function (JsDoc) {
            var jsDocTagNames = [
                "abstract",
                "access",
                "alias",
                "argument",
                "async",
                "augments",
                "author",
                "borrows",
                "callback",
                "class",
                "classdesc",
                "constant",
                "constructor",
                "constructs",
                "copyright",
                "default",
                "deprecated",
                "description",
                "emits",
                "enum",
                "event",
                "example",
                "exports",
                "extends",
                "external",
                "field",
                "file",
                "fileoverview",
                "fires",
                "function",
                "generator",
                "global",
                "hideconstructor",
                "host",
                "ignore",
                "implements",
                "inheritdoc",
                "inner",
                "instance",
                "interface",
                "kind",
                "lends",
                "license",
                "listens",
                "member",
                "memberof",
                "method",
                "mixes",
                "module",
                "name",
                "namespace",
                "override",
                "package",
                "param",
                "private",
                "property",
                "protected",
                "public",
                "readonly",
                "requires",
                "returns",
                "see",
                "since",
                "static",
                "summary",
                "template",
                "this",
                "throws",
                "todo",
                "tutorial",
                "type",
                "typedef",
                "var",
                "variation",
                "version",
                "virtual",
                "yields"
            ];
            var jsDocTagNameCompletionEntries;
            var jsDocTagCompletionEntries;
            function getJsDocCommentsFromDeclarations(declarations) {
                // Only collect doc comments from duplicate declarations once:
                // In case of a union property there might be same declaration multiple times
                // which only varies in type parameter
                // Eg. const a: Array<string> | Array<number>; a.length
                // The property length will have two declarations of property length coming
                // from Array<T> - Array<string> and Array<number>
                var documentationComment = [];
                forEachUnique(declarations, function (declaration) {
                    for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) {
                        var comment = _a[_i].comment;
                        if (comment === undefined)
                            continue;
                        if (documentationComment.length) {
                            documentationComment.push(ts.lineBreakPart());
                        }
                        documentationComment.push(ts.textPart(comment));
                    }
                });
                return documentationComment;
            }
            JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
            function getCommentHavingNodes(declaration) {
                switch (declaration.kind) {
                    case 297 /* JSDocParameterTag */:
                    case 303 /* JSDocPropertyTag */:
                        return [declaration];
                    case 295 /* JSDocCallbackTag */:
                    case 302 /* JSDocTypedefTag */:
                        return [declaration, declaration.parent];
                    default:
                        return ts.getJSDocCommentsAndTags(declaration);
                }
            }
            function getJsDocTagsFromDeclarations(declarations) {
                // Only collect doc comments from duplicate declarations once.
                var tags = [];
                forEachUnique(declarations, function (declaration) {
                    for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) {
                        var tag = _a[_i];
                        tags.push({ name: tag.tagName.text, text: getCommentText(tag) });
                    }
                });
                return tags;
            }
            JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations;
            function getCommentText(tag) {
                var comment = tag.comment;
                switch (tag.kind) {
                    case 293 /* JSDocAugmentsTag */:
                        return withNode(tag.class);
                    case 301 /* JSDocTemplateTag */:
                        return withList(tag.typeParameters);
                    case 300 /* JSDocTypeTag */:
                        return withNode(tag.typeExpression);
                    case 302 /* JSDocTypedefTag */:
                    case 295 /* JSDocCallbackTag */:
                    case 303 /* JSDocPropertyTag */:
                    case 297 /* JSDocParameterTag */:
                        var name = tag.name;
                        return name ? withNode(name) : comment;
                    default:
                        return comment;
                }
                function withNode(node) {
                    return addComment(node.getText());
                }
                function withList(list) {
                    return addComment(list.map(function (x) { return x.getText(); }).join(", "));
                }
                function addComment(s) {
                    return comment === undefined ? s : s + " " + comment;
                }
            }
            /**
             * Iterates through 'array' by index and performs the callback on each element of array until the callback
             * returns a truthy value, then returns that value.
             * If no such value is found, the callback is applied to each element of array and undefined is returned.
             */
            function forEachUnique(array, callback) {
                if (array) {
                    for (var i = 0; i < array.length; i++) {
                        if (array.indexOf(array[i]) === i) {
                            var result = callback(array[i], i);
                            if (result) {
                                return result;
                            }
                        }
                    }
                }
                return undefined;
            }
            function getJSDocTagNameCompletions() {
                return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
                    return {
                        name: tagName,
                        kind: "keyword" /* keyword */,
                        kindModifiers: "",
                        sortText: "0",
                    };
                }));
            }
            JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions;
            JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails;
            function getJSDocTagCompletions() {
                return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
                    return {
                        name: "@" + tagName,
                        kind: "keyword" /* keyword */,
                        kindModifiers: "",
                        sortText: "0"
                    };
                }));
            }
            JsDoc.getJSDocTagCompletions = getJSDocTagCompletions;
            function getJSDocTagCompletionDetails(name) {
                return {
                    name: name,
                    kind: "" /* unknown */,
                    kindModifiers: "",
                    displayParts: [ts.textPart(name)],
                    documentation: ts.emptyArray,
                    tags: undefined,
                    codeActions: undefined,
                };
            }
            JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails;
            function getJSDocParameterNameCompletions(tag) {
                if (!ts.isIdentifier(tag.name)) {
                    return ts.emptyArray;
                }
                var nameThusFar = tag.name.text;
                var jsdoc = tag.parent;
                var fn = jsdoc.parent;
                if (!ts.isFunctionLike(fn))
                    return [];
                return ts.mapDefined(fn.parameters, function (param) {
                    if (!ts.isIdentifier(param.name))
                        return undefined;
                    var name = param.name.text;
                    if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217
                        || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) {
                        return undefined;
                    }
                    return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" };
                });
            }
            JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions;
            function getJSDocParameterNameCompletionDetails(name) {
                return {
                    name: name,
                    kind: "parameter" /* parameterElement */,
                    kindModifiers: "",
                    displayParts: [ts.textPart(name)],
                    documentation: ts.emptyArray,
                    tags: undefined,
                    codeActions: undefined,
                };
            }
            JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails;
            /**
             * Checks if position points to a valid position to add JSDoc comments, and if so,
             * returns the appropriate template. Otherwise returns an empty string.
             * Valid positions are
             *      - outside of comments, statements, and expressions, and
             *      - preceding a:
             *          - function/constructor/method declaration
             *          - class declarations
             *          - variable statements
             *          - namespace declarations
             *          - interface declarations
             *          - method signatures
             *          - type alias declarations
             *
             * Hosts should ideally check that:
             * - The line is all whitespace up to 'position' before performing the insertion.
             * - If the keystroke sequence "/\*\*" induced the call, we also check that the next
             * non-whitespace character is '*', which (approximately) indicates whether we added
             * the second '*' to complete an existing (JSDoc) comment.
             * @param fileName The file in which to perform the check.
             * @param position The (character-indexed) position in the file where the check should
             * be performed.
             */
            function getDocCommentTemplateAtPosition(newLine, sourceFile, position) {
                var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
                var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc);
                if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) {
                    // Non-empty comment already exists.
                    return undefined;
                }
                var tokenStart = tokenAtPos.getStart(sourceFile);
                // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.)
                if (!existingDocComment && tokenStart < position) {
                    return undefined;
                }
                var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos);
                if (!commentOwnerInfo) {
                    return undefined;
                }
                var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters;
                if (commentOwner.getStart(sourceFile) < position) {
                    return undefined;
                }
                if (!parameters || parameters.length === 0) {
                    // if there are no parameters, just complete to a single line JSDoc comment
                    var singleLineResult = "/** */";
                    return { newText: singleLineResult, caretOffset: 3 };
                }
                var indentationStr = getIndentationStringAtPosition(sourceFile, position);
                // A doc comment consists of the following
                // * The opening comment line
                // * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
                // * the '@param'-tagged lines
                // * TODO: other tags.
                // * the closing comment line
                // * if the caret was directly in front of the object, then we add an extra line and indentation.
                var preamble = "/**" + newLine + indentationStr + " * ";
                var result = preamble + newLine +
                    parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) +
                    indentationStr + " */" +
                    (tokenStart === position ? newLine + indentationStr : "");
                return { newText: result, caretOffset: preamble.length };
            }
            JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition;
            function getIndentationStringAtPosition(sourceFile, position) {
                var text = sourceFile.text;
                var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
                var pos = lineStart;
                for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++)
                    ;
                return text.slice(lineStart, pos);
            }
            function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) {
                return parameters.map(function (_a, i) {
                    var name = _a.name, dotDotDotToken = _a.dotDotDotToken;
                    var paramName = name.kind === 71 /* Identifier */ ? name.text : "param" + i;
                    var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : "";
                    return indentationStr + " * @param " + type + paramName + newLine;
                }).join("");
            }
            function getCommentOwnerInfo(tokenAtPos) {
                return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker);
            }
            function getCommentOwnerInfoWorker(commentOwner) {
                switch (commentOwner.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 154 /* MethodDeclaration */:
                    case 155 /* Constructor */:
                    case 153 /* MethodSignature */:
                        var parameters = commentOwner.parameters;
                        return { commentOwner: commentOwner, parameters: parameters };
                    case 273 /* PropertyAssignment */:
                        return getCommentOwnerInfoWorker(commentOwner.initializer);
                    case 238 /* ClassDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 151 /* PropertySignature */:
                    case 241 /* EnumDeclaration */:
                    case 276 /* EnumMember */:
                    case 240 /* TypeAliasDeclaration */:
                        return { commentOwner: commentOwner };
                    case 217 /* VariableStatement */: {
                        var varStatement = commentOwner;
                        var varDeclarations = varStatement.declarationList.declarations;
                        var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer
                            ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer)
                            : undefined;
                        return { commentOwner: commentOwner, parameters: parameters_1 };
                    }
                    case 277 /* SourceFile */:
                        return "quit";
                    case 242 /* ModuleDeclaration */:
                        // If in walking up the tree, we hit a a nested namespace declaration,
                        // then we must be somewhere within a dotted namespace name; however we don't
                        // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
                        return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner };
                    case 202 /* BinaryExpression */: {
                        var be = commentOwner;
                        if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) {
                            return "quit";
                        }
                        var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray;
                        return { commentOwner: commentOwner, parameters: parameters_2 };
                    }
                }
            }
            /**
             * Digs into an an initializer or RHS operand of an assignment operation
             * to get the parameters of an apt signature corresponding to a
             * function expression or a class expression.
             *
             * @param rightHandSide the expression which may contain an appropriate set of parameters
             * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
             */
            function getParametersFromRightHandSideOfAssignment(rightHandSide) {
                while (rightHandSide.kind === 193 /* ParenthesizedExpression */) {
                    rightHandSide = rightHandSide.expression;
                }
                switch (rightHandSide.kind) {
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        return rightHandSide.parameters;
                    case 207 /* ClassExpression */: {
                        var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration);
                        return ctr ? ctr.parameters : ts.emptyArray;
                    }
                }
                return ts.emptyArray;
            }
        })(JsDoc = ts.JsDoc || (ts.JsDoc = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var NavigateTo;
        (function (NavigateTo) {
            function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
                var patternMatcher = ts.createPatternMatcher(searchValue);
                if (!patternMatcher)
                    return ts.emptyArray;
                var rawItems = [];
                var _loop_12 = function (sourceFile) {
                    cancellationToken.throwIfCancellationRequested();
                    if (excludeDtsFiles && sourceFile.isDeclarationFile) {
                        return "continue";
                    }
                    sourceFile.getNamedDeclarations().forEach(function (declarations, name) {
                        getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems);
                    });
                };
                // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
                for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
                    var sourceFile = sourceFiles_6[_i];
                    _loop_12(sourceFile);
                }
                rawItems.sort(compareNavigateToItems);
                return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
            }
            NavigateTo.getNavigateToItems = getNavigateToItems;
            function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) {
                // First do a quick check to see if the name of the declaration matches the
                // last portion of the (possibly) dotted name they're searching for.
                var match = patternMatcher.getMatchForLastSegmentOfPattern(name);
                if (!match) {
                    return; // continue to next named declarations
                }
                for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
                    var declaration = declarations_13[_i];
                    if (!shouldKeepItem(declaration, checker))
                        continue;
                    if (patternMatcher.patternContainsDots) {
                        // If the pattern has dots in it, then also see if the declaration container matches as well.
                        var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
                        if (fullMatch) {
                            rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration });
                        }
                    }
                    else {
                        rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration });
                    }
                }
            }
            function shouldKeepItem(declaration, checker) {
                switch (declaration.kind) {
                    case 248 /* ImportClause */:
                    case 251 /* ImportSpecifier */:
                    case 246 /* ImportEqualsDeclaration */:
                        var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217
                        var imported = checker.getAliasedSymbol(importer);
                        return importer.escapedName !== imported.escapedName;
                    default:
                        return true;
                }
            }
            function tryAddSingleDeclarationName(declaration, containers) {
                var name = ts.getNameOfDeclaration(declaration);
                return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers));
            }
            // Only added the names of computed properties if they're simple dotted expressions, like:
            //
            //      [X.Y.Z]() { }
            function tryAddComputedPropertyName(expression, containers) {
                return pushLiteral(expression, containers)
                    || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers);
            }
            function pushLiteral(node, containers) {
                return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true);
            }
            function getContainers(declaration) {
                var containers = [];
                // First, if we started with a computed property name, then add all but the last
                // portion into the container array.
                var name = ts.getNameOfDeclaration(declaration);
                if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) {
                    return ts.emptyArray;
                }
                // Don't include the last portion.
                containers.shift();
                // Now, walk up our containers, adding all their names to the container array.
                var container = ts.getContainerNode(declaration);
                while (container) {
                    if (!tryAddSingleDeclarationName(container, containers)) {
                        return ts.emptyArray;
                    }
                    container = ts.getContainerNode(container);
                }
                return containers.reverse();
            }
            function compareNavigateToItems(i1, i2) {
                // TODO(cyrusn): get the gamut of comparisons that VS already uses here.
                return ts.compareValues(i1.matchKind, i2.matchKind)
                    || ts.compareStringsCaseSensitiveUI(i1.name, i2.name);
            }
            function createNavigateToItem(rawItem) {
                var declaration = rawItem.declaration;
                var container = ts.getContainerNode(declaration);
                var containerName = container && ts.getNameOfDeclaration(container);
                return {
                    name: rawItem.name,
                    kind: ts.getNodeKind(declaration),
                    kindModifiers: ts.getNodeModifiers(declaration),
                    matchKind: ts.PatternMatchKind[rawItem.matchKind],
                    isCaseSensitive: rawItem.isCaseSensitive,
                    fileName: rawItem.fileName,
                    textSpan: ts.createTextSpanFromNode(declaration),
                    // TODO(jfreeman): What should be the containerName when the container has a computed name?
                    containerName: containerName ? containerName.text : "",
                    containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */,
                };
            }
        })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var NavigationBar;
        (function (NavigationBar) {
            /**
             * Matches all whitespace characters in a string. Eg:
             *
             * "app.
             *
             * onactivated"
             *
             * matches because of the newline, whereas
             *
             * "app.onactivated"
             *
             * does not match.
             */
            var whiteSpaceRegex = /\s+/g;
            // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`.
            var curCancellationToken;
            var curSourceFile;
            /**
             * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion.
             * `parent` is the current parent and is *not* stored in parentsStack.
             * `startNode` sets a new parent and `endNode` returns to the previous parent.
             */
            var parentsStack = [];
            var parent;
            // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance.
            var emptyChildItemArray = [];
            function getNavigationBarItems(sourceFile, cancellationToken) {
                curCancellationToken = cancellationToken;
                curSourceFile = sourceFile;
                try {
                    return ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem);
                }
                finally {
                    reset();
                }
            }
            NavigationBar.getNavigationBarItems = getNavigationBarItems;
            function getNavigationTree(sourceFile, cancellationToken) {
                curCancellationToken = cancellationToken;
                curSourceFile = sourceFile;
                try {
                    return convertToTree(rootNavigationBarNode(sourceFile));
                }
                finally {
                    reset();
                }
            }
            NavigationBar.getNavigationTree = getNavigationTree;
            function reset() {
                curSourceFile = undefined;
                curCancellationToken = undefined;
                parentsStack = [];
                parent = undefined;
                emptyChildItemArray = [];
            }
            function nodeText(node) {
                return node.getText(curSourceFile);
            }
            function navigationBarNodeKind(n) {
                return n.node.kind;
            }
            function pushChild(parent, child) {
                if (parent.children) {
                    parent.children.push(child);
                }
                else {
                    parent.children = [child];
                }
            }
            function rootNavigationBarNode(sourceFile) {
                ts.Debug.assert(!parentsStack.length);
                var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 };
                parent = root;
                for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
                    var statement = _a[_i];
                    addChildrenRecursively(statement);
                }
                endNode();
                ts.Debug.assert(!parent && !parentsStack.length);
                return root;
            }
            function addLeafNode(node) {
                pushChild(parent, emptyNavigationBarNode(node));
            }
            function emptyNavigationBarNode(node) {
                return {
                    node: node,
                    name: ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined,
                    additionalNodes: undefined,
                    parent: parent,
                    children: undefined,
                    indent: parent.indent + 1
                };
            }
            /**
             * Add a new level of NavigationBarNodes.
             * This pushes to the stack, so you must call `endNode` when you are done adding to this node.
             */
            function startNode(node) {
                var navNode = emptyNavigationBarNode(node);
                pushChild(parent, navNode);
                // Save the old parent
                parentsStack.push(parent);
                parent = navNode;
            }
            /** Call after calling `startNode` and adding children to it. */
            function endNode() {
                if (parent.children) {
                    mergeChildren(parent.children, parent);
                    sortChildren(parent.children);
                }
                parent = parentsStack.pop();
            }
            function addNodeWithRecursiveChild(node, child) {
                startNode(node);
                addChildrenRecursively(child);
                endNode();
            }
            /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */
            function addChildrenRecursively(node) {
                curCancellationToken.throwIfCancellationRequested();
                if (!node || ts.isToken(node)) {
                    return;
                }
                switch (node.kind) {
                    case 155 /* Constructor */:
                        // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it.
                        var ctr = node;
                        addNodeWithRecursiveChild(ctr, ctr.body);
                        // Parameter properties are children of the class, not the constructor.
                        for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) {
                            var param = _a[_i];
                            if (ts.isParameterPropertyDeclaration(param)) {
                                addLeafNode(param);
                            }
                        }
                        break;
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 153 /* MethodSignature */:
                        if (!ts.hasDynamicName(node)) {
                            addNodeWithRecursiveChild(node, node.body);
                        }
                        break;
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                        if (!ts.hasDynamicName(node)) {
                            addLeafNode(node);
                        }
                        break;
                    case 248 /* ImportClause */:
                        var importClause = node;
                        // Handle default import case e.g.:
                        //    import d from "mod";
                        if (importClause.name) {
                            addLeafNode(importClause.name);
                        }
                        // Handle named bindings in imports e.g.:
                        //    import * as NS from "mod";
                        //    import {a, b as B} from "mod";
                        var namedBindings = importClause.namedBindings;
                        if (namedBindings) {
                            if (namedBindings.kind === 249 /* NamespaceImport */) {
                                addLeafNode(namedBindings);
                            }
                            else {
                                for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) {
                                    var element = _c[_b];
                                    addLeafNode(element);
                                }
                            }
                        }
                        break;
                    case 184 /* BindingElement */:
                    case 235 /* VariableDeclaration */:
                        var _d = node, name = _d.name, initializer = _d.initializer;
                        if (ts.isBindingPattern(name)) {
                            addChildrenRecursively(name);
                        }
                        else if (initializer && isFunctionOrClassExpression(initializer)) {
                            if (initializer.name) {
                                // Don't add a node for the VariableDeclaration, just for the initializer.
                                addChildrenRecursively(initializer);
                            }
                            else {
                                // Add a node for the VariableDeclaration, but not for the initializer.
                                startNode(node);
                                ts.forEachChild(initializer, addChildrenRecursively);
                                endNode();
                            }
                        }
                        else {
                            addNodeWithRecursiveChild(node, initializer);
                        }
                        break;
                    case 195 /* ArrowFunction */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                        addNodeWithRecursiveChild(node, node.body);
                        break;
                    case 241 /* EnumDeclaration */:
                        startNode(node);
                        for (var _e = 0, _f = node.members; _e < _f.length; _e++) {
                            var member = _f[_e];
                            if (!isComputedProperty(member)) {
                                addLeafNode(member);
                            }
                        }
                        endNode();
                        break;
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                    case 239 /* InterfaceDeclaration */:
                        startNode(node);
                        for (var _g = 0, _h = node.members; _g < _h.length; _g++) {
                            var member = _h[_g];
                            addChildrenRecursively(member);
                        }
                        endNode();
                        break;
                    case 242 /* ModuleDeclaration */:
                        addNodeWithRecursiveChild(node, getInteriorModule(node).body);
                        break;
                    case 255 /* ExportSpecifier */:
                    case 246 /* ImportEqualsDeclaration */:
                    case 160 /* IndexSignature */:
                    case 158 /* CallSignature */:
                    case 159 /* ConstructSignature */:
                    case 240 /* TypeAliasDeclaration */:
                        addLeafNode(node);
                        break;
                    case 202 /* BinaryExpression */: {
                        var special = ts.getAssignmentDeclarationKind(node);
                        switch (special) {
                            case 1 /* ExportsProperty */:
                            case 2 /* ModuleExports */:
                            case 3 /* PrototypeProperty */:
                            case 6 /* Prototype */:
                                addNodeWithRecursiveChild(node, node.right);
                                return;
                            case 4 /* ThisProperty */:
                            case 5 /* Property */:
                            case 0 /* None */:
                                break;
                            default:
                                ts.Debug.assertNever(special);
                        }
                    }
                    // falls through
                    default:
                        if (ts.hasJSDocNodes(node)) {
                            ts.forEach(node.jsDoc, function (jsDoc) {
                                ts.forEach(jsDoc.tags, function (tag) {
                                    if (ts.isJSDocTypeAlias(tag)) {
                                        addLeafNode(tag);
                                    }
                                });
                            });
                        }
                        ts.forEachChild(node, addChildrenRecursively);
                }
            }
            /** Merge declarations of the same kind. */
            function mergeChildren(children, node) {
                var nameToItems = ts.createMap();
                ts.filterMutate(children, function (child) {
                    var declName = ts.getNameOfDeclaration(child.node);
                    var name = declName && nodeText(declName);
                    if (!name) {
                        // Anonymous items are never merged.
                        return true;
                    }
                    var itemsWithSameName = nameToItems.get(name);
                    if (!itemsWithSameName) {
                        nameToItems.set(name, child);
                        return true;
                    }
                    if (itemsWithSameName instanceof Array) {
                        for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) {
                            var itemWithSameName = itemsWithSameName_1[_i];
                            if (tryMerge(itemWithSameName, child, node)) {
                                return false;
                            }
                        }
                        itemsWithSameName.push(child);
                        return true;
                    }
                    else {
                        var itemWithSameName = itemsWithSameName;
                        if (tryMerge(itemWithSameName, child, node)) {
                            return false;
                        }
                        nameToItems.set(name, [itemWithSameName, child]);
                        return true;
                    }
                });
            }
            function tryMerge(a, b, parent) {
                if (shouldReallyMerge(a.node, b.node, parent)) {
                    merge(a, b);
                    return true;
                }
                return false;
            }
            /** a and b have the same name, but they may not be mergeable. */
            function shouldReallyMerge(a, b, parent) {
                if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) {
                    return false;
                }
                switch (a.kind) {
                    case 152 /* PropertyDeclaration */:
                    case 154 /* MethodDeclaration */:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                        return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */);
                    case 242 /* ModuleDeclaration */:
                        return areSameModule(a, b);
                    default:
                        return true;
                }
            }
            // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }`
            // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };`
            function isOwnChild(n, parent) {
                var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent;
                return par === parent.node || ts.contains(parent.additionalNodes, par);
            }
            // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes.
            // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'!
            function areSameModule(a, b) {
                // TODO: GH#18217
                return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
            }
            /** Merge source into target. Source should be thrown away after this is called. */
            function merge(target, source) {
                var _a;
                target.additionalNodes = target.additionalNodes || [];
                target.additionalNodes.push(source.node);
                if (source.additionalNodes) {
                    (_a = target.additionalNodes).push.apply(_a, source.additionalNodes);
                }
                target.children = ts.concatenate(target.children, source.children);
                if (target.children) {
                    mergeChildren(target.children, target);
                    sortChildren(target.children);
                }
            }
            /** Recursively ensure that each NavNode's children are in sorted order. */
            function sortChildren(children) {
                children.sort(compareChildren);
            }
            function compareChildren(child1, child2) {
                return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217
                    || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2));
            }
            /**
             * This differs from getItemName because this is just used for sorting.
             * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like.
             * So `new()` can still come before an `aardvark` method.
             */
            function tryGetName(node) {
                if (node.kind === 242 /* ModuleDeclaration */) {
                    return getModuleName(node);
                }
                var declName = ts.getNameOfDeclaration(node);
                if (declName && ts.isPropertyName(declName)) {
                    return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217
                }
                switch (node.kind) {
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                    case 207 /* ClassExpression */:
                        return getFunctionOrClassName(node);
                    default:
                        return undefined;
                }
            }
            function getItemName(node, name) {
                if (node.kind === 242 /* ModuleDeclaration */) {
                    return getModuleName(node);
                }
                if (name) {
                    var text = nodeText(name);
                    if (text.length > 0) {
                        return text;
                    }
                }
                switch (node.kind) {
                    case 277 /* SourceFile */:
                        var sourceFile = node;
                        return ts.isExternalModule(sourceFile)
                            ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
                            : "<global>";
                    case 195 /* ArrowFunction */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                        if (ts.getModifierFlags(node) & 512 /* Default */) {
                            return "default";
                        }
                        // We may get a string with newlines or other whitespace in the case of an object dereference
                        // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the
                        // navigation bar.
                        return getFunctionOrClassName(node);
                    case 155 /* Constructor */:
                        return "constructor";
                    case 159 /* ConstructSignature */:
                        return "new()";
                    case 158 /* CallSignature */:
                        return "()";
                    case 160 /* IndexSignature */:
                        return "[]";
                    default:
                        return "<unknown>";
                }
            }
            /** Flattens the NavNode tree to a list, keeping only the top-level items. */
            function topLevelItems(root) {
                var topLevel = [];
                function recur(item) {
                    if (isTopLevel(item)) {
                        topLevel.push(item);
                        if (item.children) {
                            for (var _i = 0, _a = item.children; _i < _a.length; _i++) {
                                var child = _a[_i];
                                recur(child);
                            }
                        }
                    }
                }
                recur(root);
                return topLevel;
                function isTopLevel(item) {
                    switch (navigationBarNodeKind(item)) {
                        case 238 /* ClassDeclaration */:
                        case 207 /* ClassExpression */:
                        case 241 /* EnumDeclaration */:
                        case 239 /* InterfaceDeclaration */:
                        case 242 /* ModuleDeclaration */:
                        case 277 /* SourceFile */:
                        case 240 /* TypeAliasDeclaration */:
                        case 302 /* JSDocTypedefTag */:
                        case 295 /* JSDocCallbackTag */:
                            return true;
                        case 155 /* Constructor */:
                        case 154 /* MethodDeclaration */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                        case 235 /* VariableDeclaration */:
                            return hasSomeImportantChild(item);
                        case 195 /* ArrowFunction */:
                        case 237 /* FunctionDeclaration */:
                        case 194 /* FunctionExpression */:
                            return isTopLevelFunctionDeclaration(item);
                        default:
                            return false;
                    }
                    function isTopLevelFunctionDeclaration(item) {
                        if (!item.node.body) {
                            return false;
                        }
                        switch (navigationBarNodeKind(item.parent)) {
                            case 243 /* ModuleBlock */:
                            case 277 /* SourceFile */:
                            case 154 /* MethodDeclaration */:
                            case 155 /* Constructor */:
                                return true;
                            default:
                                return hasSomeImportantChild(item);
                        }
                    }
                    function hasSomeImportantChild(item) {
                        return ts.some(item.children, function (child) {
                            var childKind = navigationBarNodeKind(child);
                            return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */;
                        });
                    }
                }
            }
            function convertToTree(n) {
                return {
                    text: getItemName(n.node, n.name),
                    kind: ts.getNodeKind(n.node),
                    kindModifiers: getModifiers(n.node),
                    spans: getSpans(n),
                    nameSpan: n.name && getNodeSpan(n.name),
                    childItems: ts.map(n.children, convertToTree)
                };
            }
            function convertToTopLevelItem(n) {
                return {
                    text: getItemName(n.node, n.name),
                    kind: ts.getNodeKind(n.node),
                    kindModifiers: getModifiers(n.node),
                    spans: getSpans(n),
                    childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray,
                    indent: n.indent,
                    bolded: false,
                    grayed: false
                };
                function convertToChildItem(n) {
                    return {
                        text: getItemName(n.node, n.name),
                        kind: ts.getNodeKind(n.node),
                        kindModifiers: ts.getNodeModifiers(n.node),
                        spans: getSpans(n),
                        childItems: emptyChildItemArray,
                        indent: 0,
                        bolded: false,
                        grayed: false
                    };
                }
            }
            function getSpans(n) {
                var spans = [getNodeSpan(n.node)];
                if (n.additionalNodes) {
                    for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) {
                        var node = _a[_i];
                        spans.push(getNodeSpan(node));
                    }
                }
                return spans;
            }
            function getModuleName(moduleDeclaration) {
                // We want to maintain quotation marks.
                if (ts.isAmbientModule(moduleDeclaration)) {
                    return ts.getTextOfNode(moduleDeclaration.name);
                }
                // Otherwise, we need to aggregate each identifier to build up the qualified name.
                var result = [];
                result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
                while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) {
                    moduleDeclaration = moduleDeclaration.body;
                    result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
                }
                return result.join(".");
            }
            /**
             * For 'module A.B.C', we want to get the node for 'C'.
             * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again.
             */
            function getInteriorModule(decl) {
                return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl;
            }
            function isComputedProperty(member) {
                return !member.name || member.name.kind === 147 /* ComputedPropertyName */;
            }
            function getNodeSpan(node) {
                return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
            }
            function getModifiers(node) {
                if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) {
                    node = node.parent;
                }
                return ts.getNodeModifiers(node);
            }
            function getFunctionOrClassName(node) {
                if (node.name && ts.getFullWidth(node.name) > 0) {
                    return ts.declarationNameToString(node.name);
                }
                // See if it is a var initializer. If so, use the var name.
                else if (node.parent.kind === 235 /* VariableDeclaration */) {
                    return ts.declarationNameToString(node.parent.name);
                }
                // See if it is of the form "<expr> = function(){...}". If so, use the text from the left-hand side.
                else if (node.parent.kind === 202 /* BinaryExpression */ &&
                    node.parent.operatorToken.kind === 58 /* EqualsToken */) {
                    return nodeText(node.parent.left).replace(whiteSpaceRegex, "");
                }
                // See if it is a property assignment, and if so use the property name
                else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) {
                    return nodeText(node.parent.name);
                }
                // Default exports are named "default"
                else if (ts.getModifierFlags(node) & 512 /* Default */) {
                    return "default";
                }
                else {
                    return ts.isClassLike(node) ? "<class>" : "<function>";
                }
            }
            function isFunctionOrClassExpression(node) {
                switch (node.kind) {
                    case 195 /* ArrowFunction */:
                    case 194 /* FunctionExpression */:
                    case 207 /* ClassExpression */:
                        return true;
                    default:
                        return false;
                }
            }
        })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var OrganizeImports;
        (function (OrganizeImports) {
            /**
             * Organize imports by:
             *   1) Removing unused imports
             *   2) Coalescing imports from the same module
             *   3) Sorting imports
             */
            function organizeImports(sourceFile, formatContext, host, program, _preferences) {
                var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
                var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
                // All of the old ImportDeclarations in the file, in syntactic order.
                var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
                organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
                // All of the old ExportDeclarations in the file, in syntactic order.
                var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
                organizeImportsWorker(topLevelExportDecls, coalesceExports);
                for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
                    var ambientModule = _a[_i];
                    var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217
                    var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
                    organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
                    var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
                    organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
                }
                return changeTracker.getChanges();
                function organizeImportsWorker(oldImportDecls, coalesce) {
                    if (ts.length(oldImportDecls) === 0) {
                        return;
                    }
                    // Special case: normally, we'd expect leading and trailing trivia to follow each import
                    // around as it's sorted.  However, we do not want this to happen for leading trivia
                    // on the first import because it is probably the header comment for the file.
                    // Consider: we could do a more careful check that this trivia is actually a header,
                    // but the consequences of being wrong are very minor.
                    ts.suppressLeadingTrivia(oldImportDecls[0]);
                    var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
                    var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
                    var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
                        return getExternalModuleName(importGroup[0].moduleSpecifier)
                            ? coalesce(importGroup)
                            : importGroup;
                    });
                    // Delete or replace the first import.
                    if (newImportDecls.length === 0) {
                        changeTracker.delete(sourceFile, oldImportDecls[0]);
                    }
                    else {
                        // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
                        changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
                            useNonAdjustedStartPosition: true,
                            useNonAdjustedEndPosition: false,
                            suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
                        });
                    }
                    // Delete any subsequent imports.
                    for (var i = 1; i < oldImportDecls.length; i++) {
                        changeTracker.delete(sourceFile, oldImportDecls[i]);
                    }
                }
            }
            OrganizeImports.organizeImports = organizeImports;
            function getModuleBlock(moduleDecl) {
                var body = moduleDecl.body;
                return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined;
            }
            function removeUnusedImports(oldImports, sourceFile, program) {
                var typeChecker = program.getTypeChecker();
                var jsxNamespace = typeChecker.getJsxNamespace();
                var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */);
                var usedImports = [];
                for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
                    var importDecl = oldImports_1[_i];
                    var importClause = importDecl.importClause;
                    if (!importClause) {
                        // Imports without import clauses are assumed to be included for their side effects and are not removed.
                        usedImports.push(importDecl);
                        continue;
                    }
                    var name = importClause.name, namedBindings = importClause.namedBindings;
                    // Default import
                    if (name && !isDeclarationUsed(name)) {
                        name = undefined;
                    }
                    if (namedBindings) {
                        if (ts.isNamespaceImport(namedBindings)) {
                            // Namespace import
                            if (!isDeclarationUsed(namedBindings.name)) {
                                namedBindings = undefined;
                            }
                        }
                        else {
                            // List of named imports
                            var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); });
                            if (newElements.length < namedBindings.elements.length) {
                                namedBindings = newElements.length
                                    ? ts.updateNamedImports(namedBindings, newElements)
                                    : undefined;
                            }
                        }
                    }
                    if (name || namedBindings) {
                        usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
                    }
                }
                return usedImports;
                function isDeclarationUsed(identifier) {
                    // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed.
                    return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
                }
            }
            function getExternalModuleName(specifier) {
                return specifier !== undefined && ts.isStringLiteralLike(specifier)
                    ? specifier.text
                    : undefined;
            }
            /* @internal */ // Internal for testing
            /**
             * @param importGroup a list of ImportDeclarations, all with the same module name.
             */
            function coalesceImports(importGroup) {
                if (importGroup.length === 0) {
                    return importGroup;
                }
                var _a = getCategorizedImports(importGroup), importWithoutClause = _a.importWithoutClause, defaultImports = _a.defaultImports, namespaceImports = _a.namespaceImports, namedImports = _a.namedImports;
                var coalescedImports = [];
                if (importWithoutClause) {
                    coalescedImports.push(importWithoutClause);
                }
                // Normally, we don't combine default and namespace imports, but it would be silly to
                // produce two import declarations in this special case.
                if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
                    // Add the namespace import to the existing default ImportDeclaration.
                    var defaultImport = defaultImports[0];
                    coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217
                    return coalescedImports;
                }
                var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
                    return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
                }); // TODO: GH#18217
                for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) {
                    var namespaceImport = sortedNamespaceImports_1[_i];
                    // Drop the name, if any
                    coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217
                }
                if (defaultImports.length === 0 && namedImports.length === 0) {
                    return coalescedImports;
                }
                var newDefaultImport;
                var newImportSpecifiers = [];
                if (defaultImports.length === 1) {
                    newDefaultImport = defaultImports[0].importClause.name;
                }
                else {
                    for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) {
                        var defaultImport = defaultImports_1[_b];
                        newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217
                    }
                }
                newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217
                var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
                var importDecl = defaultImports.length > 0
                    ? defaultImports[0]
                    : namedImports[0];
                var newNamedImports = sortedImportSpecifiers.length === 0
                    ? newDefaultImport
                        ? undefined
                        : ts.createNamedImports(ts.emptyArray)
                    : namedImports.length === 0
                        ? ts.createNamedImports(sortedImportSpecifiers)
                        : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217
                coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
                return coalescedImports;
                /*
                 * Returns entire import declarations because they may already have been rewritten and
                 * may lack parent pointers.  The desired parts can easily be recovered based on the
                 * categorization.
                 *
                 * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
                 */
                function getCategorizedImports(importGroup) {
                    var importWithoutClause;
                    var defaultImports = [];
                    var namespaceImports = [];
                    var namedImports = [];
                    for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) {
                        var importDeclaration = importGroup_1[_i];
                        if (importDeclaration.importClause === undefined) {
                            // Only the first such import is interesting - the others are redundant.
                            // Note: Unfortunately, we will lose trivia that was on this node.
                            importWithoutClause = importWithoutClause || importDeclaration;
                            continue;
                        }
                        var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
                        if (name) {
                            defaultImports.push(importDeclaration);
                        }
                        if (namedBindings) {
                            if (ts.isNamespaceImport(namedBindings)) {
                                namespaceImports.push(importDeclaration);
                            }
                            else {
                                namedImports.push(importDeclaration);
                            }
                        }
                    }
                    return {
                        importWithoutClause: importWithoutClause,
                        defaultImports: defaultImports,
                        namespaceImports: namespaceImports,
                        namedImports: namedImports,
                    };
                }
            }
            OrganizeImports.coalesceImports = coalesceImports;
            /* @internal */ // Internal for testing
            /**
             * @param exportGroup a list of ExportDeclarations, all with the same module name.
             */
            function coalesceExports(exportGroup) {
                if (exportGroup.length === 0) {
                    return exportGroup;
                }
                var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
                var coalescedExports = [];
                if (exportWithoutClause) {
                    coalescedExports.push(exportWithoutClause);
                }
                if (namedExports.length === 0) {
                    return coalescedExports;
                }
                var newExportSpecifiers = [];
                newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
                var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
                var exportDecl = namedExports[0];
                coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
                return coalescedExports;
                /*
                 * Returns entire export declarations because they may already have been rewritten and
                 * may lack parent pointers.  The desired parts can easily be recovered based on the
                 * categorization.
                 */
                function getCategorizedExports(exportGroup) {
                    var exportWithoutClause;
                    var namedExports = [];
                    for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
                        var exportDeclaration = exportGroup_1[_i];
                        if (exportDeclaration.exportClause === undefined) {
                            // Only the first such export is interesting - the others are redundant.
                            // Note: Unfortunately, we will lose trivia that was on this node.
                            exportWithoutClause = exportWithoutClause || exportDeclaration;
                        }
                        else {
                            namedExports.push(exportDeclaration);
                        }
                    }
                    return {
                        exportWithoutClause: exportWithoutClause,
                        namedExports: namedExports,
                    };
                }
            }
            OrganizeImports.coalesceExports = coalesceExports;
            function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
                return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217
                importDeclaration.moduleSpecifier);
            }
            function sortSpecifiers(specifiers) {
                return ts.stableSort(specifiers, function (s1, s2) {
                    return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
                        compareIdentifiers(s1.name, s2.name);
                });
            }
            /* internal */ // Exported for testing
            function compareModuleSpecifiers(m1, m2) {
                var name1 = getExternalModuleName(m1);
                var name2 = getExternalModuleName(m2);
                return ts.compareBooleans(name1 === undefined, name2 === undefined) ||
                    ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) ||
                    ts.compareStringsCaseInsensitive(name1, name2);
            }
            OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
            function compareIdentifiers(s1, s2) {
                return ts.compareStringsCaseInsensitive(s1.text, s2.text);
            }
        })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var OutliningElementsCollector;
        (function (OutliningElementsCollector) {
            function collectElements(sourceFile, cancellationToken) {
                var res = [];
                addNodeOutliningSpans(sourceFile, cancellationToken, res);
                addRegionOutliningSpans(sourceFile, res);
                return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; });
            }
            OutliningElementsCollector.collectElements = collectElements;
            function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
                var depthRemaining = 40;
                var current = 0;
                var statements = sourceFile.statements;
                var n = statements.length;
                while (current < n) {
                    while (current < n && !ts.isAnyImportSyntax(statements[current])) {
                        visitNonImportNode(statements[current]);
                        current++;
                    }
                    if (current === n)
                        break;
                    var firstImport = current;
                    while (current < n && ts.isAnyImportSyntax(statements[current])) {
                        addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
                        current++;
                    }
                    var lastImport = current - 1;
                    if (lastImport !== firstImport) {
                        out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
                    }
                }
                function visitNonImportNode(n) {
                    if (depthRemaining === 0)
                        return;
                    cancellationToken.throwIfCancellationRequested();
                    if (ts.isDeclaration(n)) {
                        addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out);
                    }
                    var span = getOutliningSpanForNode(n, sourceFile);
                    if (span)
                        out.push(span);
                    depthRemaining--;
                    if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
                        // Consider an 'else if' to be on the same depth as the 'if'.
                        visitNonImportNode(n.expression);
                        visitNonImportNode(n.thenStatement);
                        depthRemaining++;
                        visitNonImportNode(n.elseStatement);
                        depthRemaining--;
                    }
                    else {
                        n.forEachChild(visitNonImportNode);
                    }
                    depthRemaining++;
                }
            }
            function addRegionOutliningSpans(sourceFile, out) {
                var regions = [];
                var lineStarts = sourceFile.getLineStarts();
                for (var i = 0; i < lineStarts.length; i++) {
                    var currentLineStart = lineStarts[i];
                    var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1;
                    var lineText = sourceFile.text.substring(currentLineStart, lineEnd);
                    var result = isRegionDelimiter(lineText);
                    if (!result || ts.isInComment(sourceFile, currentLineStart)) {
                        continue;
                    }
                    if (!result[1]) {
                        var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
                        regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
                    }
                    else {
                        var region = regions.pop();
                        if (region) {
                            region.textSpan.length = lineEnd - region.textSpan.start;
                            region.hintSpan.length = lineEnd - region.textSpan.start;
                            out.push(region);
                        }
                    }
                }
            }
            var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/;
            function isRegionDelimiter(lineText) {
                return regionDelimiterRegExp.exec(lineText);
            }
            function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) {
                var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
                if (!comments)
                    return;
                var firstSingleLineCommentStart = -1;
                var lastSingleLineCommentEnd = -1;
                var singleLineCommentCount = 0;
                var sourceText = sourceFile.getFullText();
                for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) {
                    var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
                    cancellationToken.throwIfCancellationRequested();
                    switch (kind) {
                        case 2 /* SingleLineCommentTrivia */:
                            // never fold region delimiters into single-line comment regions
                            var commentText = sourceText.slice(pos, end);
                            if (isRegionDelimiter(commentText)) {
                                combineAndAddMultipleSingleLineComments();
                                singleLineCommentCount = 0;
                                break;
                            }
                            // For single line comments, combine consecutive ones (2 or more) into
                            // a single span from the start of the first till the end of the last
                            if (singleLineCommentCount === 0) {
                                firstSingleLineCommentStart = pos;
                            }
                            lastSingleLineCommentEnd = end;
                            singleLineCommentCount++;
                            break;
                        case 3 /* MultiLineCommentTrivia */:
                            combineAndAddMultipleSingleLineComments();
                            out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
                            singleLineCommentCount = 0;
                            break;
                        default:
                            ts.Debug.assertNever(kind);
                    }
                }
                combineAndAddMultipleSingleLineComments();
                function combineAndAddMultipleSingleLineComments() {
                    // Only outline spans of two or more consecutive single line comments
                    if (singleLineCommentCount > 1) {
                        out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
                    }
                }
            }
            function createOutliningSpanFromBounds(pos, end, kind) {
                return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
            }
            function getOutliningSpanForNode(n, sourceFile) {
                switch (n.kind) {
                    case 216 /* Block */:
                        if (ts.isFunctionBlock(n)) {
                            return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */);
                        }
                        // Check if the block is standalone, or 'attached' to some parent statement.
                        // If the latter, we want to collapse the block, but consider its hint span
                        // to be the entire span of the parent.
                        switch (n.parent.kind) {
                            case 221 /* DoStatement */:
                            case 224 /* ForInStatement */:
                            case 225 /* ForOfStatement */:
                            case 223 /* ForStatement */:
                            case 220 /* IfStatement */:
                            case 222 /* WhileStatement */:
                            case 229 /* WithStatement */:
                            case 272 /* CatchClause */:
                                return spanForNode(n.parent);
                            case 233 /* TryStatement */:
                                // Could be the try-block, or the finally-block.
                                var tryStatement = n.parent;
                                if (tryStatement.tryBlock === n) {
                                    return spanForNode(n.parent);
                                }
                                else if (tryStatement.finallyBlock === n) {
                                    return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile));
                                }
                            // falls through
                            default:
                                // Block was a standalone block.  In this case we want to only collapse
                                // the span of the block, independent of any parent span.
                                return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
                        }
                    case 243 /* ModuleBlock */:
                        return spanForNode(n.parent);
                    case 238 /* ClassDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 244 /* CaseBlock */:
                        return spanForNode(n);
                    case 186 /* ObjectLiteralExpression */:
                        return spanForObjectOrArrayLiteral(n);
                    case 185 /* ArrayLiteralExpression */:
                        return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */);
                    case 258 /* JsxElement */:
                        return spanForJSXElement(n);
                    case 259 /* JsxSelfClosingElement */:
                    case 260 /* JsxOpeningElement */:
                        return spanForJSXAttributes(n.attributes);
                }
                function spanForJSXElement(node) {
                    var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd());
                    var tagName = node.openingElement.tagName.getText(sourceFile);
                    var bannerText = "<" + tagName + ">...</" + tagName + ">";
                    return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText);
                }
                function spanForJSXAttributes(node) {
                    if (node.properties.length === 0) {
                        return undefined;
                    }
                    return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
                }
                function spanForObjectOrArrayLiteral(node, open) {
                    if (open === void 0) {
                        open = 17 /* OpenBraceToken */;
                    }
                    // If the block has no leading keywords and is inside an array literal,
                    // we only want to collapse the span of the block.
                    // Otherwise, the collapsed section will include the end of the previous line.
                    return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open);
                }
                function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) {
                    if (autoCollapse === void 0) {
                        autoCollapse = false;
                    }
                    if (useFullStart === void 0) {
                        useFullStart = true;
                    }
                    if (open === void 0) {
                        open = 17 /* OpenBraceToken */;
                    }
                    var openToken = ts.findChildOfKind(n, open, sourceFile);
                    var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */;
                    var closeToken = ts.findChildOfKind(n, close, sourceFile);
                    if (!openToken || !closeToken) {
                        return undefined;
                    }
                    var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
                    return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
                }
            }
            function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
                if (hintSpan === void 0) {
                    hintSpan = textSpan;
                }
                if (autoCollapse === void 0) {
                    autoCollapse = false;
                }
                if (bannerText === void 0) {
                    bannerText = "...";
                }
                return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
            }
        })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        // Note(cyrusn): this enum is ordered from strongest match type to weakest match type.
        var PatternMatchKind;
        (function (PatternMatchKind) {
            PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact";
            PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix";
            PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring";
            PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase";
        })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {}));
        function createPatternMatch(kind, isCaseSensitive) {
            return {
                kind: kind,
                isCaseSensitive: isCaseSensitive
            };
        }
        function createPatternMatcher(pattern) {
            // We'll often see the same candidate string many times when searching (For example, when
            // we see the name of a module that is used everywhere, or the name of an overload).  As
            // such, we cache the information we compute about the candidate for the life of this
            // pattern matcher so we don't have to compute it multiple times.
            var stringToWordSpans = ts.createMap();
            var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); });
            // A segment is considered invalid if we couldn't find any words in it.
            if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; }))
                return undefined;
            return {
                getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); },
                getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); },
                patternContainsDots: dotSeparatedSegments.length > 1
            };
        }
        ts.createPatternMatcher = createPatternMatcher;
        function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) {
            // First, check that the last part of the dot separated pattern matches the name of the
            // candidate.  If not, then there's no point in proceeding and doing the more
            // expensive work.
            var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans);
            if (!candidateMatch) {
                return undefined;
            }
            // -1 because the last part was checked against the name, and only the rest
            // of the parts are checked against the container.
            if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
                // There weren't enough container parts to match against the pattern parts.
                // So this definitely doesn't match.
                return undefined;
            }
            var bestMatch;
            for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) {
                bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans));
            }
            return bestMatch;
        }
        function getWordSpans(word, stringToWordSpans) {
            var spans = stringToWordSpans.get(word);
            if (!spans) {
                stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
            }
            return spans;
        }
        function matchTextChunk(candidate, chunk, stringToWordSpans) {
            var index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
            if (index === 0) {
                // a) Check if the word is a prefix of the candidate, in a case insensitive or
                //    sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match.
                return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
            }
            if (chunk.isLowerCase) {
                if (index === -1)
                    return undefined;
                // b) If the part is entirely lowercase, then check if it is contained anywhere in the
                //    candidate in a case insensitive manner.  If so, return that there was a substring
                //    match.
                //
                //    Note: We only have a substring match if the lowercase part is prefix match of some
                //    word part. That way we don't match something like 'Class' when the user types 'a'.
                //    But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
                var wordSpans = getWordSpans(candidate, stringToWordSpans);
                for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
                    var span = wordSpans_1[_i];
                    if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) {
                        return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false));
                    }
                }
                // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
                // We could check every character boundary start of the candidate for the pattern. However, that's
                // an m * n operation in the wost case. Instead, find the first instance of the pattern
                // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
                // filter the list based on a substring that starts on a capital letter and also with a lowercase one.
                // (Pattern: fogbar, Candidate: quuxfogbarFogBar).
                if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) {
                    return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false);
                }
            }
            else {
                // d) If the part was not entirely lowercase, then check if it is contained in the
                //    candidate in a case *sensitive* manner. If so, return that there was a substring
                //    match.
                if (candidate.indexOf(chunk.text) > 0) {
                    return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true);
                }
                // e) If the part was not entirely lowercase, then attempt a camel cased match as well.
                if (chunk.characterSpans.length > 0) {
                    var candidateParts = getWordSpans(candidate, stringToWordSpans);
                    var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true
                        : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined;
                    if (isCaseSensitive !== undefined) {
                        return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive);
                    }
                }
            }
        }
        function matchSegment(candidate, segment, stringToWordSpans) {
            // First check if the segment matches as is.  This is also useful if the segment contains
            // characters we would normally strip when splitting into parts that we also may want to
            // match in the candidate.  For example if the segment is "@int" and the candidate is
            // "@int", then that will show up as an exact match here.
            //
            // Note: if the segment contains a space or an asterisk then we must assume that it's a
            // multi-word segment.
            if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) {
                var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans);
                if (match)
                    return match;
            }
            // The logic for pattern matching is now as follows:
            //
            // 1) Break the segment passed in into words.  Breaking is rather simple and a
            //    good way to think about it that if gives you all the individual alphanumeric words
            //    of the pattern.
            //
            // 2) For each word try to match the word against the candidate value.
            //
            // 3) Matching is as follows:
            //
            //   a) Check if the word is a prefix of the candidate, in a case insensitive or
            //      sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match.
            //
            //   If the word is entirely lowercase:
            //      b) Then check if it is contained anywhere in the
            //          candidate in a case insensitive manner.  If so, return that there was a substring
            //          match.
            //
            //          Note: We only have a substring match if the lowercase part is prefix match of
            //          some word part. That way we don't match something like 'Class' when the user
            //          types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
            //          'a').
            //
            //       c) The word is all lower case. Is it a case insensitive substring of the candidate starting
            //          on a part boundary of the candidate?
            //
            //   Else:
            //       d) If the word was not entirely lowercase, then check if it is contained in the
            //          candidate in a case *sensitive* manner. If so, return that there was a substring
            //          match.
            //
            //       e) If the word was not entirely lowercase, then attempt a camel cased match as
            //          well.
            //
            // Only if all words have some sort of match is the pattern considered matched.
            var subWordTextChunks = segment.subWordTextChunks;
            var bestMatch;
            for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
                var subWordTextChunk = subWordTextChunks_1[_i];
                bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans));
            }
            return bestMatch;
        }
        function betterMatch(a, b) {
            return ts.min(a, b, compareMatches);
        }
        function compareMatches(a, b) {
            return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */
                : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive);
        }
        function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) {
            if (patternSpan === void 0) {
                patternSpan = { start: 0, length: pattern.length };
            }
            return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match.
                && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); });
        }
        function equalChars(ch1, ch2, ignoreCase) {
            return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2;
        }
        function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) {
            var chunkCharacterSpans = chunk.characterSpans;
            // Note: we may have more pattern parts than candidate parts.  This is because multiple
            // pattern parts may match a candidate part.  For example "SiUI" against "SimpleUI".
            // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI.  However, U
            // and I will both match in UI.
            var currentCandidate = 0;
            var currentChunkSpan = 0;
            var firstMatch;
            var contiguous;
            while (true) {
                // Let's consider our termination cases
                if (currentChunkSpan === chunkCharacterSpans.length) {
                    return true;
                }
                else if (currentCandidate === candidateParts.length) {
                    // No match, since we still have more of the pattern to hit
                    return false;
                }
                var candidatePart = candidateParts[currentCandidate];
                var gotOneMatchThisCandidate = false;
                // Consider the case of matching SiUI against SimpleUIElement. The candidate parts
                // will be Simple/UI/Element, and the pattern parts will be Si/U/I.  We'll match 'Si'
                // against 'Simple' first.  Then we'll match 'U' against 'UI'. However, we want to
                // still keep matching pattern parts against that candidate part.
                for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
                    var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
                    if (gotOneMatchThisCandidate) {
                        // We've already gotten one pattern part match in this candidate.  We will
                        // only continue trying to consumer pattern parts if the last part and this
                        // part are both upper case.
                        if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) ||
                            !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
                            break;
                        }
                    }
                    if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) {
                        break;
                    }
                    gotOneMatchThisCandidate = true;
                    firstMatch = firstMatch === undefined ? currentCandidate : firstMatch;
                    // If we were contiguous, then keep that value.  If we weren't, then keep that
                    // value.  If we don't know, then set the value to 'true' as an initial match is
                    // obviously contiguous.
                    contiguous = contiguous === undefined ? true : contiguous;
                    candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length);
                }
                // Check if we matched anything at all.  If we didn't, then we need to unset the
                // contiguous bit if we currently had it set.
                // If we haven't set the bit yet, then that means we haven't matched anything so
                // far, and we don't want to change that.
                if (!gotOneMatchThisCandidate && contiguous !== undefined) {
                    contiguous = false;
                }
                // Move onto the next candidate.
                currentCandidate++;
            }
        }
        function createSegment(text) {
            return {
                totalTextChunk: createTextChunk(text),
                subWordTextChunks: breakPatternIntoTextChunks(text)
            };
        }
        function isUpperCaseLetter(ch) {
            // Fast check for the ascii range.
            if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
                return true;
            }
            if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
                return false;
            }
            // TODO: find a way to determine this for any unicode characters in a
            // non-allocating manner.
            var str = String.fromCharCode(ch);
            return str === str.toUpperCase();
        }
        function isLowerCaseLetter(ch) {
            // Fast check for the ascii range.
            if (ch >= 97 /* a */ && ch <= 122 /* z */) {
                return true;
            }
            if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
                return false;
            }
            // TODO: find a way to determine this for any unicode characters in a
            // non-allocating manner.
            var str = String.fromCharCode(ch);
            return str === str.toLowerCase();
        }
        // Assumes 'value' is already lowercase.
        function indexOfIgnoringCase(str, value) {
            var n = str.length - value.length;
            var _loop_13 = function (start) {
                if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
                    return { value: start };
                }
            };
            for (var start = 0; start <= n; start++) {
                var state_3 = _loop_13(start);
                if (typeof state_3 === "object")
                    return state_3.value;
            }
            return -1;
        }
        function toLowerCase(ch) {
            // Fast convert for the ascii range.
            if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
                return 97 /* a */ + (ch - 65 /* A */);
            }
            if (ch < 127 /* maxAsciiCharacter */) {
                return ch;
            }
            // TODO: find a way to compute this for any unicode characters in a
            // non-allocating manner.
            return String.fromCharCode(ch).toLowerCase().charCodeAt(0);
        }
        function isDigit(ch) {
            // TODO(cyrusn): Find a way to support this for unicode digits.
            return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
        }
        function isWordChar(ch) {
            return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */;
        }
        function breakPatternIntoTextChunks(pattern) {
            var result = [];
            var wordStart = 0;
            var wordLength = 0;
            for (var i = 0; i < pattern.length; i++) {
                var ch = pattern.charCodeAt(i);
                if (isWordChar(ch)) {
                    if (wordLength === 0) {
                        wordStart = i;
                    }
                    wordLength++;
                }
                else {
                    if (wordLength > 0) {
                        result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
                        wordLength = 0;
                    }
                }
            }
            if (wordLength > 0) {
                result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
            }
            return result;
        }
        function createTextChunk(text) {
            var textLowerCase = text.toLowerCase();
            return {
                text: text,
                textLowerCase: textLowerCase,
                isLowerCase: text === textLowerCase,
                characterSpans: breakIntoCharacterSpans(text)
            };
        }
        /* @internal */ function breakIntoCharacterSpans(identifier) {
            return breakIntoSpans(identifier, /*word:*/ false);
        }
        ts.breakIntoCharacterSpans = breakIntoCharacterSpans;
        /* @internal */ function breakIntoWordSpans(identifier) {
            return breakIntoSpans(identifier, /*word:*/ true);
        }
        ts.breakIntoWordSpans = breakIntoWordSpans;
        function breakIntoSpans(identifier, word) {
            var result = [];
            var wordStart = 0;
            for (var i = 1; i < identifier.length; i++) {
                var lastIsDigit = isDigit(identifier.charCodeAt(i - 1));
                var currentIsDigit = isDigit(identifier.charCodeAt(i));
                var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
                var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart);
                if (charIsPunctuation(identifier.charCodeAt(i - 1)) ||
                    charIsPunctuation(identifier.charCodeAt(i)) ||
                    lastIsDigit !== currentIsDigit ||
                    hasTransitionFromLowerToUpper ||
                    hasTransitionFromUpperToLower) {
                    if (!isAllPunctuation(identifier, wordStart, i)) {
                        result.push(ts.createTextSpan(wordStart, i - wordStart));
                    }
                    wordStart = i;
                }
            }
            if (!isAllPunctuation(identifier, wordStart, identifier.length)) {
                result.push(ts.createTextSpan(wordStart, identifier.length - wordStart));
            }
            return result;
        }
        function charIsPunctuation(ch) {
            switch (ch) {
                case 33 /* exclamation */:
                case 34 /* doubleQuote */:
                case 35 /* hash */:
                case 37 /* percent */:
                case 38 /* ampersand */:
                case 39 /* singleQuote */:
                case 40 /* openParen */:
                case 41 /* closeParen */:
                case 42 /* asterisk */:
                case 44 /* comma */:
                case 45 /* minus */:
                case 46 /* dot */:
                case 47 /* slash */:
                case 58 /* colon */:
                case 59 /* semicolon */:
                case 63 /* question */:
                case 64 /* at */:
                case 91 /* openBracket */:
                case 92 /* backslash */:
                case 93 /* closeBracket */:
                case 95 /* _ */:
                case 123 /* openBrace */:
                case 125 /* closeBrace */:
                    return true;
            }
            return false;
        }
        function isAllPunctuation(identifier, start, end) {
            return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end);
        }
        function transitionFromUpperToLower(identifier, index, wordStart) {
            // Cases this supports:
            // 1) IDisposable -> I, Disposable
            // 2) UIElement -> UI, Element
            // 3) HTMLDocument -> HTML, Document
            //
            // etc.
            // We have a transition from an upper to a lower letter here.  But we only
            // want to break if all the letters that preceded are uppercase.  i.e. if we
            // have "Foo" we don't want to break that into "F, oo".  But if we have
            // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI,
            // Foo".  i.e. the last uppercase letter belongs to the lowercase letters
            // that follows.  Note: this will make the following not split properly:
            // "HELLOthere".  However, these sorts of names do not show up in .Net
            // programs.
            return index !== wordStart
                && index + 1 < identifier.length
                && isUpperCaseLetter(identifier.charCodeAt(index))
                && isLowerCaseLetter(identifier.charCodeAt(index + 1))
                && every(identifier, isUpperCaseLetter, wordStart, index);
        }
        function transitionFromLowerToUpper(identifier, word, index) {
            var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
            var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
            // See if the casing indicates we're starting a new word. Note: if we're breaking on
            // words, then just seeing an upper case character isn't enough.  Instead, it has to
            // be uppercase and the previous character can't be uppercase.
            //
            // For example, breaking "AddMetadata" on words would make: Add Metadata
            //
            // on characters would be: A dd M etadata
            //
            // Break "AM" on words would be: AM
            //
            // on characters would be: A M
            //
            // We break the search string on characters.  But we break the symbol name on words.
            return currentIsUpper && (!word || !lastIsUpper);
        }
        function everyInRange(start, end, pred) {
            for (var i = start; i < end; i++) {
                if (!pred(i)) {
                    return false;
                }
            }
            return true;
        }
        function every(s, pred, start, end) {
            if (start === void 0) {
                start = 0;
            }
            if (end === void 0) {
                end = s.length;
            }
            return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); });
        }
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
            if (readImportFiles === void 0) {
                readImportFiles = true;
            }
            if (detectJavaScriptImports === void 0) {
                detectJavaScriptImports = false;
            }
            var pragmaContext = {
                languageVersion: 1 /* ES5 */,
                pragmas: undefined,
                checkJsDirective: undefined,
                referencedFiles: [],
                typeReferenceDirectives: [],
                libReferenceDirectives: [],
                amdDependencies: [],
                hasNoDefaultLib: undefined,
                moduleName: undefined
            };
            var importedFiles = [];
            var ambientExternalModules;
            var lastToken;
            var currentToken;
            var braceNesting = 0;
            // assume that text represent an external module if it contains at least one top level import/export
            // ambient modules that are found inside external modules are interpreted as module augmentations
            var externalModule = false;
            function nextToken() {
                lastToken = currentToken;
                currentToken = ts.scanner.scan();
                if (currentToken === 17 /* OpenBraceToken */) {
                    braceNesting++;
                }
                else if (currentToken === 18 /* CloseBraceToken */) {
                    braceNesting--;
                }
                return currentToken;
            }
            function getFileReference() {
                var fileName = ts.scanner.getTokenValue();
                var pos = ts.scanner.getTokenPos();
                return { fileName: fileName, pos: pos, end: pos + fileName.length };
            }
            function recordAmbientExternalModule() {
                if (!ambientExternalModules) {
                    ambientExternalModules = [];
                }
                ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
            }
            function recordModuleName() {
                importedFiles.push(getFileReference());
                markAsExternalModuleIfTopLevel();
            }
            function markAsExternalModuleIfTopLevel() {
                if (braceNesting === 0) {
                    externalModule = true;
                }
            }
            /**
             * Returns true if at least one token was consumed from the stream
             */
            function tryConsumeDeclare() {
                var token = ts.scanner.getToken();
                if (token === 124 /* DeclareKeyword */) {
                    // declare module "mod"
                    token = nextToken();
                    if (token === 129 /* ModuleKeyword */) {
                        token = nextToken();
                        if (token === 9 /* StringLiteral */) {
                            recordAmbientExternalModule();
                        }
                    }
                    return true;
                }
                return false;
            }
            /**
             * Returns true if at least one token was consumed from the stream
             */
            function tryConsumeImport() {
                if (lastToken === 23 /* DotToken */) {
                    return false;
                }
                var token = ts.scanner.getToken();
                if (token === 91 /* ImportKeyword */) {
                    token = nextToken();
                    if (token === 19 /* OpenParenToken */) {
                        token = nextToken();
                        if (token === 9 /* StringLiteral */) {
                            // import("mod");
                            recordModuleName();
                            return true;
                        }
                    }
                    else if (token === 9 /* StringLiteral */) {
                        // import "mod";
                        recordModuleName();
                        return true;
                    }
                    else {
                        if (token === 71 /* Identifier */ || ts.isKeyword(token)) {
                            token = nextToken();
                            if (token === 143 /* FromKeyword */) {
                                token = nextToken();
                                if (token === 9 /* StringLiteral */) {
                                    // import d from "mod";
                                    recordModuleName();
                                    return true;
                                }
                            }
                            else if (token === 58 /* EqualsToken */) {
                                if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
                                    return true;
                                }
                            }
                            else if (token === 26 /* CommaToken */) {
                                // consume comma and keep going
                                token = nextToken();
                            }
                            else {
                                // unknown syntax
                                return true;
                            }
                        }
                        if (token === 17 /* OpenBraceToken */) {
                            token = nextToken();
                            // consume "{ a as B, c, d as D}" clauses
                            // make sure that it stops on EOF
                            while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
                                token = nextToken();
                            }
                            if (token === 18 /* CloseBraceToken */) {
                                token = nextToken();
                                if (token === 143 /* FromKeyword */) {
                                    token = nextToken();
                                    if (token === 9 /* StringLiteral */) {
                                        // import {a as A} from "mod";
                                        // import d, {a, b as B} from "mod"
                                        recordModuleName();
                                    }
                                }
                            }
                        }
                        else if (token === 39 /* AsteriskToken */) {
                            token = nextToken();
                            if (token === 118 /* AsKeyword */) {
                                token = nextToken();
                                if (token === 71 /* Identifier */ || ts.isKeyword(token)) {
                                    token = nextToken();
                                    if (token === 143 /* FromKeyword */) {
                                        token = nextToken();
                                        if (token === 9 /* StringLiteral */) {
                                            // import * as NS from "mod"
                                            // import d, * as NS from "mod"
                                            recordModuleName();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return true;
                }
                return false;
            }
            function tryConsumeExport() {
                var token = ts.scanner.getToken();
                if (token === 84 /* ExportKeyword */) {
                    markAsExternalModuleIfTopLevel();
                    token = nextToken();
                    if (token === 17 /* OpenBraceToken */) {
                        token = nextToken();
                        // consume "{ a as B, c, d as D}" clauses
                        // make sure it stops on EOF
                        while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
                            token = nextToken();
                        }
                        if (token === 18 /* CloseBraceToken */) {
                            token = nextToken();
                            if (token === 143 /* FromKeyword */) {
                                token = nextToken();
                                if (token === 9 /* StringLiteral */) {
                                    // export {a as A} from "mod";
                                    // export {a, b as B} from "mod"
                                    recordModuleName();
                                }
                            }
                        }
                    }
                    else if (token === 39 /* AsteriskToken */) {
                        token = nextToken();
                        if (token === 143 /* FromKeyword */) {
                            token = nextToken();
                            if (token === 9 /* StringLiteral */) {
                                // export * from "mod"
                                recordModuleName();
                            }
                        }
                    }
                    else if (token === 91 /* ImportKeyword */) {
                        token = nextToken();
                        if (token === 71 /* Identifier */ || ts.isKeyword(token)) {
                            token = nextToken();
                            if (token === 58 /* EqualsToken */) {
                                if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
                                    return true;
                                }
                            }
                        }
                    }
                    return true;
                }
                return false;
            }
            function tryConsumeRequireCall(skipCurrentToken) {
                var token = skipCurrentToken ? nextToken() : ts.scanner.getToken();
                if (token === 133 /* RequireKeyword */) {
                    token = nextToken();
                    if (token === 19 /* OpenParenToken */) {
                        token = nextToken();
                        if (token === 9 /* StringLiteral */) {
                            //  require("mod");
                            recordModuleName();
                        }
                    }
                    return true;
                }
                return false;
            }
            function tryConsumeDefine() {
                var token = ts.scanner.getToken();
                if (token === 71 /* Identifier */ && ts.scanner.getTokenValue() === "define") {
                    token = nextToken();
                    if (token !== 19 /* OpenParenToken */) {
                        return true;
                    }
                    token = nextToken();
                    if (token === 9 /* StringLiteral */) {
                        // looks like define ("modname", ... - skip string literal and comma
                        token = nextToken();
                        if (token === 26 /* CommaToken */) {
                            token = nextToken();
                        }
                        else {
                            // unexpected token
                            return true;
                        }
                    }
                    // should be start of dependency list
                    if (token !== 21 /* OpenBracketToken */) {
                        return true;
                    }
                    // skip open bracket
                    token = nextToken();
                    // scan until ']' or EOF
                    while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
                        // record string literals as module names
                        if (token === 9 /* StringLiteral */) {
                            recordModuleName();
                        }
                        token = nextToken();
                    }
                    return true;
                }
                return false;
            }
            function processImports() {
                ts.scanner.setText(sourceText);
                nextToken();
                // Look for:
                //    import "mod";
                //    import d from "mod"
                //    import {a as A } from "mod";
                //    import * as NS from "mod"
                //    import d, {a, b as B} from "mod"
                //    import i = require("mod");
                //    import("mod");
                //    export * from "mod"
                //    export {a as b} from "mod"
                //    export import i = require("mod")
                //    (for JavaScript files) require("mod")
                // Do not look for:
                //    AnySymbol.import("mod")
                //    AnySymbol.nested.import("mod")
                while (true) {
                    if (ts.scanner.getToken() === 1 /* EndOfFileToken */) {
                        break;
                    }
                    // check if at least one of alternative have moved scanner forward
                    if (tryConsumeDeclare() ||
                        tryConsumeImport() ||
                        tryConsumeExport() ||
                        (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) {
                        continue;
                    }
                    else {
                        nextToken();
                    }
                }
                ts.scanner.setText(undefined);
            }
            if (readImportFiles) {
                processImports();
            }
            ts.processCommentPragmas(pragmaContext, sourceText);
            ts.processPragmasIntoFields(pragmaContext, ts.noop);
            if (externalModule) {
                // for external modules module all nested ambient modules are augmentations
                if (ambientExternalModules) {
                    // move all detected ambient modules to imported files since they need to be resolved
                    for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) {
                        var decl = ambientExternalModules_1[_i];
                        importedFiles.push(decl.ref);
                    }
                }
                return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
            }
            else {
                // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
                var ambientModuleNames = void 0;
                if (ambientExternalModules) {
                    for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) {
                        var decl = ambientExternalModules_2[_a];
                        if (decl.depth === 0) {
                            if (!ambientModuleNames) {
                                ambientModuleNames = [];
                            }
                            ambientModuleNames.push(decl.ref.fileName);
                        }
                        else {
                            importedFiles.push(decl.ref);
                        }
                    }
                }
                return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
            }
        }
        ts.preProcessFile = preProcessFile;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var Rename;
        (function (Rename) {
            function getRenameInfo(program, sourceFile, position) {
                var node = ts.getTouchingPropertyName(sourceFile, position);
                var renameInfo = node && nodeIsEligibleForRename(node)
                    ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); })
                    : undefined;
                return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element);
            }
            Rename.getRenameInfo = getRenameInfo;
            function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) {
                var symbol = typeChecker.getSymbolAtLocation(node);
                if (!symbol)
                    return;
                // Only allow a symbol to be renamed if it actually has at least one declaration.
                var declarations = symbol.declarations;
                if (!declarations || declarations.length === 0)
                    return;
                // Disallow rename for elements that are defined in the standard TypeScript library.
                if (declarations.some(isDefinedInLibraryFile)) {
                    return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
                }
                // Cannot rename `default` as in `import { default as foo } from "./someModule";
                if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
                    return undefined;
                }
                if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) {
                    return getRenameInfoForModule(node, sourceFile, symbol);
                }
                var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
                var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */)
                    ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
                    : undefined;
                var displayName = specifierName || typeChecker.symbolToString(symbol);
                var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
                return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
            }
            function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
                if (!ts.isExternalModuleNameRelative(node.text)) {
                    return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import);
                }
                var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile);
                if (!moduleSourceFile)
                    return undefined;
                var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index");
                var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex;
                var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */;
                var indexAfterLastSlash = node.text.lastIndexOf("/") + 1;
                // Span should only be the last component of the path. + 1 to account for the quote character.
                var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash);
                return {
                    canRename: true,
                    fileToRename: name,
                    kind: kind,
                    displayName: name,
                    fullDisplayName: name,
                    kindModifiers: "" /* none */,
                    triggerSpan: triggerSpan,
                };
            }
            function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
                return {
                    canRename: true,
                    fileToRename: undefined,
                    kind: kind,
                    displayName: displayName,
                    fullDisplayName: fullDisplayName,
                    kindModifiers: kindModifiers,
                    triggerSpan: createTriggerSpanForNode(node, sourceFile)
                };
            }
            function getRenameInfoError(diagnostic) {
                return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) };
            }
            function createTriggerSpanForNode(node, sourceFile) {
                var start = node.getStart(sourceFile);
                var width = node.getWidth(sourceFile);
                if (node.kind === 9 /* StringLiteral */) {
                    // Exclude the quotes
                    start += 1;
                    width -= 2;
                }
                return ts.createTextSpan(start, width);
            }
            function nodeIsEligibleForRename(node) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                    case 9 /* StringLiteral */:
                    case 99 /* ThisKeyword */:
                        return true;
                    case 8 /* NumericLiteral */:
                        return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node);
                    default:
                        return false;
                }
            }
        })(Rename = ts.Rename || (ts.Rename = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var SignatureHelp;
        (function (SignatureHelp) {
            var InvocationKind;
            (function (InvocationKind) {
                InvocationKind[InvocationKind["Call"] = 0] = "Call";
                InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs";
                InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual";
            })(InvocationKind || (InvocationKind = {}));
            function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) {
                var typeChecker = program.getTypeChecker();
                // Decide whether to show signature help
                var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position);
                if (!startingToken) {
                    // We are at the beginning of the file
                    return undefined;
                }
                // Only need to be careful if the user typed a character and signature help wasn't showing.
                var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped";
                // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it.
                if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) {
                    return undefined;
                }
                var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker);
                if (!argumentInfo)
                    return undefined;
                cancellationToken.throwIfCancellationRequested();
                // Extra syntactic and semantic filtering of signature help
                var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
                cancellationToken.throwIfCancellationRequested();
                if (!candidateInfo) {
                    // We didn't have any sig help items produced by the TS compiler.  If this is a JS
                    // file, then see if we can figure out anything better.
                    return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined;
                }
                return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
                    return candidateInfo.kind === 0 /* Candidate */
                        ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker)
                        : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker);
                });
            }
            SignatureHelp.getSignatureHelpItems = getSignatureHelpItems;
            var CandidateOrTypeKind;
            (function (CandidateOrTypeKind) {
                CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate";
                CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type";
            })(CandidateOrTypeKind || (CandidateOrTypeKind = {}));
            function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
                var invocation = _a.invocation, argumentCount = _a.argumentCount;
                switch (invocation.kind) {
                    case 0 /* Call */: {
                        if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) {
                            return undefined;
                        }
                        var candidates = [];
                        var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217
                        return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature };
                    }
                    case 1 /* TypeArgs */: {
                        var called = invocation.called;
                        if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) {
                            return undefined;
                        }
                        var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker);
                        if (candidates.length !== 0)
                            return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) };
                        var symbol = checker.getSymbolAtLocation(called);
                        return symbol && { kind: 1 /* Type */, symbol: symbol };
                    }
                    case 2 /* Contextual */:
                        return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature };
                    default:
                        return ts.Debug.assertNever(invocation);
                }
            }
            function isSyntacticOwner(startingToken, node, sourceFile) {
                if (!ts.isCallOrNewExpression(node))
                    return false;
                var invocationChildren = node.getChildren(sourceFile);
                switch (startingToken.kind) {
                    case 19 /* OpenParenToken */:
                        return ts.contains(invocationChildren, startingToken);
                    case 26 /* CommaToken */: {
                        var containingList = ts.findContainingList(startingToken);
                        return !!containingList && ts.contains(invocationChildren, containingList);
                    }
                    case 27 /* LessThanToken */:
                        return containsPrecedingToken(startingToken, sourceFile, node.expression);
                    default:
                        return false;
                }
            }
            function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) {
                if (argumentInfo.invocation.kind === 2 /* Contextual */)
                    return undefined;
                // See if we can find some symbol with the call expression name that has call signatures.
                var expression = getExpressionFromInvocation(argumentInfo.invocation);
                var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined;
                var typeChecker = program.getTypeChecker();
                return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) {
                    return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) {
                        var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration);
                        var callSignatures = type && type.getCallSignatures();
                        if (callSignatures && callSignatures.length) {
                            return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); });
                        }
                    });
                });
            }
            function containsPrecedingToken(startingToken, sourceFile, container) {
                var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true));
                return ts.rangeContainsRange(container, precedingToken);
            }
            function getArgumentInfoForCompletions(node, position, sourceFile) {
                var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile);
                return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined
                    : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex };
            }
            SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions;
            function getArgumentOrParameterListInfo(node, sourceFile) {
                var info = getArgumentOrParameterListAndIndex(node, sourceFile);
                if (!info)
                    return undefined;
                var list = info.list, argumentIndex = info.argumentIndex;
                var argumentCount = getArgumentCount(list);
                if (argumentIndex !== 0) {
                    ts.Debug.assertLessThan(argumentIndex, argumentCount);
                }
                var argumentsSpan = getApplicableSpanForArguments(list, sourceFile);
                return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
            }
            function getArgumentOrParameterListAndIndex(node, sourceFile) {
                if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) {
                    // Find the list that starts right *after* the < or ( token.
                    // If the user has just opened a list, consider this item 0.
                    return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 };
                }
                else {
                    // findListItemInfo can return undefined if we are not in parent's argument list
                    // or type argument list. This includes cases where the cursor is:
                    //   - To the right of the closing parenthesis, non-substitution template, or template tail.
                    //   - Between the type arguments and the arguments (greater than token)
                    //   - On the target of the call (parent.func)
                    //   - On the 'new' keyword in a 'new' expression
                    var list = ts.findContainingList(node);
                    return list && { list: list, argumentIndex: getArgumentIndex(list, node) };
                }
            }
            /**
             * Returns relevant information for the argument list and the current argument if we are
             * in the argument of an invocation; returns undefined otherwise.
             */
            function getImmediatelyContainingArgumentInfo(node, position, sourceFile) {
                var parent = node.parent;
                if (ts.isCallOrNewExpression(parent)) {
                    var invocation = parent;
                    // There are 3 cases to handle:
                    //   1. The token introduces a list, and should begin a signature help session
                    //   2. The token is either not associated with a list, or ends a list, so the session should end
                    //   3. The token is buried inside a list, and should give signature help
                    //
                    // The following are examples of each:
                    //
                    //    Case 1:
                    //          foo<#T, U>(#a, b)    -> The token introduces a list, and should begin a signature help session
                    //    Case 2:
                    //          fo#o<T, U>#(a, b)#   -> The token is either not associated with a list, or ends a list, so the session should end
                    //    Case 3:
                    //          foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give signature help
                    // Find out if 'node' is an argument, a type argument, or neither
                    var info = getArgumentOrParameterListInfo(node, sourceFile);
                    if (!info)
                        return undefined;
                    var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
                    var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos;
                    return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
                }
                else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) {
                    // Check if we're actually inside the template;
                    // otherwise we'll fall out and return undefined.
                    if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
                        return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile);
                    }
                    return undefined;
                }
                else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) {
                    var templateExpression = parent;
                    var tagExpression = templateExpression.parent;
                    ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */);
                    var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
                    return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
                }
                else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) {
                    var templateSpan = parent;
                    var tagExpression = parent.parent.parent;
                    // If we're just after a template tail, don't show signature help.
                    if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) {
                        return undefined;
                    }
                    var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan);
                    var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile);
                    return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
                }
                else if (ts.isJsxOpeningLikeElement(parent)) {
                    // Provide a signature help for JSX opening element or JSX self-closing element.
                    // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems")
                    // i.e
                    //      export function MainButton(props: ButtonProps, context: any): JSX.Element { ... }
                    //      <MainButton /*signatureHelp*/
                    var attributeSpanStart = parent.attributes.pos;
                    var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false);
                    return {
                        isTypeParameterList: false,
                        invocation: { kind: 0 /* Call */, node: parent },
                        argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart),
                        argumentIndex: 0,
                        argumentCount: 1
                    };
                }
                else {
                    var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile);
                    if (typeArgInfo) {
                        var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments;
                        var invocation = { kind: 1 /* TypeArgs */, called: called };
                        var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end);
                        return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 };
                    }
                    return undefined;
                }
            }
            function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) {
                return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile);
            }
            function getHighestBinary(b) {
                return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b;
            }
            function countBinaryExpressionParameters(b) {
                return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2;
            }
            function tryGetParameterInfo(startingToken, _position, sourceFile, checker) {
                var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker);
                if (!info)
                    return undefined;
                var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
                var signatures = contextualType.getCallSignatures();
                if (signatures.length !== 1)
                    return undefined;
                var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) };
                return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
            }
            function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) {
                if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */)
                    return undefined;
                var parent = startingToken.parent;
                switch (parent.kind) {
                    case 193 /* ParenthesizedExpression */:
                    case 154 /* MethodDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                        var info = getArgumentOrParameterListInfo(startingToken, sourceFile);
                        if (!info)
                            return undefined;
                        var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
                        var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent);
                        return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
                    case 202 /* BinaryExpression */: {
                        var highestBinary = getHighestBinary(parent);
                        var contextualType_1 = checker.getContextualType(highestBinary);
                        var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1;
                        var argumentCount_1 = countBinaryExpressionParameters(highestBinary);
                        return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) };
                    }
                    default:
                        return undefined;
                }
            }
            // The type of a function type node has a symbol at that node, but it's better to use the symbol for a parameter or type alias.
            function chooseBetterSymbol(s) {
                return s.name === "__type" /* Type */
                    ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s
                    : s;
            }
            function getArgumentIndex(argumentsList, node) {
                // The list we got back can include commas.  In the presence of errors it may
                // also just have nodes without commas.  For example "Foo(a b c)" will have 3
                // args without commas. We want to find what index we're at.  So we count
                // forward until we hit ourselves, only incrementing the index if it isn't a
                // comma.
                //
                // Note: the subtlety around trailing commas (in getArgumentCount) does not apply
                // here.  That's because we're only walking forward until we hit the node we're
                // on.  In that case, even if we're after the trailing comma, we'll still see
                // that trailing comma in the list, and we'll have generated the appropriate
                // arg index.
                var argumentIndex = 0;
                for (var _i = 0, _a = argumentsList.getChildren(); _i < _a.length; _i++) {
                    var child = _a[_i];
                    if (child === node) {
                        break;
                    }
                    if (child.kind !== 26 /* CommaToken */) {
                        argumentIndex++;
                    }
                }
                return argumentIndex;
            }
            function getArgumentCount(argumentsList) {
                // The argument count for a list is normally the number of non-comma children it has.
                // For example, if you have "Foo(a,b)" then there will be three children of the arg
                // list 'a' '<comma>' 'b'.  So, in this case the arg count will be 2.  However, there
                // is a small subtlety.  If you have "Foo(a,)", then the child list will just have
                // 'a' '<comma>'.  So, in the case where the last child is a comma, we increase the
                // arg count by one to compensate.
                //
                // Note: this subtlety only applies to the last comma.  If you had "Foo(a,," then
                // we'll have: 'a' '<comma>' '<missing>'
                // That will give us 2 non-commas.  We then add one for the last comma, giving us an
                // arg count of 3.
                var listChildren = argumentsList.getChildren();
                var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26 /* CommaToken */; });
                if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) {
                    argumentCount++;
                }
                return argumentCount;
            }
            // spanIndex is either the index for a given template span.
            // This does not give appropriate results for a NoSubstitutionTemplateLiteral
            function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) {
                // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1.
                // There are three cases we can encounter:
                //      1. We are precisely in the template literal (argIndex = 0).
                //      2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1).
                //      3. We are directly to the right of the template literal, but because we look for the token on the left,
                //          not enough to put us in the substitution expression; we should consider ourselves part of
                //          the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1).
                //
                // tslint:disable no-double-space
                // Example: f  `# abcd $#{#  1 + 1#  }# efghi ${ #"#hello"#  }  #  `
                //              ^       ^ ^       ^   ^          ^ ^      ^     ^
                // Case:        1       1 3       2   1          3 2      2     1
                // tslint:enable no-double-space
                ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node.");
                if (ts.isTemplateLiteralToken(node)) {
                    if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
                        return 0;
                    }
                    return spanIndex + 2;
                }
                return spanIndex + 1;
            }
            function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) {
                // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument.
                var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1;
                if (argumentIndex !== 0) {
                    ts.Debug.assertLessThan(argumentIndex, argumentCount);
                }
                return {
                    isTypeParameterList: false,
                    invocation: { kind: 0 /* Call */, node: tagExpression },
                    argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile),
                    argumentIndex: argumentIndex,
                    argumentCount: argumentCount
                };
            }
            function getApplicableSpanForArguments(argumentsList, sourceFile) {
                // We use full start and skip trivia on the end because we want to include trivia on
                // both sides. For example,
                //
                //    foo(   /*comment */     a, b, c      /*comment*/     )
                //        |                                               |
                //
                // The applicable span is from the first bar to the second bar (inclusive,
                // but not including parentheses)
                var applicableSpanStart = argumentsList.getFullStart();
                var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false);
                return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
            }
            function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) {
                var template = taggedTemplate.template;
                var applicableSpanStart = template.getStart();
                var applicableSpanEnd = template.getEnd();
                // We need to adjust the end position for the case where the template does not have a tail.
                // Otherwise, we will not show signature help past the expression.
                // For example,
                //
                //      ` ${ 1 + 1 foo(10)
                //       |       |
                // This is because a Missing node has no width. However, what we actually want is to include trivia
                // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail.
                if (template.kind === 204 /* TemplateExpression */) {
                    var lastSpan = ts.last(template.templateSpans);
                    if (lastSpan.literal.getFullWidth() === 0) {
                        applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
                    }
                }
                return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
            }
            function getContainingArgumentInfo(node, position, sourceFile, checker) {
                var _loop_14 = function (n) {
                    // If the node is not a subspan of its parent, this is a big problem.
                    // There have been crashes that might be caused by this violation.
                    ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); });
                    var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker);
                    if (argumentInfo) {
                        return { value: argumentInfo };
                    }
                };
                for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) {
                    var state_4 = _loop_14(n);
                    if (typeof state_4 === "object")
                        return state_4.value;
                }
                return undefined;
            }
            function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) {
                var children = parent.getChildren(sourceFile);
                var indexOfOpenerToken = children.indexOf(openerToken);
                ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
                return children[indexOfOpenerToken + 1];
            }
            function getExpressionFromInvocation(invocation) {
                return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called;
            }
            function getEnclosingDeclarationFromInvocation(invocation) {
                return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
            }
            var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
            function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
                var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
                var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
                var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation));
                var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray;
                var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); });
                if (argumentIndex !== 0) {
                    ts.Debug.assertLessThan(argumentIndex, argumentCount);
                }
                var selectedItemIndex = candidates.indexOf(resolvedSignature);
                ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function.
                return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount };
            }
            function createTypeHelpItems(symbol, _a, sourceFile, checker) {
                var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
                var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
                if (!typeParameters)
                    return undefined;
                var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)];
                return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount };
            }
            function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) {
                var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol);
                var printer = ts.createPrinter({ removeComments: true });
                var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
                var documentation = symbol.getDocumentationComment(checker);
                var tags = symbol.getJsDocTags();
                var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]);
                return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
            }
            var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()];
            function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) {
                var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix;
                var prefixDisplayParts = callTargetDisplayParts.concat(prefix);
                var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker));
                var documentation = candidateSignature.getDocumentationComment(checker);
                var tags = candidateSignature.getJsDocTags();
                return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
            }
            function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) {
                return ts.mapToDisplayParts(function (writer) {
                    writer.writePunctuation(":");
                    writer.writeSpace(" ");
                    var predicate = checker.getTypePredicateOfSignature(candidateSignature);
                    if (predicate) {
                        checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer);
                    }
                    else {
                        checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer);
                    }
                });
            }
            function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
                var typeParameters = (candidateSignature.target || candidateSignature).typeParameters;
                var printer = ts.createPrinter({ removeComments: true });
                var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
                var parameterParts = ts.mapToDisplayParts(function (writer) {
                    var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
                    var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
                    printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer);
                });
                return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) };
            }
            function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
                var isVariadic = candidateSignature.hasRestParameter;
                var printer = ts.createPrinter({ removeComments: true });
                var typeParameterParts = ts.mapToDisplayParts(function (writer) {
                    if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
                        var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); }));
                        printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer);
                    }
                });
                var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
                return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] };
            }
            function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
                var displayParts = ts.mapToDisplayParts(function (writer) {
                    var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
                    printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
                });
                var isOptional = checker.isOptionalParameter(parameter.valueDeclaration);
                return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional };
            }
            function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) {
                var displayParts = ts.mapToDisplayParts(function (writer) {
                    var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration);
                    printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
                });
                return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false };
            }
        })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M])
        var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
        var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
        var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
        function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) {
            var sourcemappedFileCache;
            return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache };
            function scanForSourcemapURL(fileName) {
                var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
                if (!mappedFile) {
                    return;
                }
                var starts = ts.getLineStarts(mappedFile);
                for (var index = starts.length - 1; index >= 0; index--) {
                    var lineText = mappedFile.text.substring(starts[index], starts[index + 1]);
                    var comment = sourceMapCommentRegExp.exec(lineText);
                    if (comment) {
                        return comment[1];
                    }
                    // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
                    else if (!lineText.match(whitespaceOrMapCommentRegExp)) {
                        break;
                    }
                }
            }
            function convertDocumentToSourceMapper(file, contents, mapFileName) {
                var maps;
                try {
                    maps = JSON.parse(contents);
                }
                catch (_a) {
                    // swallow error
                }
                if (!maps || !maps.sources || !maps.file || !maps.mappings) {
                    // obviously invalid map
                    return file.sourceMapper = ts.sourcemaps.identitySourceMapper;
                }
                return file.sourceMapper = ts.sourcemaps.decode({
                    readFile: function (s) { return host.readFile(s); },
                    fileExists: function (s) { return host.fileExists(s); },
                    getCanonicalFileName: getCanonicalFileName,
                    log: log,
                }, mapFileName, maps, getProgram(), sourcemappedFileCache);
            }
            function getSourceMapper(fileName, file) {
                if (!host.readFile || !host.fileExists) {
                    return file.sourceMapper = ts.sourcemaps.identitySourceMapper;
                }
                if (file.sourceMapper) {
                    return file.sourceMapper;
                }
                var mapFileName = scanForSourcemapURL(fileName);
                if (mapFileName) {
                    var match = base64UrlRegExp.exec(mapFileName);
                    if (match) {
                        if (match[1]) {
                            var base64Object = match[1];
                            return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName);
                        }
                        // Not a data URL we can parse, skip it
                        mapFileName = undefined;
                    }
                }
                var possibleMapLocations = [];
                if (mapFileName) {
                    possibleMapLocations.push(mapFileName);
                }
                possibleMapLocations.push(fileName + ".map");
                for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) {
                    var location = possibleMapLocations_1[_i];
                    var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName);
                    if (host.fileExists(mapPath)) {
                        return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217
                    }
                }
                return file.sourceMapper = ts.sourcemaps.identitySourceMapper;
            }
            function tryGetOriginalLocation(info) {
                if (!ts.isDeclarationFileName(info.fileName))
                    return undefined;
                var file = getFile(info.fileName);
                if (!file)
                    return undefined;
                var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info);
                return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc;
            }
            function tryGetGeneratedLocation(info) {
                var program = getProgram();
                var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName);
                if (declarationPath === undefined)
                    return undefined;
                var declarationFile = getFile(declarationPath);
                if (!declarationFile)
                    return undefined;
                var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info);
                return newLoc === info ? undefined : newLoc;
            }
            function getFile(fileName) {
                return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
            }
            function toLineColumnOffset(fileName, position) {
                var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
                var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217
                return file.getLineAndCharacterOfPosition(position);
            }
            function clearCache() {
                sourcemappedFileCache = ts.createSourceFileLikeCache(host);
            }
        }
        ts.getSourceMapper = getSourceMapper;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
            program.getSemanticDiagnostics(sourceFile, cancellationToken);
            var diags = [];
            var checker = program.getTypeChecker();
            if (sourceFile.commonJsModuleIndicator &&
                (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
                containsTopLevelCommonjs(sourceFile)) {
                diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
            }
            var isJsFile = ts.isSourceFileJS(sourceFile);
            check(sourceFile);
            if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
                for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
                    var moduleSpecifier = _a[_i];
                    var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
                    var name = importNameForConvertToDefaultImport(importNode);
                    if (!name)
                        continue;
                    var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
                    var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
                    if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
                        diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
                    }
                }
            }
            ts.addRange(diags, sourceFile.bindSuggestionDiagnostics);
            ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken));
            return diags.sort(function (d1, d2) { return d1.start - d2.start; });
            function check(node) {
                if (isJsFile) {
                    switch (node.kind) {
                        case 194 /* FunctionExpression */:
                            var decl = ts.getDeclarationOfExpando(node);
                            if (decl) {
                                var symbol_2 = decl.symbol;
                                if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) {
                                    diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
                                    break;
                                }
                            }
                        // falls through if no diagnostic was created
                        case 237 /* FunctionDeclaration */:
                            var symbol = node.symbol;
                            if (symbol.members && (symbol.members.size > 0)) {
                                diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
                            }
                            break;
                    }
                }
                else {
                    if (ts.isVariableStatement(node) &&
                        node.parent === sourceFile &&
                        node.declarationList.flags & 2 /* Const */ &&
                        node.declarationList.declarations.length === 1) {
                        var init = node.declarationList.declarations[0].initializer;
                        if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) {
                            diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import));
                        }
                    }
                    if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
                        diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
                    }
                }
                if (ts.isFunctionLikeDeclaration(node)) {
                    addConvertToAsyncFunctionDiagnostics(node, checker, diags);
                }
                node.forEachChild(check);
            }
        }
        ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
        // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
        function containsTopLevelCommonjs(sourceFile) {
            return sourceFile.statements.some(function (statement) {
                switch (statement.kind) {
                    case 217 /* VariableStatement */:
                        return statement.declarationList.declarations.some(function (decl) {
                            return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
                        }); // TODO: GH#18217
                    case 219 /* ExpressionStatement */: {
                        var expression = statement.expression;
                        if (!ts.isBinaryExpression(expression))
                            return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
                        var kind = ts.getAssignmentDeclarationKind(expression);
                        return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
                    }
                    default:
                        return false;
                }
            });
        }
        function propertyAccessLeftHandSide(node) {
            return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
        }
        function importNameForConvertToDefaultImport(node) {
            switch (node.kind) {
                case 247 /* ImportDeclaration */:
                    var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
                    return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
                        ? importClause.namedBindings.name
                        : undefined;
                case 246 /* ImportEqualsDeclaration */:
                    return node.name;
                default:
                    return undefined;
            }
        }
        function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
            if (ts.isAsyncFunction(node) || !node.body) {
                return;
            }
            var functionType = checker.getTypeAtLocation(node);
            var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */);
            var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined;
            if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) {
                return;
            }
            // collect all the return statements
            // check that a property access expression exists in there and that it is a handler
            var returnStatements = getReturnStatementsWithPromiseHandlers(node);
            if (returnStatements.length > 0) {
                diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function));
            }
        }
        function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) {
            return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator;
        }
        /** @internal */
        function getReturnStatementsWithPromiseHandlers(node) {
            var returnStatements = [];
            if (ts.isFunctionLike(node)) {
                ts.forEachChild(node, visit);
            }
            else {
                visit(node);
            }
            function visit(child) {
                if (ts.isFunctionLike(child)) {
                    return;
                }
                if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) {
                    returnStatements.push(child);
                }
                ts.forEachChild(child, visit);
            }
            return returnStatements;
        }
        ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers;
        // Should be kept up to date with transformExpression in convertToAsyncFunction.ts
        function isFixablePromiseHandler(node) {
            // ensure outermost call exists and is a promise handler
            if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) {
                return false;
            }
            // ensure all chained calls are valid
            var currentNode = node.expression;
            while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) {
                if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) {
                    return false;
                }
                currentNode = currentNode.expression;
            }
            return true;
        }
        function isPromiseHandler(node) {
            return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch"));
        }
        // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts
        function isFixablePromiseArgument(arg) {
            switch (arg.kind) {
                case 95 /* NullKeyword */:
                case 71 /* Identifier */: // identifier includes undefined
                case 237 /* FunctionDeclaration */:
                case 194 /* FunctionExpression */:
                case 195 /* ArrowFunction */:
                    return true;
                default:
                    return false;
            }
        }
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var SymbolDisplay;
        (function (SymbolDisplay) {
            // TODO(drosen): use contextual SemanticMeaning.
            function getSymbolKind(typeChecker, symbol, location) {
                var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
                if (result !== "" /* unknown */) {
                    return result;
                }
                var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
                if (flags & 32 /* Class */) {
                    return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ?
                        "local class" /* localClassElement */ : "class" /* classElement */;
                }
                if (flags & 384 /* Enum */)
                    return "enum" /* enumElement */;
                if (flags & 524288 /* TypeAlias */)
                    return "type" /* typeElement */;
                if (flags & 64 /* Interface */)
                    return "interface" /* interfaceElement */;
                if (flags & 262144 /* TypeParameter */)
                    return "type parameter" /* typeParameterElement */;
                if (flags & 262144 /* TypeParameter */)
                    return "type parameter" /* typeParameterElement */;
                if (flags & 8 /* EnumMember */)
                    return "enum member" /* enumMemberElement */;
                if (flags & 2097152 /* Alias */)
                    return "alias" /* alias */;
                if (flags & 1536 /* Module */)
                    return "module" /* moduleElement */;
                return result;
            }
            SymbolDisplay.getSymbolKind = getSymbolKind;
            function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) {
                var roots = typeChecker.getRootSymbols(symbol);
                // If this is a method from a mapped type, leave as a method so long as it still has a call signature.
                if (roots.length === 1
                    && ts.first(roots).flags & 8192 /* Method */
                    // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`.
                    && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) {
                    return "method" /* memberFunctionElement */;
                }
                if (typeChecker.isUndefinedSymbol(symbol)) {
                    return "var" /* variableElement */;
                }
                if (typeChecker.isArgumentsSymbol(symbol)) {
                    return "local var" /* localVariableElement */;
                }
                if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) {
                    return "parameter" /* parameterElement */;
                }
                var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
                if (flags & 3 /* Variable */) {
                    if (ts.isFirstDeclarationOfSymbolParameter(symbol)) {
                        return "parameter" /* parameterElement */;
                    }
                    else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) {
                        return "const" /* constElement */;
                    }
                    else if (ts.forEach(symbol.declarations, ts.isLet)) {
                        return "let" /* letElement */;
                    }
                    return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */;
                }
                if (flags & 16 /* Function */)
                    return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */;
                if (flags & 32768 /* GetAccessor */)
                    return "getter" /* memberGetAccessorElement */;
                if (flags & 65536 /* SetAccessor */)
                    return "setter" /* memberSetAccessorElement */;
                if (flags & 8192 /* Method */)
                    return "method" /* memberFunctionElement */;
                if (flags & 16384 /* Constructor */)
                    return "constructor" /* constructorImplementationElement */;
                if (flags & 4 /* Property */) {
                    if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) {
                        // If union property is result of union of non method (property/accessors/variables), it is labeled as property
                        var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) {
                            var rootSymbolFlags = rootSymbol.getFlags();
                            if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) {
                                return "property" /* memberVariableElement */;
                            }
                            // May be a Function if this was from `typeof N` with `namespace N { function f();. }`.
                            ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */)));
                        });
                        if (!unionPropertyKind) {
                            // If this was union of all methods,
                            // make sure it has call signatures before we can label it as method
                            var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
                            if (typeOfUnionProperty.getCallSignatures().length) {
                                return "method" /* memberFunctionElement */;
                            }
                            return "property" /* memberVariableElement */;
                        }
                        return unionPropertyKind;
                    }
                    // If we requested completions after `x.` at the top-level, we may be at a source file location.
                    switch (location.parent && location.parent.kind) {
                        // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'.
                        case 260 /* JsxOpeningElement */:
                        case 258 /* JsxElement */:
                        case 259 /* JsxSelfClosingElement */:
                            return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */;
                        case 265 /* JsxAttribute */:
                            return "JSX attribute" /* jsxAttribute */;
                        default:
                            return "property" /* memberVariableElement */;
                    }
                }
                return "" /* unknown */;
            }
            function getSymbolModifiers(symbol) {
                var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0
                    ? ts.getNodeModifiers(symbol.declarations[0])
                    : "" /* none */;
                var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ?
                    "optional" /* optionalModifier */
                    : "" /* none */;
                return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers;
            }
            SymbolDisplay.getSymbolModifiers = getSymbolModifiers;
            // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location
            function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) {
                if (semanticMeaning === void 0) {
                    semanticMeaning = ts.getMeaningFromLocation(location);
                }
                var displayParts = [];
                var documentation;
                var tags;
                var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
                var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */;
                var hasAddedSymbolInfo = false;
                var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location);
                var type;
                var printer;
                var documentationFromAlias;
                var tagsFromAlias;
                if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) {
                    return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined };
                }
                // Class at constructor site need to be shown as constructor apart from property,method, vars
                if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) {
                    // If it is accessor they are allowed only if location is at name of the accessor
                    if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) {
                        symbolKind = "property" /* memberVariableElement */;
                    }
                    var signature = void 0;
                    type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location);
                    if (location.parent && location.parent.kind === 187 /* PropertyAccessExpression */) {
                        var right = location.parent.name;
                        // Either the location is on the right of a property access, or on the left and the right is missing
                        if (right === location || (right && right.getFullWidth() === 0)) {
                            location = location.parent;
                        }
                    }
                    // try get the call/construct signature from the type if it matches
                    var callExpressionLike = void 0;
                    if (ts.isCallOrNewExpression(location)) {
                        callExpressionLike = location;
                    }
                    else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) {
                        callExpressionLike = location.parent;
                    }
                    else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) {
                        callExpressionLike = location.parent;
                    }
                    if (callExpressionLike) {
                        var candidateSignatures = [];
                        signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217
                        var useConstructSignatures = callExpressionLike.kind === 190 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */);
                        var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
                        if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) {
                            // Get the first signature if there is one -- allSignatures may contain
                            // either the original signature or its target, so check for either
                            signature = allSignatures.length ? allSignatures[0] : undefined;
                        }
                        if (signature) {
                            if (useConstructSignatures && (symbolFlags & 32 /* Class */)) {
                                // Constructor
                                symbolKind = "constructor" /* constructorImplementationElement */;
                                addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
                            }
                            else if (symbolFlags & 2097152 /* Alias */) {
                                symbolKind = "alias" /* alias */;
                                pushSymbolKind(symbolKind);
                                displayParts.push(ts.spacePart());
                                if (useConstructSignatures) {
                                    displayParts.push(ts.keywordPart(94 /* NewKeyword */));
                                    displayParts.push(ts.spacePart());
                                }
                                addFullSymbolName(symbol);
                            }
                            else {
                                addPrefixForAnyFunctionOrVar(symbol, symbolKind);
                            }
                            switch (symbolKind) {
                                case "JSX attribute" /* jsxAttribute */:
                                case "property" /* memberVariableElement */:
                                case "var" /* variableElement */:
                                case "const" /* constElement */:
                                case "let" /* letElement */:
                                case "parameter" /* parameterElement */:
                                case "local var" /* localVariableElement */:
                                    // If it is call or construct signature of lambda's write type name
                                    displayParts.push(ts.punctuationPart(56 /* ColonToken */));
                                    displayParts.push(ts.spacePart());
                                    if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) {
                                        ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */));
                                        displayParts.push(ts.lineBreakPart());
                                    }
                                    if (useConstructSignatures) {
                                        displayParts.push(ts.keywordPart(94 /* NewKeyword */));
                                        displayParts.push(ts.spacePart());
                                    }
                                    addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */);
                                    break;
                                default:
                                    // Just signature
                                    addSignatureDisplayParts(signature, allSignatures);
                            }
                            hasAddedSymbolInfo = true;
                        }
                    }
                    else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration
                        (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 155 /* Constructor */)) { // At constructor keyword of constructor declaration
                        // get the signature from the declaration and write it
                        var functionDeclaration_1 = location.parent;
                        // Use function declaration to write the signatures only if the symbol corresponding to this declaration
                        var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) {
                            return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1);
                        });
                        if (locationIsSymbolDeclaration) {
                            var allSignatures = functionDeclaration_1.kind === 155 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
                            if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) {
                                signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217
                            }
                            else {
                                signature = allSignatures[0];
                            }
                            if (functionDeclaration_1.kind === 155 /* Constructor */) {
                                // show (constructor) Type(...) signature
                                symbolKind = "constructor" /* constructorImplementationElement */;
                                addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
                            }
                            else {
                                // (function/method) symbol(..signature)
                                addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 158 /* CallSignature */ &&
                                    !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind);
                            }
                            addSignatureDisplayParts(signature, allSignatures);
                            hasAddedSymbolInfo = true;
                        }
                    }
                }
                if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
                    addAliasPrefixIfNecessary();
                    if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) {
                        // Special case for class expressions because we would like to indicate that
                        // the class name is local to the class body (similar to function expression)
                        //      (local class) class <className>
                        pushSymbolKind("local class" /* localClassElement */);
                    }
                    else {
                        // Class declaration has name which is not local.
                        displayParts.push(ts.keywordPart(75 /* ClassKeyword */));
                    }
                    displayParts.push(ts.spacePart());
                    addFullSymbolName(symbol);
                    writeTypeParametersOfSymbol(symbol, sourceFile);
                }
                if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) {
                    prefixNextMeaning();
                    displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */));
                    displayParts.push(ts.spacePart());
                    addFullSymbolName(symbol);
                    writeTypeParametersOfSymbol(symbol, sourceFile);
                }
                if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) {
                    prefixNextMeaning();
                    displayParts.push(ts.keywordPart(139 /* TypeKeyword */));
                    displayParts.push(ts.spacePart());
                    addFullSymbolName(symbol);
                    writeTypeParametersOfSymbol(symbol, sourceFile);
                    displayParts.push(ts.spacePart());
                    displayParts.push(ts.operatorPart(58 /* EqualsToken */));
                    displayParts.push(ts.spacePart());
                    ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */));
                }
                if (symbolFlags & 384 /* Enum */) {
                    prefixNextMeaning();
                    if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) {
                        displayParts.push(ts.keywordPart(76 /* ConstKeyword */));
                        displayParts.push(ts.spacePart());
                    }
                    displayParts.push(ts.keywordPart(83 /* EnumKeyword */));
                    displayParts.push(ts.spacePart());
                    addFullSymbolName(symbol);
                }
                if (symbolFlags & 1536 /* Module */) {
                    prefixNextMeaning();
                    var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */);
                    var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */;
                    displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */));
                    displayParts.push(ts.spacePart());
                    addFullSymbolName(symbol);
                }
                if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) {
                    prefixNextMeaning();
                    displayParts.push(ts.punctuationPart(19 /* OpenParenToken */));
                    displayParts.push(ts.textPart("type parameter"));
                    displayParts.push(ts.punctuationPart(20 /* CloseParenToken */));
                    displayParts.push(ts.spacePart());
                    addFullSymbolName(symbol);
                    if (symbol.parent) {
                        // Class/Interface type parameter
                        addInPrefix();
                        addFullSymbolName(symbol.parent, enclosingDeclaration);
                        writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration);
                    }
                    else {
                        // Method/function type parameter
                        var decl = ts.getDeclarationOfKind(symbol, 148 /* TypeParameter */);
                        if (decl === undefined)
                            return ts.Debug.fail();
                        var declaration = decl.parent;
                        if (declaration) {
                            if (ts.isFunctionLikeKind(declaration.kind)) {
                                addInPrefix();
                                var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217
                                if (declaration.kind === 159 /* ConstructSignature */) {
                                    displayParts.push(ts.keywordPart(94 /* NewKeyword */));
                                    displayParts.push(ts.spacePart());
                                }
                                else if (declaration.kind !== 158 /* CallSignature */ && declaration.name) {
                                    addFullSymbolName(declaration.symbol);
                                }
                                ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
                            }
                            else if (declaration.kind === 240 /* TypeAliasDeclaration */) {
                                // Type alias type parameter
                                // For example
                                //      type list<T> = T[]; // Both T will go through same code path
                                addInPrefix();
                                displayParts.push(ts.keywordPart(139 /* TypeKeyword */));
                                displayParts.push(ts.spacePart());
                                addFullSymbolName(declaration.symbol);
                                writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
                            }
                        }
                    }
                }
                if (symbolFlags & 8 /* EnumMember */) {
                    symbolKind = "enum member" /* enumMemberElement */;
                    addPrefixForAnyFunctionOrVar(symbol, "enum member");
                    var declaration = symbol.declarations[0];
                    if (declaration.kind === 276 /* EnumMember */) {
                        var constantValue = typeChecker.getConstantValue(declaration);
                        if (constantValue !== undefined) {
                            displayParts.push(ts.spacePart());
                            displayParts.push(ts.operatorPart(58 /* EqualsToken */));
                            displayParts.push(ts.spacePart());
                            displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral));
                        }
                    }
                }
                if (symbolFlags & 2097152 /* Alias */) {
                    prefixNextMeaning();
                    if (!hasAddedSymbolInfo) {
                        var resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
                        if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) {
                            var resolvedNode = resolvedSymbol.declarations[0];
                            var declarationName = ts.getNameOfDeclaration(resolvedNode);
                            if (declarationName) {
                                var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) &&
                                    ts.hasModifier(resolvedNode, 2 /* Ambient */);
                                var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration;
                                var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol);
                                displayParts.push.apply(displayParts, resolvedInfo.displayParts);
                                displayParts.push(ts.lineBreakPart());
                                documentationFromAlias = resolvedInfo.documentation;
                                tagsFromAlias = resolvedInfo.tags;
                            }
                        }
                    }
                    switch (symbol.declarations[0].kind) {
                        case 245 /* NamespaceExportDeclaration */:
                            displayParts.push(ts.keywordPart(84 /* ExportKeyword */));
                            displayParts.push(ts.spacePart());
                            displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */));
                            break;
                        case 252 /* ExportAssignment */:
                            displayParts.push(ts.keywordPart(84 /* ExportKeyword */));
                            displayParts.push(ts.spacePart());
                            displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */));
                            break;
                        case 255 /* ExportSpecifier */:
                            displayParts.push(ts.keywordPart(84 /* ExportKeyword */));
                            break;
                        default:
                            displayParts.push(ts.keywordPart(91 /* ImportKeyword */));
                    }
                    displayParts.push(ts.spacePart());
                    addFullSymbolName(symbol);
                    ts.forEach(symbol.declarations, function (declaration) {
                        if (declaration.kind === 246 /* ImportEqualsDeclaration */) {
                            var importEqualsDeclaration = declaration;
                            if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
                                displayParts.push(ts.spacePart());
                                displayParts.push(ts.operatorPart(58 /* EqualsToken */));
                                displayParts.push(ts.spacePart());
                                displayParts.push(ts.keywordPart(133 /* RequireKeyword */));
                                displayParts.push(ts.punctuationPart(19 /* OpenParenToken */));
                                displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral));
                                displayParts.push(ts.punctuationPart(20 /* CloseParenToken */));
                            }
                            else {
                                var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference);
                                if (internalAliasSymbol) {
                                    displayParts.push(ts.spacePart());
                                    displayParts.push(ts.operatorPart(58 /* EqualsToken */));
                                    displayParts.push(ts.spacePart());
                                    addFullSymbolName(internalAliasSymbol, enclosingDeclaration);
                                }
                            }
                            return true;
                        }
                    });
                }
                if (!hasAddedSymbolInfo) {
                    if (symbolKind !== "" /* unknown */) {
                        if (type) {
                            if (isThisExpression) {
                                prefixNextMeaning();
                                displayParts.push(ts.keywordPart(99 /* ThisKeyword */));
                            }
                            else {
                                addPrefixForAnyFunctionOrVar(symbol, symbolKind);
                            }
                            // For properties, variables and local vars: show the type
                            if (symbolKind === "property" /* memberVariableElement */ ||
                                symbolKind === "JSX attribute" /* jsxAttribute */ ||
                                symbolFlags & 3 /* Variable */ ||
                                symbolKind === "local var" /* localVariableElement */ ||
                                isThisExpression) {
                                displayParts.push(ts.punctuationPart(56 /* ColonToken */));
                                displayParts.push(ts.spacePart());
                                // If the type is type parameter, format it specially
                                if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) {
                                    var typeParameterParts = ts.mapToDisplayParts(function (writer) {
                                        var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration);
                                        getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
                                    });
                                    ts.addRange(displayParts, typeParameterParts);
                                }
                                else {
                                    ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration));
                                }
                            }
                            else if (symbolFlags & 16 /* Function */ ||
                                symbolFlags & 8192 /* Method */ ||
                                symbolFlags & 16384 /* Constructor */ ||
                                symbolFlags & 131072 /* Signature */ ||
                                symbolFlags & 98304 /* Accessor */ ||
                                symbolKind === "method" /* memberFunctionElement */) {
                                var allSignatures = type.getNonNullableType().getCallSignatures();
                                if (allSignatures.length) {
                                    addSignatureDisplayParts(allSignatures[0], allSignatures);
                                }
                            }
                        }
                    }
                    else {
                        symbolKind = getSymbolKind(typeChecker, symbol, location);
                    }
                }
                if (!documentation) {
                    documentation = symbol.getDocumentationComment(typeChecker);
                    tags = symbol.getJsDocTags();
                    if (documentation.length === 0 && symbolFlags & 4 /* Property */) {
                        // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
                        // there documentation comments might be attached to the right hand side symbol of their declarations.
                        // The pattern of such special property access is that the parent symbol is the symbol of the file.
                        if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) {
                            for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                                var declaration = _a[_i];
                                if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) {
                                    continue;
                                }
                                var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
                                if (!rhsSymbol) {
                                    continue;
                                }
                                documentation = rhsSymbol.getDocumentationComment(typeChecker);
                                tags = rhsSymbol.getJsDocTags();
                                if (documentation.length > 0) {
                                    break;
                                }
                            }
                        }
                    }
                }
                if (documentation.length === 0 && documentationFromAlias) {
                    documentation = documentationFromAlias;
                }
                if (tags.length === 0 && tagsFromAlias) {
                    tags = tagsFromAlias;
                }
                return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags };
                function getPrinter() {
                    if (!printer) {
                        printer = ts.createPrinter({ removeComments: true });
                    }
                    return printer;
                }
                function prefixNextMeaning() {
                    if (displayParts.length) {
                        displayParts.push(ts.lineBreakPart());
                    }
                    addAliasPrefixIfNecessary();
                }
                function addAliasPrefixIfNecessary() {
                    if (alias) {
                        pushSymbolKind("alias" /* alias */);
                        displayParts.push(ts.spacePart());
                    }
                }
                function addInPrefix() {
                    displayParts.push(ts.spacePart());
                    displayParts.push(ts.keywordPart(92 /* InKeyword */));
                    displayParts.push(ts.spacePart());
                }
                function addFullSymbolName(symbolToDisplay, enclosingDeclaration) {
                    if (alias && symbolToDisplay === symbol) {
                        symbolToDisplay = alias;
                    }
                    var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */);
                    ts.addRange(displayParts, fullSymbolDisplayParts);
                    if (symbol.flags & 16777216 /* Optional */) {
                        displayParts.push(ts.punctuationPart(55 /* QuestionToken */));
                    }
                }
                function addPrefixForAnyFunctionOrVar(symbol, symbolKind) {
                    prefixNextMeaning();
                    if (symbolKind) {
                        pushSymbolKind(symbolKind);
                        if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) {
                            displayParts.push(ts.spacePart());
                            addFullSymbolName(symbol);
                        }
                    }
                }
                function pushSymbolKind(symbolKind) {
                    switch (symbolKind) {
                        case "var" /* variableElement */:
                        case "function" /* functionElement */:
                        case "let" /* letElement */:
                        case "const" /* constElement */:
                        case "constructor" /* constructorImplementationElement */:
                            displayParts.push(ts.textOrKeywordPart(symbolKind));
                            return;
                        default:
                            displayParts.push(ts.punctuationPart(19 /* OpenParenToken */));
                            displayParts.push(ts.textOrKeywordPart(symbolKind));
                            displayParts.push(ts.punctuationPart(20 /* CloseParenToken */));
                            return;
                    }
                }
                function addSignatureDisplayParts(signature, allSignatures, flags) {
                    if (flags === void 0) {
                        flags = 0 /* None */;
                    }
                    ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */));
                    if (allSignatures.length > 1) {
                        displayParts.push(ts.spacePart());
                        displayParts.push(ts.punctuationPart(19 /* OpenParenToken */));
                        displayParts.push(ts.operatorPart(37 /* PlusToken */));
                        displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral));
                        displayParts.push(ts.spacePart());
                        displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads"));
                        displayParts.push(ts.punctuationPart(20 /* CloseParenToken */));
                    }
                    var docComment = signature.getDocumentationComment(typeChecker);
                    documentation = docComment.length === 0 ? undefined : docComment;
                    tags = signature.getJsDocTags();
                }
                function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) {
                    var typeParameterParts = ts.mapToDisplayParts(function (writer) {
                        var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration);
                        getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
                    });
                    ts.addRange(displayParts, typeParameterParts);
                }
            }
            SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind;
            function isLocalVariableOrFunction(symbol) {
                if (symbol.parent) {
                    return false; // This is exported symbol
                }
                return ts.forEach(symbol.declarations, function (declaration) {
                    // Function expressions are local
                    if (declaration.kind === 194 /* FunctionExpression */) {
                        return true;
                    }
                    if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) {
                        return false;
                    }
                    // If the parent is not sourceFile or module block it is local variable
                    for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
                        // Reached source file or module block
                        if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) {
                            return false;
                        }
                    }
                    // parent is in function block
                    return true;
                });
            }
        })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {}));
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        /*
         * This function will compile source text from 'input' argument using specified compiler options.
         * If not options are provided - it will use a set of default compiler options.
         * Extra compiler options that will unconditionally be used by this function are:
         * - isolatedModules = true
         * - allowNonTsExtensions = true
         * - noLib = true
         * - noResolve = true
         */
        function transpileModule(input, transpileOptions) {
            var diagnostics = [];
            var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions();
            options.isolatedModules = true;
            // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths.
            options.suppressOutputPathCheck = true;
            // Filename can be non-ts file.
            options.allowNonTsExtensions = true;
            // We are not returning a sourceFile for lib file when asked by the program,
            // so pass --noLib to avoid reporting a file not found error.
            options.noLib = true;
            // Clear out other settings that would not be used in transpiling this module
            options.lib = undefined;
            options.types = undefined;
            options.noEmit = undefined;
            options.noEmitOnError = undefined;
            options.paths = undefined;
            options.rootDirs = undefined;
            options.declaration = undefined;
            options.composite = undefined;
            options.declarationDir = undefined;
            options.out = undefined;
            options.outFile = undefined;
            // We are not doing a full typecheck, we are not resolving the whole context,
            // so pass --noResolve to avoid reporting missing file errors.
            options.noResolve = true;
            // if jsx is specified then treat file as .tsx
            var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts");
            var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217
            if (transpileOptions.moduleName) {
                sourceFile.moduleName = transpileOptions.moduleName;
            }
            if (transpileOptions.renamedDependencies) {
                sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies);
            }
            var newLine = ts.getNewLineCharacter(options);
            // Output
            var outputText;
            var sourceMapText;
            // Create a compilerHost object to allow the compiler to read and write files
            var compilerHost = {
                getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; },
                writeFile: function (name, text) {
                    if (ts.fileExtensionIs(name, ".map")) {
                        ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name);
                        sourceMapText = text;
                    }
                    else {
                        ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name);
                        outputText = text;
                    }
                },
                getDefaultLibFileName: function () { return "lib.d.ts"; },
                useCaseSensitiveFileNames: function () { return false; },
                getCanonicalFileName: function (fileName) { return fileName; },
                getCurrentDirectory: function () { return ""; },
                getNewLine: function () { return newLine; },
                fileExists: function (fileName) { return fileName === inputFileName; },
                readFile: function () { return ""; },
                directoryExists: function () { return true; },
                getDirectories: function () { return []; }
            };
            var program = ts.createProgram([inputFileName], options, compilerHost);
            if (transpileOptions.reportDiagnostics) {
                ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
                ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
            }
            // Emit
            program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers);
            if (outputText === undefined)
                return ts.Debug.fail("Output generation failed");
            return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText };
        }
        ts.transpileModule = transpileModule;
        /*
         * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result.
         */
        function transpile(input, compilerOptions, fileName, diagnostics, moduleName) {
            var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName });
            // addRange correctly handles cases when wither 'from' or 'to' argument is missing
            ts.addRange(diagnostics, output.diagnostics);
            return output.outputText;
        }
        ts.transpile = transpile;
        var commandLineOptionsStringToEnum;
        /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */
        /*@internal*/
        function fixupCompilerOptions(options, diagnostics) {
            // Lazily create this value to fix module loading errors.
            commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) {
                return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
            });
            options = ts.cloneCompilerOptions(options);
            var _loop_15 = function (opt) {
                if (!ts.hasProperty(options, opt.name)) {
                    return "continue";
                }
                var value = options[opt.name];
                // Value should be a key of opt.type
                if (ts.isString(value)) {
                    // If value is not a string, this will fail
                    options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics);
                }
                else {
                    if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) {
                        // Supplied value isn't a valid enum value.
                        diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt));
                    }
                }
            };
            for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
                var opt = commandLineOptionsStringToEnum_1[_i];
                _loop_15(opt);
            }
            return options;
        }
        ts.fixupCompilerOptions = fixupCompilerOptions;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var formatting;
        (function (formatting) {
            var FormattingRequestKind;
            (function (FormattingRequestKind) {
                FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument";
                FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection";
                FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter";
                FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon";
                FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace";
                FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace";
            })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {}));
            var FormattingContext = /** @class */ (function () {
                function FormattingContext(sourceFile, formattingRequestKind, options) {
                    this.sourceFile = sourceFile;
                    this.formattingRequestKind = formattingRequestKind;
                    this.options = options;
                }
                FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
                    ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null");
                    ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null");
                    ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null");
                    ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null");
                    ts.Debug.assert(commonParent !== undefined, "commonParent is null");
                    this.currentTokenSpan = currentRange;
                    this.currentTokenParent = currentTokenParent;
                    this.nextTokenSpan = nextRange;
                    this.nextTokenParent = nextTokenParent;
                    this.contextNode = commonParent;
                    // drop cached results
                    this.contextNodeAllOnSameLine = undefined;
                    this.nextNodeAllOnSameLine = undefined;
                    this.tokensAreOnSameLine = undefined;
                    this.contextNodeBlockIsOnOneLine = undefined;
                    this.nextNodeBlockIsOnOneLine = undefined;
                };
                FormattingContext.prototype.ContextNodeAllOnSameLine = function () {
                    if (this.contextNodeAllOnSameLine === undefined) {
                        this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode);
                    }
                    return this.contextNodeAllOnSameLine;
                };
                FormattingContext.prototype.NextNodeAllOnSameLine = function () {
                    if (this.nextNodeAllOnSameLine === undefined) {
                        this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent);
                    }
                    return this.nextNodeAllOnSameLine;
                };
                FormattingContext.prototype.TokensAreOnSameLine = function () {
                    if (this.tokensAreOnSameLine === undefined) {
                        var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
                        var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
                        this.tokensAreOnSameLine = (startLine === endLine);
                    }
                    return this.tokensAreOnSameLine;
                };
                FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () {
                    if (this.contextNodeBlockIsOnOneLine === undefined) {
                        this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode);
                    }
                    return this.contextNodeBlockIsOnOneLine;
                };
                FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () {
                    if (this.nextNodeBlockIsOnOneLine === undefined) {
                        this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent);
                    }
                    return this.nextNodeBlockIsOnOneLine;
                };
                FormattingContext.prototype.NodeIsOnOneLine = function (node) {
                    var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
                    var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
                    return startLine === endLine;
                };
                FormattingContext.prototype.BlockIsOnOneLine = function (node) {
                    var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile);
                    var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile);
                    if (openBrace && closeBrace) {
                        var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
                        var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
                        return startLine === endLine;
                    }
                    return false;
                };
                return FormattingContext;
            }());
            formatting.FormattingContext = FormattingContext;
        })(formatting = ts.formatting || (ts.formatting = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var formatting;
        (function (formatting) {
            var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
            var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
            var ScanAction;
            (function (ScanAction) {
                ScanAction[ScanAction["Scan"] = 0] = "Scan";
                ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken";
                ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
                ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
                ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
                ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
            })(ScanAction || (ScanAction = {}));
            function getFormattingScanner(text, languageVariant, startPos, endPos, cb) {
                var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
                scanner.setText(text);
                scanner.setTextPos(startPos);
                var wasNewLine = true;
                var leadingTrivia;
                var trailingTrivia;
                var savedPos;
                var lastScanAction;
                var lastTokenInfo;
                var res = cb({
                    advance: advance,
                    readTokenInfo: readTokenInfo,
                    isOnToken: isOnToken,
                    getCurrentLeadingTrivia: function () { return leadingTrivia; },
                    lastTrailingTriviaWasNewLine: function () { return wasNewLine; },
                    skipToEndOf: skipToEndOf,
                });
                lastTokenInfo = undefined;
                scanner.setText(undefined);
                return res;
                function advance() {
                    lastTokenInfo = undefined;
                    var isStarted = scanner.getStartPos() !== startPos;
                    if (isStarted) {
                        wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */;
                    }
                    else {
                        scanner.scan();
                    }
                    leadingTrivia = undefined;
                    trailingTrivia = undefined;
                    var pos = scanner.getStartPos();
                    // Read leading trivia and token
                    while (pos < endPos) {
                        var t = scanner.getToken();
                        if (!ts.isTrivia(t)) {
                            break;
                        }
                        // consume leading trivia
                        scanner.scan();
                        var item = {
                            pos: pos,
                            end: scanner.getStartPos(),
                            kind: t
                        };
                        pos = scanner.getStartPos();
                        leadingTrivia = ts.append(leadingTrivia, item);
                    }
                    savedPos = scanner.getStartPos();
                }
                function shouldRescanGreaterThanToken(node) {
                    switch (node.kind) {
                        case 31 /* GreaterThanEqualsToken */:
                        case 66 /* GreaterThanGreaterThanEqualsToken */:
                        case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                        case 47 /* GreaterThanGreaterThanGreaterThanToken */:
                        case 46 /* GreaterThanGreaterThanToken */:
                            return true;
                    }
                    return false;
                }
                function shouldRescanJsxIdentifier(node) {
                    if (node.parent) {
                        switch (node.parent.kind) {
                            case 265 /* JsxAttribute */:
                            case 260 /* JsxOpeningElement */:
                            case 261 /* JsxClosingElement */:
                            case 259 /* JsxSelfClosingElement */:
                                // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier.
                                return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */;
                        }
                    }
                    return false;
                }
                function shouldRescanJsxText(node) {
                    return node.kind === 10 /* JsxText */;
                }
                function shouldRescanSlashToken(container) {
                    return container.kind === 12 /* RegularExpressionLiteral */;
                }
                function shouldRescanTemplateToken(container) {
                    return container.kind === 15 /* TemplateMiddle */ ||
                        container.kind === 16 /* TemplateTail */;
                }
                function startsWithSlashToken(t) {
                    return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */;
                }
                function readTokenInfo(n) {
                    ts.Debug.assert(isOnToken());
                    // normally scanner returns the smallest available token
                    // check the kind of context node to determine if scanner should have more greedy behavior and consume more text.
                    var expectedScanAction = shouldRescanGreaterThanToken(n)
                        ? 1 /* RescanGreaterThanToken */
                        : shouldRescanSlashToken(n)
                            ? 2 /* RescanSlashToken */
                            : shouldRescanTemplateToken(n)
                                ? 3 /* RescanTemplateToken */
                                : shouldRescanJsxIdentifier(n)
                                    ? 4 /* RescanJsxIdentifier */
                                    : shouldRescanJsxText(n)
                                        ? 5 /* RescanJsxText */
                                        : 0 /* Scan */;
                    if (lastTokenInfo && expectedScanAction === lastScanAction) {
                        // readTokenInfo was called before with the same expected scan action.
                        // No need to re-scan text, return existing 'lastTokenInfo'
                        // it is ok to call fixTokenKind here since it does not affect
                        // what portion of text is consumed. In contrast rescanning can change it,
                        // i.e. for '>=' when originally scanner eats just one character
                        // and rescanning forces it to consume more.
                        return fixTokenKind(lastTokenInfo, n);
                    }
                    if (scanner.getStartPos() !== savedPos) {
                        ts.Debug.assert(lastTokenInfo !== undefined);
                        // readTokenInfo was called before but scan action differs - rescan text
                        scanner.setTextPos(savedPos);
                        scanner.scan();
                    }
                    var currentToken = getNextToken(n, expectedScanAction);
                    var token = {
                        pos: scanner.getStartPos(),
                        end: scanner.getTextPos(),
                        kind: currentToken
                    };
                    // consume trailing trivia
                    if (trailingTrivia) {
                        trailingTrivia = undefined;
                    }
                    while (scanner.getStartPos() < endPos) {
                        currentToken = scanner.scan();
                        if (!ts.isTrivia(currentToken)) {
                            break;
                        }
                        var trivia = {
                            pos: scanner.getStartPos(),
                            end: scanner.getTextPos(),
                            kind: currentToken
                        };
                        if (!trailingTrivia) {
                            trailingTrivia = [];
                        }
                        trailingTrivia.push(trivia);
                        if (currentToken === 4 /* NewLineTrivia */) {
                            // move past new line
                            scanner.scan();
                            break;
                        }
                    }
                    lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token };
                    return fixTokenKind(lastTokenInfo, n);
                }
                function getNextToken(n, expectedScanAction) {
                    var token = scanner.getToken();
                    lastScanAction = 0 /* Scan */;
                    switch (expectedScanAction) {
                        case 1 /* RescanGreaterThanToken */:
                            if (token === 29 /* GreaterThanToken */) {
                                lastScanAction = 1 /* RescanGreaterThanToken */;
                                var newToken = scanner.reScanGreaterToken();
                                ts.Debug.assert(n.kind === newToken);
                                return newToken;
                            }
                            break;
                        case 2 /* RescanSlashToken */:
                            if (startsWithSlashToken(token)) {
                                lastScanAction = 2 /* RescanSlashToken */;
                                var newToken = scanner.reScanSlashToken();
                                ts.Debug.assert(n.kind === newToken);
                                return newToken;
                            }
                            break;
                        case 3 /* RescanTemplateToken */:
                            if (token === 18 /* CloseBraceToken */) {
                                lastScanAction = 3 /* RescanTemplateToken */;
                                return scanner.reScanTemplateToken();
                            }
                            break;
                        case 4 /* RescanJsxIdentifier */:
                            lastScanAction = 4 /* RescanJsxIdentifier */;
                            return scanner.scanJsxIdentifier();
                        case 5 /* RescanJsxText */:
                            lastScanAction = 5 /* RescanJsxText */;
                            return scanner.reScanJsxToken();
                        case 0 /* Scan */:
                            break;
                        default:
                            ts.Debug.assertNever(expectedScanAction);
                    }
                    return token;
                }
                function isOnToken() {
                    var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
                    var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos();
                    return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current);
                }
                // when containing node in the tree is token
                // but its kind differs from the kind that was returned by the scanner,
                // then kind needs to be fixed. This might happen in cases
                // when parser interprets token differently, i.e keyword treated as identifier
                function fixTokenKind(tokenInfo, container) {
                    if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) {
                        tokenInfo.token.kind = container.kind;
                    }
                    return tokenInfo;
                }
                function skipToEndOf(node) {
                    scanner.setTextPos(node.end);
                    savedPos = scanner.getStartPos();
                    lastScanAction = undefined;
                    lastTokenInfo = undefined;
                    wasNewLine = false;
                    leadingTrivia = undefined;
                    trailingTrivia = undefined;
                }
            }
            formatting.getFormattingScanner = getFormattingScanner;
        })(formatting = ts.formatting || (ts.formatting = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var formatting;
        (function (formatting) {
            formatting.anyContext = ts.emptyArray;
            var RuleAction;
            (function (RuleAction) {
                RuleAction[RuleAction["Ignore"] = 1] = "Ignore";
                RuleAction[RuleAction["Space"] = 2] = "Space";
                RuleAction[RuleAction["NewLine"] = 4] = "NewLine";
                RuleAction[RuleAction["Delete"] = 8] = "Delete";
            })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {}));
            var RuleFlags;
            (function (RuleFlags) {
                RuleFlags[RuleFlags["None"] = 0] = "None";
                RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines";
            })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {}));
        })(formatting = ts.formatting || (ts.formatting = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var formatting;
        (function (formatting) {
            function getAllRules() {
                var allTokens = [];
                for (var token = 0 /* FirstToken */; token <= 145 /* LastToken */; token++) {
                    allTokens.push(token);
                }
                function anyTokenExcept() {
                    var tokens = [];
                    for (var _i = 0; _i < arguments.length; _i++) {
                        tokens[_i] = arguments[_i];
                    }
                    return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false };
                }
                var anyToken = { tokens: allTokens, isSpecific: false };
                var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */]));
                var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 145 /* LastKeyword */);
                var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */);
                var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 145 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */];
                var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */];
                var unaryPrefixExpressions = [
                    8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */,
                    17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */
                ];
                var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */];
                var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */];
                var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */];
                var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */];
                var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */];
                var typeNames = [71 /* Identifier */].concat(ts.typeKeywords);
                // Place a space before open brace in a function declaration
                // TypeScript: Function can have return types, which can be made of tons of different token kinds
                var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments;
                // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc)
                var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]);
                // Place a space before open brace in a control flow construct
                var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]);
                // These rules are higher in priority than user-configurable
                var highPriorityCommonRules = [
                    // Leave comments alone
                    rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */),
                    rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */),
                    rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */),
                    rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */),
                    rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */),
                    // insert space after '?' only when it is used in conditional operator
                    rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */),
                    // in other cases there should be no space between '?' and next token
                    rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */),
                    // Special handling of unary operators.
                    // Prefix operators generally shouldn't have a space between
                    // them and their target unary expression.
                    rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */),
                    rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // More unary operator special-casing.
                    // DevDiv 181814: Be careful when removing leading whitespace
                    // around unary operators.  Examples:
                    //      1 - -2  --X--> 1--2
                    //      a + ++b --X--> a+++b
                    rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // For functions and control block place } on a new line [multi-line rule]
                    rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */),
                    // Space/new line after }.
                    rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */),
                    // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
                    // Also should not apply to })
                    rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */),
                    // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];'
                    rule("SpaceAfterConditionalClosingParen", 20 /* CloseParenToken */, 21 /* OpenBracketToken */, [isControlDeclContext], 2 /* Space */),
                    rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */),
                    rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */),
                    rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */),
                    // Insert new line after { and before } in multi-line contexts.
                    rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */),
                    // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token.
                    // Though, we do extra check on the context to make sure we are dealing with get/set node. Example:
                    //      get x() {}
                    //      set x(val) {}
                    rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 136 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */),
                    rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */),
                    rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */),
                    rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */),
                    rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */),
                    // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
                    rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */),
                    // Async-await
                    rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    // Template string
                    rule("NoSpaceBetweenTagAndTemplateString", [71 /* Identifier */, 20 /* CloseParenToken */], [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // JSX opening elements
                    rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // TypeScript-specific rules
                    // Use of module as a function call. e.g.: import m2 = module("m2");
                    rule("NoSpaceAfterModuleImport", [129 /* ModuleKeyword */, 133 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // Add a space around certain TypeScript keywords
                    rule("SpaceAfterCertainTypeScriptKeywords", [
                        117 /* AbstractKeyword */,
                        75 /* ClassKeyword */,
                        124 /* DeclareKeyword */,
                        79 /* DefaultKeyword */,
                        83 /* EnumKeyword */,
                        84 /* ExportKeyword */,
                        85 /* ExtendsKeyword */,
                        125 /* GetKeyword */,
                        108 /* ImplementsKeyword */,
                        91 /* ImportKeyword */,
                        109 /* InterfaceKeyword */,
                        129 /* ModuleKeyword */,
                        130 /* NamespaceKeyword */,
                        112 /* PrivateKeyword */,
                        114 /* PublicKeyword */,
                        113 /* ProtectedKeyword */,
                        132 /* ReadonlyKeyword */,
                        136 /* SetKeyword */,
                        115 /* StaticKeyword */,
                        139 /* TypeKeyword */,
                        143 /* FromKeyword */,
                        128 /* KeyOfKeyword */,
                        126 /* InferKeyword */,
                    ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 143 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */),
                    // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
                    rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */),
                    // Lambda expressions
                    rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    // Optional parameters and let args
                    rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */),
                    // Remove spaces in empty interface literals. e.g.: x: {}
                    rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */),
                    // generics and type assertions
                    rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */),
                    rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */),
                    rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */),
                    rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */),
                    rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */),
                    // decorators
                    rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // Insert space after @ in decorator
                    rule("SpaceAfterDecorator", anyToken, [
                        117 /* AbstractKeyword */,
                        71 /* Identifier */,
                        84 /* ExportKeyword */,
                        79 /* DefaultKeyword */,
                        75 /* ClassKeyword */,
                        115 /* StaticKeyword */,
                        114 /* PublicKeyword */,
                        112 /* PrivateKeyword */,
                        113 /* ProtectedKeyword */,
                        125 /* GetKeyword */,
                        136 /* SetKeyword */,
                        21 /* OpenBracketToken */,
                        39 /* AsteriskToken */,
                    ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */),
                    rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */),
                    rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */),
                ];
                // These rules are applied after high priority
                var userConfigurableRules = [
                    // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
                    rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */),
                    rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */),
                    // Insert space after function keyword for anonymous functions
                    rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */),
                    rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */),
                    // Insert space after keywords in control flow statements
                    rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */),
                    rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */),
                    // Insert space after opening and before closing nonempty parenthesis
                    rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // Insert space after opening and before closing nonempty brackets
                    rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
                    rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */),
                    rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */),
                    rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */),
                    rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // Insert space after opening and before closing template string braces
                    rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */),
                    rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // No space after { and before } in JSX expression
                    rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */),
                    rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */),
                    rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */),
                    rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */),
                    // Insert space after semicolon in for statement
                    rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */),
                    rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */),
                    // Insert space before and after binary operators
                    rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */),
                    rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */),
                    rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */),
                    rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */),
                    rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */),
                    // Open Brace braces after control block
                    rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */),
                    // Open Brace braces after function
                    // TypeScript: Function can have return types, which can be made of tons of different token kinds
                    rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */),
                    // Open Brace braces after TypeScript module/class/interface
                    rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */),
                    rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */),
                    rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */),
                    rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */),
                    rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */),
                ];
                // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list.
                var lowPriorityCommonRules = [
                    // Space after keyword but not before ; or : or ?
                    rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */),
                    rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */),
                    rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */),
                    rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    // No space before and after indexer `x[]`
                    rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
                    rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */),
                    rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    // Remove extra space between for and await
                    rule("SpaceBetweenForAndAwaitKeyword", 88 /* ForKeyword */, 121 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */),
                    // Add a space between statements. All keywords except (do,else,case) has open/close parens after them.
                    // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any]
                    rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */),
                    // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
                    rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */),
                ];
                return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules);
            }
            formatting.getAllRules = getAllRules;
            function rule(debugName, left, right, context, action, flags) {
                if (flags === void 0) {
                    flags = 0 /* None */;
                }
                return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } };
            }
            function tokenRangeFrom(tokens) {
                return { tokens: tokens, isSpecific: true };
            }
            function toTokenRange(arg) {
                return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg;
            }
            function tokenRangeFromRange(from, to, except) {
                if (except === void 0) {
                    except = [];
                }
                var tokens = [];
                for (var token = from; token <= to; token++) {
                    if (!ts.contains(except, token)) {
                        tokens.push(token);
                    }
                }
                return tokenRangeFrom(tokens);
            }
            ///
            /// Contexts
            ///
            function isOptionEnabled(optionName) {
                return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; };
            }
            function isOptionDisabled(optionName) {
                return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; };
            }
            function isOptionDisabledOrUndefined(optionName) {
                return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; };
            }
            function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) {
                return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); };
            }
            function isOptionEnabledOrUndefined(optionName) {
                return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; };
            }
            function isForContext(context) {
                return context.contextNode.kind === 223 /* ForStatement */;
            }
            function isNotForContext(context) {
                return !isForContext(context);
            }
            function isBinaryOpContext(context) {
                switch (context.contextNode.kind) {
                    case 202 /* BinaryExpression */:
                    case 203 /* ConditionalExpression */:
                    case 173 /* ConditionalType */:
                    case 210 /* AsExpression */:
                    case 255 /* ExportSpecifier */:
                    case 251 /* ImportSpecifier */:
                    case 161 /* TypePredicate */:
                    case 171 /* UnionType */:
                    case 172 /* IntersectionType */:
                        return true;
                    // equals in binding elements: function foo([[x, y] = [1, 2]])
                    case 184 /* BindingElement */:
                    // equals in type X = ...
                    case 240 /* TypeAliasDeclaration */:
                    // equal in import a = module('a');
                    case 246 /* ImportEqualsDeclaration */:
                    // equal in let a = 0;
                    case 235 /* VariableDeclaration */:
                    // equal in p = 0;
                    case 149 /* Parameter */:
                    case 276 /* EnumMember */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                        return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */;
                    // "in" keyword in for (let x in []) { }
                    case 224 /* ForInStatement */:
                    // "in" keyword in [P in keyof T]: T[P]
                    case 148 /* TypeParameter */:
                        return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */;
                    // Technically, "of" is not a binary operator, but format it the same way as "in"
                    case 225 /* ForOfStatement */:
                        return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */;
                }
                return false;
            }
            function isNotBinaryOpContext(context) {
                return !isBinaryOpContext(context);
            }
            function isNotTypeAnnotationContext(context) {
                return !isTypeAnnotationContext(context);
            }
            function isTypeAnnotationContext(context) {
                var contextKind = context.contextNode.kind;
                return contextKind === 152 /* PropertyDeclaration */ ||
                    contextKind === 151 /* PropertySignature */ ||
                    contextKind === 149 /* Parameter */ ||
                    contextKind === 235 /* VariableDeclaration */ ||
                    ts.isFunctionLikeKind(contextKind);
            }
            function isConditionalOperatorContext(context) {
                return context.contextNode.kind === 203 /* ConditionalExpression */ ||
                    context.contextNode.kind === 173 /* ConditionalType */;
            }
            function isSameLineTokenOrBeforeBlockContext(context) {
                return context.TokensAreOnSameLine() || isBeforeBlockContext(context);
            }
            function isBraceWrappedContext(context) {
                return context.contextNode.kind === 182 /* ObjectBindingPattern */ ||
                    context.contextNode.kind === 179 /* MappedType */ ||
                    isSingleLineBlockContext(context);
            }
            // This check is done before an open brace in a control construct, a function, or a typescript block declaration
            function isBeforeMultilineBlockContext(context) {
                return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
            }
            function isMultilineBlockContext(context) {
                return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
            }
            function isSingleLineBlockContext(context) {
                return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
            }
            function isBlockContext(context) {
                return nodeIsBlockContext(context.contextNode);
            }
            function isBeforeBlockContext(context) {
                return nodeIsBlockContext(context.nextTokenParent);
            }
            // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children
            function nodeIsBlockContext(node) {
                if (nodeIsTypeScriptDeclWithBlockContext(node)) {
                    // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc).
                    return true;
                }
                switch (node.kind) {
                    case 216 /* Block */:
                    case 244 /* CaseBlock */:
                    case 186 /* ObjectLiteralExpression */:
                    case 243 /* ModuleBlock */:
                        return true;
                }
                return false;
            }
            function isFunctionDeclContext(context) {
                switch (context.contextNode.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    // case SyntaxKind.MemberFunctionDeclaration:
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    // case SyntaxKind.MethodSignature:
                    case 158 /* CallSignature */:
                    case 194 /* FunctionExpression */:
                    case 155 /* Constructor */:
                    case 195 /* ArrowFunction */:
                    // case SyntaxKind.ConstructorDeclaration:
                    // case SyntaxKind.SimpleArrowFunctionExpression:
                    // case SyntaxKind.ParenthesizedArrowFunctionExpression:
                    case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
                        return true;
                }
                return false;
            }
            function isNotFunctionDeclContext(context) {
                return !isFunctionDeclContext(context);
            }
            function isFunctionDeclarationOrFunctionExpressionContext(context) {
                return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */;
            }
            function isTypeScriptDeclWithBlockContext(context) {
                return nodeIsTypeScriptDeclWithBlockContext(context.contextNode);
            }
            function nodeIsTypeScriptDeclWithBlockContext(node) {
                switch (node.kind) {
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                    case 239 /* InterfaceDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 166 /* TypeLiteral */:
                    case 242 /* ModuleDeclaration */:
                    case 253 /* ExportDeclaration */:
                    case 254 /* NamedExports */:
                    case 247 /* ImportDeclaration */:
                    case 250 /* NamedImports */:
                        return true;
                }
                return false;
            }
            function isAfterCodeBlockContext(context) {
                switch (context.currentTokenParent.kind) {
                    case 238 /* ClassDeclaration */:
                    case 242 /* ModuleDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 272 /* CatchClause */:
                    case 243 /* ModuleBlock */:
                    case 230 /* SwitchStatement */:
                        return true;
                    case 216 /* Block */: {
                        var blockParent = context.currentTokenParent.parent;
                        // In a codefix scenario, we can't rely on parents being set. So just always return true.
                        if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) {
                            return true;
                        }
                    }
                }
                return false;
            }
            function isControlDeclContext(context) {
                switch (context.contextNode.kind) {
                    case 220 /* IfStatement */:
                    case 230 /* SwitchStatement */:
                    case 223 /* ForStatement */:
                    case 224 /* ForInStatement */:
                    case 225 /* ForOfStatement */:
                    case 222 /* WhileStatement */:
                    case 233 /* TryStatement */:
                    case 221 /* DoStatement */:
                    case 229 /* WithStatement */:
                    // TODO
                    // case SyntaxKind.ElseClause:
                    case 272 /* CatchClause */:
                        return true;
                    default:
                        return false;
                }
            }
            function isObjectContext(context) {
                return context.contextNode.kind === 186 /* ObjectLiteralExpression */;
            }
            function isFunctionCallContext(context) {
                return context.contextNode.kind === 189 /* CallExpression */;
            }
            function isNewContext(context) {
                return context.contextNode.kind === 190 /* NewExpression */;
            }
            function isFunctionCallOrNewContext(context) {
                return isFunctionCallContext(context) || isNewContext(context);
            }
            function isPreviousTokenNotComma(context) {
                return context.currentTokenSpan.kind !== 26 /* CommaToken */;
            }
            function isNextTokenNotCloseBracket(context) {
                return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */;
            }
            function isArrowFunctionContext(context) {
                return context.contextNode.kind === 195 /* ArrowFunction */;
            }
            function isImportTypeContext(context) {
                return context.contextNode.kind === 181 /* ImportType */;
            }
            function isNonJsxSameLineTokenContext(context) {
                return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
            }
            function isNonJsxElementOrFragmentContext(context) {
                return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */;
            }
            function isJsxExpressionContext(context) {
                return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */;
            }
            function isNextTokenParentJsxAttribute(context) {
                return context.nextTokenParent.kind === 265 /* JsxAttribute */;
            }
            function isJsxAttributeContext(context) {
                return context.contextNode.kind === 265 /* JsxAttribute */;
            }
            function isJsxSelfClosingElementContext(context) {
                return context.contextNode.kind === 259 /* JsxSelfClosingElement */;
            }
            function isNotBeforeBlockInFunctionDeclarationContext(context) {
                return !isFunctionDeclContext(context) && !isBeforeBlockContext(context);
            }
            function isEndOfDecoratorContextOnSameLine(context) {
                return context.TokensAreOnSameLine() &&
                    !!context.contextNode.decorators &&
                    nodeIsInDecoratorContext(context.currentTokenParent) &&
                    !nodeIsInDecoratorContext(context.nextTokenParent);
            }
            function nodeIsInDecoratorContext(node) {
                while (ts.isExpressionNode(node)) {
                    node = node.parent;
                }
                return node.kind === 150 /* Decorator */;
            }
            function isStartOfVariableDeclarationList(context) {
                return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ &&
                    context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
            }
            function isNotFormatOnEnter(context) {
                return context.formattingRequestKind !== 2 /* FormatOnEnter */;
            }
            function isModuleDeclContext(context) {
                return context.contextNode.kind === 242 /* ModuleDeclaration */;
            }
            function isObjectTypeContext(context) {
                return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
            }
            function isConstructorSignatureContext(context) {
                return context.contextNode.kind === 159 /* ConstructSignature */;
            }
            function isTypeArgumentOrParameterOrAssertion(token, parent) {
                if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) {
                    return false;
                }
                switch (parent.kind) {
                    case 162 /* TypeReference */:
                    case 192 /* TypeAssertionExpression */:
                    case 240 /* TypeAliasDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 207 /* ClassExpression */:
                    case 239 /* InterfaceDeclaration */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 158 /* CallSignature */:
                    case 159 /* ConstructSignature */:
                    case 189 /* CallExpression */:
                    case 190 /* NewExpression */:
                    case 209 /* ExpressionWithTypeArguments */:
                        return true;
                    default:
                        return false;
                }
            }
            function isTypeArgumentOrParameterOrAssertionContext(context) {
                return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) ||
                    isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
            }
            function isTypeAssertionContext(context) {
                return context.contextNode.kind === 192 /* TypeAssertionExpression */;
            }
            function isVoidOpContext(context) {
                return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */;
            }
            function isYieldOrYieldStarWithOperand(context) {
                return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined;
            }
            function isNonNullAssertionContext(context) {
                return context.contextNode.kind === 211 /* NonNullExpression */;
            }
        })(formatting = ts.formatting || (ts.formatting = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var formatting;
        (function (formatting) {
            function getFormatContext(options) {
                return { options: options, getRule: getRulesMap() };
            }
            formatting.getFormatContext = getFormatContext;
            var rulesMapCache;
            function getRulesMap() {
                if (rulesMapCache === undefined) {
                    rulesMapCache = createRulesMap(formatting.getAllRules());
                }
                return rulesMapCache;
            }
            function createRulesMap(rules) {
                var map = buildMap(rules);
                return function (context) {
                    var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)];
                    return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); });
                };
            }
            function buildMap(rules) {
                // Map from bucket index to array of rules
                var map = new Array(mapRowLength * mapRowLength);
                // This array is used only during construction of the rulesbucket in the map
                var rulesBucketConstructionStateList = new Array(map.length);
                for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
                    var rule = rules_1[_i];
                    var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
                    for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
                        var left = _b[_a];
                        for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
                            var right = _d[_c];
                            var index = getRuleBucketIndex(left, right);
                            var rulesBucket = map[index];
                            if (rulesBucket === undefined) {
                                rulesBucket = map[index] = [];
                            }
                            addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
                        }
                    }
                }
                return map;
            }
            function getRuleBucketIndex(row, column) {
                ts.Debug.assert(row <= 145 /* LastKeyword */ && column <= 145 /* LastKeyword */, "Must compute formatting context from tokens");
                return (row * mapRowLength) + column;
            }
            var maskBitSize = 5;
            var mask = 31; // MaskBitSize bits
            var mapRowLength = 145 /* LastToken */ + 1;
            var RulesPosition;
            (function (RulesPosition) {
                RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific";
                RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny";
                RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific";
                RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny";
                RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific";
                RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny";
            })(RulesPosition || (RulesPosition = {}));
            // The Rules list contains all the inserted rules into a rulebucket in the following order:
            //    1- Ignore rules with specific token combination
            //    2- Ignore rules with any token combination
            //    3- Context rules with specific token combination
            //    4- Context rules with any token combination
            //    5- Non-context rules with specific token combination
            //    6- Non-context rules with any token combination
            //
            // The member rulesInsertionIndexBitmap is used to describe the number of rules
            // in each sub-bucket (above) hence can be used to know the index of where to insert
            // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits.
            //
            // Example:
            // In order to insert a rule to the end of sub-bucket (3), we get the index by adding
            // the values in the bitmap segments 3rd, 2nd, and 1st.
            function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) {
                var position = rule.action === 1 /* Ignore */
                    ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny
                    : rule.context !== formatting.anyContext
                        ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny
                        : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny;
                var state = constructionState[rulesBucketIndex] || 0;
                rules.splice(getInsertionIndex(state, position), 0, rule);
                constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position);
            }
            function getInsertionIndex(indexBitmap, maskPosition) {
                var index = 0;
                for (var pos = 0; pos <= maskPosition; pos += maskBitSize) {
                    index += indexBitmap & mask;
                    indexBitmap >>= maskBitSize;
                }
                return index;
            }
            function increaseInsertionIndex(indexBitmap, maskPosition) {
                var value = ((indexBitmap >> maskPosition) & mask) + 1;
                ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
                return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition);
            }
        })(formatting = ts.formatting || (ts.formatting = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var formatting;
        (function (formatting) {
            var Constants;
            (function (Constants) {
                Constants[Constants["Unknown"] = -1] = "Unknown";
            })(Constants || (Constants = {}));
            function formatOnEnter(position, sourceFile, formatContext) {
                var line = sourceFile.getLineAndCharacterOfPosition(position).line;
                if (line === 0) {
                    return [];
                }
                // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
                // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
                // trailing whitespaces. So the end of the formatting span should be the later one between:
                //  1. the end of the previous line
                //  2. the last non-whitespace character in the current line
                var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile);
                while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
                    endOfFormatSpan--;
                }
                // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to
                // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the
                // previous character before the end of format span is line break character as well.
                if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
                    endOfFormatSpan--;
                }
                var span = {
                    // get start position for the previous line
                    pos: ts.getStartPositionOfLine(line - 1, sourceFile),
                    // end value is exclusive so add 1 to the result
                    end: endOfFormatSpan + 1
                };
                return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */);
            }
            formatting.formatOnEnter = formatOnEnter;
            function formatOnSemicolon(position, sourceFile, formatContext) {
                var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile);
                return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */);
            }
            formatting.formatOnSemicolon = formatOnSemicolon;
            function formatOnOpeningCurly(position, sourceFile, formatContext) {
                var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile);
                if (!openingCurly) {
                    return [];
                }
                var curlyBraceRange = openingCurly.parent;
                var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange);
                /**
                 * We limit the span to end at the opening curly to handle the case where
                 * the brace matched to that just typed will be incorrect after further edits.
                 * For example, we could type the opening curly for the following method
                 * body without brace-matching activated:
                 * ```
                 * class C {
                 *     foo()
                 * }
                 * ```
                 * and we wouldn't want to move the closing brace.
                 */
                var textRange = {
                    pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile),
                    end: position
                };
                return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */);
            }
            formatting.formatOnOpeningCurly = formatOnOpeningCurly;
            function formatOnClosingCurly(position, sourceFile, formatContext) {
                var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile);
                return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */);
            }
            formatting.formatOnClosingCurly = formatOnClosingCurly;
            function formatDocument(sourceFile, formatContext) {
                var span = {
                    pos: 0,
                    end: sourceFile.text.length
                };
                return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */);
            }
            formatting.formatDocument = formatDocument;
            function formatSelection(start, end, sourceFile, formatContext) {
                // format from the beginning of the line
                var span = {
                    pos: ts.getLineStartPositionForPosition(start, sourceFile),
                    end: end,
                };
                return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */);
            }
            formatting.formatSelection = formatSelection;
            /**
             * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment).
             * @param expectedTokenKind The kind of the last token constituting the desired parent node.
             */
            function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) {
                var precedingToken = ts.findPrecedingToken(end, sourceFile);
                return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ?
                    precedingToken :
                    undefined;
            }
            /**
             * Finds the highest node enclosing `node` at the same list level as `node`
             * and whose end does not exceed `node.end`.
             *
             * Consider typing the following
             * ```
             * let x = 1;
             * while (true) {
             * }
             * ```
             * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding
             * variable declaration.
             */
            function findOutermostNodeWithinListLevel(node) {
                var current = node;
                while (current &&
                    current.parent &&
                    current.parent.end === node.end &&
                    !isListElement(current.parent, current)) {
                    current = current.parent;
                }
                return current;
            }
            // Returns true if node is a element in some list in parent
            // i.e. parent is class declaration with the list of members and node is one of members.
            function isListElement(parent, node) {
                switch (parent.kind) {
                    case 238 /* ClassDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                        return ts.rangeContainsRange(parent.members, node);
                    case 242 /* ModuleDeclaration */:
                        var body = parent.body;
                        return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
                    case 277 /* SourceFile */:
                    case 216 /* Block */:
                    case 243 /* ModuleBlock */:
                        return ts.rangeContainsRange(parent.statements, node);
                    case 272 /* CatchClause */:
                        return ts.rangeContainsRange(parent.block.statements, node);
                }
                return false;
            }
            /** find node that fully contains given text range */
            function findEnclosingNode(range, sourceFile) {
                return find(sourceFile);
                function find(n) {
                    var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; });
                    if (candidate) {
                        var result = find(candidate);
                        if (result) {
                            return result;
                        }
                    }
                    return n;
                }
            }
            /** formatting is not applied to ranges that contain parse errors.
             * This function will return a predicate that for a given text range will tell
             * if there are any parse errors that overlap with the range.
             */
            function prepareRangeContainsErrorFunction(errors, originalRange) {
                if (!errors.length) {
                    return rangeHasNoErrors;
                }
                // pick only errors that fall in range
                var sorted = errors
                    .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217
                    .sort(function (e1, e2) { return e1.start - e2.start; });
                if (!sorted.length) {
                    return rangeHasNoErrors;
                }
                var index = 0;
                return function (r) {
                    // in current implementation sequence of arguments [r1, r2...] is monotonically increasing.
                    // 'index' tracks the index of the most recent error that was checked.
                    while (true) {
                        if (index >= sorted.length) {
                            // all errors in the range were already checked -> no error in specified range
                            return false;
                        }
                        var error = sorted[index];
                        if (r.end <= error.start) {
                            // specified range ends before the error refered by 'index' - no error in range
                            return false;
                        }
                        if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {
                            // specified range overlaps with error range
                            return true;
                        }
                        index++;
                    }
                };
                function rangeHasNoErrors() {
                    return false;
                }
            }
            /**
             * Start of the original range might fall inside the comment - scanner will not yield appropriate results
             * This function will look for token that is located before the start of target range
             * and return its end as start position for the scanner.
             */
            function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
                var start = enclosingNode.getStart(sourceFile);
                if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
                    return start;
                }
                var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile);
                if (!precedingToken) {
                    // no preceding token found - start from the beginning of enclosing node
                    return enclosingNode.pos;
                }
                // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal)
                // start from the beginning of enclosingNode to handle the entire 'originalRange'
                if (precedingToken.end >= originalRange.pos) {
                    return enclosingNode.pos;
                }
                return precedingToken.end;
            }
            /*
             * For cases like
             * if (a ||
             *     b ||$
             *     c) {...}
             * If we hit Enter at $ we want line '    b ||' to be indented.
             * Formatting will be applied to the last two lines.
             * Node that fully encloses these lines is binary expression 'a ||...'.
             * Initial indentation for this node will be 0.
             * Binary expressions don't introduce new indentation scopes, however it is possible
             * that some parent node on the same line does - like if statement in this case.
             * Note that we are considering parents only from the same line with initial node -
             * if parent is on the different line - its delta was already contributed
             * to the initial indentation.
             */
            function getOwnOrInheritedDelta(n, options, sourceFile) {
                var previousLine = -1 /* Unknown */;
                var child;
                while (n) {
                    var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
                    if (previousLine !== -1 /* Unknown */ && line !== previousLine) {
                        break;
                    }
                    if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) {
                        return options.indentSize;
                    }
                    previousLine = line;
                    child = n;
                    n = n.parent;
                }
                return 0;
            }
            /* @internal */
            function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) {
                var range = { pos: 0, end: sourceFileLike.text.length };
                return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) {
                    return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors
                    sourceFileLike);
                });
            }
            formatting.formatNodeGivenIndentation = formatNodeGivenIndentation;
            function formatNodeLines(node, sourceFile, formatContext, requestKind) {
                if (!node) {
                    return [];
                }
                var span = {
                    pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile),
                    end: node.end
                };
                return formatSpan(span, sourceFile, formatContext, requestKind);
            }
            function formatSpan(originalRange, sourceFile, formatContext, requestKind) {
                // find the smallest node that fully wraps the range and compute the initial indentation for the node
                var enclosingNode = findEnclosingNode(originalRange, sourceFile);
                return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); });
            }
            function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) {
                var options = _a.options, getRule = _a.getRule;
                // formatting context is used by rules provider
                var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options);
                var previousRange;
                var previousParent;
                var previousRangeStartLine;
                var lastIndentedLine;
                var indentationOnLastIndentedLine;
                var edits = [];
                formattingScanner.advance();
                if (formattingScanner.isOnToken()) {
                    var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
                    var undecoratedStartLine = startLine;
                    if (enclosingNode.decorators) {
                        undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
                    }
                    processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
                }
                if (!formattingScanner.isOnToken()) {
                    var leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
                    if (leadingTrivia) {
                        processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217
                        trimTrailingWhitespacesForRemainingRange();
                    }
                }
                return edits;
                // local functions
                /** Tries to compute the indentation for a list element.
                 * If list element is not in range then
                 * function will pick its actual indentation
                 * so it can be pushed downstream as inherited indentation.
                 * If list element is in the range - its indentation will be equal
                 * to inherited indentation from its predecessors.
                 */
                function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
                    if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) ||
                        ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
                        if (inheritedIndentation !== -1 /* Unknown */) {
                            return inheritedIndentation;
                        }
                    }
                    else {
                        var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
                        var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile);
                        var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
                        if (startLine !== parentStartLine || startPos === column) {
                            // Use the base indent size if it is greater than
                            // the indentation of the inherited predecessor.
                            var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options);
                            return baseIndentSize > column ? baseIndentSize : column;
                        }
                    }
                    return -1 /* Unknown */;
                }
                function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
                    var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
                    if (effectiveParentStartLine === startLine) {
                        // if node is located on the same line with the parent
                        // - inherit indentation from the parent
                        // - push children if either parent of node itself has non-zero delta
                        return {
                            indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(),
                            delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta)
                        };
                    }
                    else if (inheritedIndentation === -1 /* Unknown */) {
                        if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) {
                            // the is used for chaining methods formatting
                            // - we need to get the indentation on last line and the delta of parent
                            return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
                        }
                        else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
                            return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
                        }
                        else {
                            return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta };
                        }
                    }
                    else {
                        return { indentation: inheritedIndentation, delta: delta };
                    }
                }
                function getFirstNonDecoratorTokenOfNode(node) {
                    if (node.modifiers && node.modifiers.length) {
                        return node.modifiers[0].kind;
                    }
                    switch (node.kind) {
                        case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */;
                        case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */;
                        case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */;
                        case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */;
                        case 156 /* GetAccessor */: return 125 /* GetKeyword */;
                        case 157 /* SetAccessor */: return 136 /* SetKeyword */;
                        case 154 /* MethodDeclaration */:
                            if (node.asteriskToken) {
                                return 39 /* AsteriskToken */;
                            }
                        // falls through
                        case 152 /* PropertyDeclaration */:
                        case 149 /* Parameter */:
                            var name = ts.getNameOfDeclaration(node);
                            if (name) {
                                return name.kind;
                            }
                    }
                }
                function getDynamicIndentation(node, nodeStartLine, indentation, delta) {
                    return {
                        getIndentationForComment: function (kind, tokenIndentation, container) {
                            switch (kind) {
                                // preceding comment to the token that closes the indentation scope inherits the indentation from the scope
                                // ..  {
                                //     // comment
                                // }
                                case 18 /* CloseBraceToken */:
                                case 22 /* CloseBracketToken */:
                                case 20 /* CloseParenToken */:
                                    return indentation + getDelta(container);
                            }
                            return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation;
                        },
                        getIndentationForToken: function (line, kind, container) {
                            return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation;
                        },
                        getIndentation: function () { return indentation; },
                        getDelta: getDelta,
                        recomputeIndentation: function (lineAdded) {
                            if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) {
                                indentation += lineAdded ? options.indentSize : -options.indentSize;
                                delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
                            }
                        }
                    };
                    function shouldAddDelta(line, kind, container) {
                        switch (kind) {
                            // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent
                            case 17 /* OpenBraceToken */:
                            case 18 /* CloseBraceToken */:
                            case 19 /* OpenParenToken */:
                            case 20 /* CloseParenToken */:
                            case 82 /* ElseKeyword */:
                            case 106 /* WhileKeyword */:
                            case 57 /* AtToken */:
                                return false;
                            case 41 /* SlashToken */:
                            case 29 /* GreaterThanToken */:
                                switch (container.kind) {
                                    case 260 /* JsxOpeningElement */:
                                    case 261 /* JsxClosingElement */:
                                    case 259 /* JsxSelfClosingElement */:
                                        return false;
                                }
                                break;
                            case 21 /* OpenBracketToken */:
                            case 22 /* CloseBracketToken */:
                                if (container.kind !== 179 /* MappedType */) {
                                    return false;
                                }
                                break;
                        }
                        // if token line equals to the line of containing node (this is a first token in the node) - use node indentation
                        return nodeStartLine !== line
                            // if this token is the first token following the list of decorators, we do not need to indent
                            && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node));
                    }
                    function getDelta(child) {
                        // Delta value should be zero when the node explicitly prevents indentation of the child node
                        return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0;
                    }
                }
                function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) {
                    if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
                        return;
                    }
                    var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta);
                    // a useful observations when tracking context node
                    //        /
                    //      [a]
                    //   /   |   \
                    //  [b] [c] [d]
                    // node 'a' is a context node for nodes 'b', 'c', 'd'
                    // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a'
                    // this rule can be applied recursively to child nodes of 'a'.
                    //
                    // context node is set to parent node value after processing every child node
                    // context node is set to parent of the token after processing every token
                    var childContextNode = contextNode;
                    // if there are any tokens that logically belong to node and interleave child nodes
                    // such tokens will be consumed in processChildNode for the child that follows them
                    ts.forEachChild(node, function (child) {
                        processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
                    }, function (nodes) {
                        processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
                    });
                    // proceed any tokens in the node that are located after child nodes
                    while (formattingScanner.isOnToken()) {
                        var tokenInfo = formattingScanner.readTokenInfo(node);
                        if (tokenInfo.token.end > node.end) {
                            break;
                        }
                        consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
                    }
                    function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) {
                        var childStartPos = child.getStart(sourceFile);
                        var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
                        var undecoratedChildStartLine = childStartLine;
                        if (child.decorators) {
                            undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
                        }
                        // if child is a list item - try to get its indentation, only if parent is within the original range.
                        var childIndentationAmount = -1 /* Unknown */;
                        if (isListItem && ts.rangeContainsRange(originalRange, parent)) {
                            childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation);
                            if (childIndentationAmount !== -1 /* Unknown */) {
                                inheritedIndentation = childIndentationAmount;
                            }
                        }
                        // child node is outside the target range - do not dive inside
                        if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
                            if (child.end < originalRange.pos) {
                                formattingScanner.skipToEndOf(child);
                            }
                            return inheritedIndentation;
                        }
                        if (child.getFullWidth() === 0) {
                            return inheritedIndentation;
                        }
                        while (formattingScanner.isOnToken()) {
                            // proceed any parent tokens that are located prior to child.getStart()
                            var tokenInfo = formattingScanner.readTokenInfo(node);
                            if (tokenInfo.token.end > childStartPos) {
                                // stop when formatting scanner advances past the beginning of the child
                                break;
                            }
                            consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
                        }
                        if (!formattingScanner.isOnToken()) {
                            return inheritedIndentation;
                        }
                        // JSX text shouldn't affect indenting
                        if (ts.isToken(child) && child.kind !== 10 /* JsxText */) {
                            // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
                            var tokenInfo = formattingScanner.readTokenInfo(child);
                            ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
                            consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
                            return inheritedIndentation;
                        }
                        var effectiveParentStartLine = child.kind === 150 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
                        var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
                        processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
                        if (child.kind === 10 /* JsxText */) {
                            var range = { pos: child.getStart(), end: child.getEnd() };
                            indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false);
                        }
                        childContextNode = node;
                        if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
                            inheritedIndentation = childIndentation.indentation;
                        }
                        return inheritedIndentation;
                    }
                    function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) {
                        ts.Debug.assert(ts.isNodeArray(nodes));
                        var listStartToken = getOpenTokenForList(parent, nodes);
                        var listDynamicIndentation = parentDynamicIndentation;
                        var startLine = parentStartLine;
                        if (listStartToken !== 0 /* Unknown */) {
                            // introduce a new indentation scope for lists (including list start and end tokens)
                            while (formattingScanner.isOnToken()) {
                                var tokenInfo = formattingScanner.readTokenInfo(parent);
                                if (tokenInfo.token.end > nodes.pos) {
                                    // stop when formatting scanner moves past the beginning of node list
                                    break;
                                }
                                else if (tokenInfo.token.kind === listStartToken) {
                                    // consume list start token
                                    startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
                                    var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine);
                                    listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta);
                                    consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent);
                                }
                                else {
                                    // consume any tokens that precede the list as child elements of 'node' using its indentation scope
                                    consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
                                }
                            }
                        }
                        var inheritedIndentation = -1 /* Unknown */;
                        for (var i = 0; i < nodes.length; i++) {
                            var child = nodes[i];
                            inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0);
                        }
                        var listEndToken = getCloseTokenForOpenToken(listStartToken);
                        if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) {
                            var tokenInfo = formattingScanner.readTokenInfo(parent);
                            if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) {
                                formattingScanner.advance();
                                tokenInfo = formattingScanner.readTokenInfo(parent);
                            }
                            // consume the list end token only if it is still belong to the parent
                            // there might be the case when current token matches end token but does not considered as one
                            // function (x: function) <--
                            // without this check close paren will be interpreted as list end token for function expression which is wrong
                            if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) {
                                // consume list end token
                                consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent);
                            }
                        }
                    }
                    function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) {
                        ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token));
                        var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
                        var indentToken = false;
                        if (currentTokenInfo.leadingTrivia) {
                            processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation);
                        }
                        var lineAction = 0 /* None */;
                        var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token);
                        var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
                        if (isTokenInRange) {
                            var rangeHasError = rangeContainsError(currentTokenInfo.token);
                            // save previousRange since processRange will overwrite this value with current one
                            var savePreviousRange = previousRange;
                            lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation);
                            // do not indent comments\token if token range overlaps with some error
                            if (!rangeHasError) {
                                if (lineAction === 0 /* None */) {
                                    // indent token only if end line of previous range does not match start line of the token
                                    var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line;
                                    indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine;
                                }
                                else {
                                    indentToken = lineAction === 1 /* LineAdded */;
                                }
                            }
                        }
                        if (currentTokenInfo.trailingTrivia) {
                            processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation);
                        }
                        if (indentToken) {
                            var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
                                dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) :
                                -1 /* Unknown */;
                            var indentNextTokenOrTrivia = true;
                            if (currentTokenInfo.leadingTrivia) {
                                var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
                                for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) {
                                    var triviaItem = _a[_i];
                                    var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem);
                                    switch (triviaItem.kind) {
                                        case 3 /* MultiLineCommentTrivia */:
                                            if (triviaInRange) {
                                                indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
                                            }
                                            indentNextTokenOrTrivia = false;
                                            break;
                                        case 2 /* SingleLineCommentTrivia */:
                                            if (indentNextTokenOrTrivia && triviaInRange) {
                                                insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false);
                                            }
                                            indentNextTokenOrTrivia = false;
                                            break;
                                        case 4 /* NewLineTrivia */:
                                            indentNextTokenOrTrivia = true;
                                            break;
                                    }
                                }
                            }
                            // indent token only if is it is in target range and does not overlap with any error ranges
                            if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) {
                                insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */);
                                lastIndentedLine = tokenStart.line;
                                indentationOnLastIndentedLine = tokenIndentation;
                            }
                        }
                        formattingScanner.advance();
                        childContextNode = parent;
                    }
                }
                function processTrivia(trivia, parent, contextNode, dynamicIndentation) {
                    for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) {
                        var triviaItem = trivia_1[_i];
                        if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) {
                            var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
                            processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation);
                        }
                    }
                }
                // TODO: GH#18217 use an enum instead of `boolean | undefined`
                function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) {
                    var rangeHasError = rangeContainsError(range);
                    var lineAction = 0 /* None */;
                    if (!rangeHasError) {
                        if (!previousRange) {
                            // trim whitespaces starting from the beginning of the span up to the current line
                            var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
                            trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
                        }
                        else {
                            lineAction =
                                processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
                        }
                    }
                    previousRange = range;
                    previousParent = parent;
                    previousRangeStartLine = rangeStart.line;
                    return lineAction;
                }
                function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) {
                    formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode);
                    var rule = getRule(formattingContext);
                    var trimTrailingWhitespaces;
                    var lineAction = 0 /* None */;
                    if (rule) {
                        lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine);
                        switch (lineAction) {
                            case 2 /* LineRemoved */:
                                // Handle the case where the next line is moved to be the end of this line.
                                // In this case we don't indent the next line in the next pass.
                                if (currentParent.getStart(sourceFile) === currentItem.pos) {
                                    dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false);
                                }
                                break;
                            case 1 /* LineAdded */:
                                // Handle the case where token2 is moved to the new line.
                                // In this case we indent token2 in the next pass but we set
                                // sameLineIndent flag to notify the indenter that the indentation is within the line.
                                if (currentParent.getStart(sourceFile) === currentItem.pos) {
                                    dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true);
                                }
                                break;
                            default:
                                ts.Debug.assert(lineAction === 0 /* None */);
                        }
                        // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
                        trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */;
                    }
                    else {
                        trimTrailingWhitespaces = true;
                    }
                    if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) {
                        // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
                        trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem);
                    }
                    return lineAction;
                }
                function insertIndentation(pos, indentation, lineAdded) {
                    var indentationString = getIndentationString(indentation, options);
                    if (lineAdded) {
                        // new line is added before the token by the formatting rules
                        // insert indentation string at the very beginning of the token
                        recordReplace(pos, 0, indentationString);
                    }
                    else {
                        var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
                        var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile);
                        if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) {
                            recordReplace(startLinePosition, tokenStart.character, indentationString);
                        }
                    }
                }
                function characterToColumn(startLinePosition, characterInLine) {
                    var column = 0;
                    for (var i = 0; i < characterInLine; i++) {
                        if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) {
                            column += options.tabSize - column % options.tabSize;
                        }
                        else {
                            column++;
                        }
                    }
                    return column;
                }
                function indentationIsDifferent(indentationString, startLinePosition) {
                    return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length);
                }
                function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) {
                    if (indentFinalLine === void 0) {
                        indentFinalLine = true;
                    }
                    // split comment in lines
                    var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line;
                    var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
                    if (startLine === endLine) {
                        if (!firstLineIsIndented) {
                            // treat as single line comment
                            insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false);
                        }
                        return;
                    }
                    var parts = [];
                    var startPos = commentRange.pos;
                    for (var line = startLine; line < endLine; line++) {
                        var endOfLine = ts.getEndLinePosition(line, sourceFile);
                        parts.push({ pos: startPos, end: endOfLine });
                        startPos = ts.getStartPositionOfLine(line + 1, sourceFile);
                    }
                    if (indentFinalLine) {
                        parts.push({ pos: startPos, end: commentRange.end });
                    }
                    if (parts.length === 0)
                        return;
                    var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile);
                    var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options);
                    if (indentation === nonWhitespaceColumnInFirstPart.column) {
                        return;
                    }
                    var startIndex = 0;
                    if (firstLineIsIndented) {
                        startIndex = 1;
                        startLine++;
                    }
                    // shift all parts on the delta size
                    var delta = indentation - nonWhitespaceColumnInFirstPart.column;
                    for (var i = startIndex; i < parts.length; i++, startLine++) {
                        var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile);
                        var nonWhitespaceCharacterAndColumn = i === 0
                            ? nonWhitespaceColumnInFirstPart
                            : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options);
                        var newIndentation = nonWhitespaceCharacterAndColumn.column + delta;
                        if (newIndentation > 0) {
                            var indentationString = getIndentationString(newIndentation, options);
                            recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString);
                        }
                        else {
                            recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character);
                        }
                    }
                }
                function trimTrailingWhitespacesForLines(line1, line2, range) {
                    for (var line = line1; line < line2; line++) {
                        var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile);
                        var lineEndPosition = ts.getEndLinePosition(line, sourceFile);
                        // do not trim whitespaces in comments or template expression
                        if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
                            continue;
                        }
                        var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
                        if (whitespaceStart !== -1) {
                            ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1)));
                            recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
                        }
                    }
                }
                /**
                 * @param start The position of the first character in range
                 * @param end The position of the last character in range
                 */
                function getTrailingWhitespaceStartPosition(start, end) {
                    var pos = end;
                    while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) {
                        pos--;
                    }
                    if (pos !== end) {
                        return pos + 1;
                    }
                    return -1;
                }
                /**
                 * Trimming will be done for lines after the previous range
                 */
                function trimTrailingWhitespacesForRemainingRange() {
                    var startPosition = previousRange ? previousRange.end : originalRange.pos;
                    var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
                    var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line;
                    trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange);
                }
                function recordDelete(start, len) {
                    if (len) {
                        edits.push(ts.createTextChangeFromStartLength(start, len, ""));
                    }
                }
                function recordReplace(start, len, newText) {
                    if (len || newText) {
                        edits.push(ts.createTextChangeFromStartLength(start, len, newText));
                    }
                }
                function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) {
                    var onLaterLine = currentStartLine !== previousStartLine;
                    switch (rule.action) {
                        case 1 /* Ignore */:
                            // no action required
                            return 0 /* None */;
                        case 8 /* Delete */:
                            if (previousRange.end !== currentRange.pos) {
                                // delete characters starting from t1.end up to t2.pos exclusive
                                recordDelete(previousRange.end, currentRange.pos - previousRange.end);
                                return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
                            }
                            break;
                        case 4 /* NewLine */:
                            // exit early if we on different lines and rule cannot change number of newlines
                            // if line1 and line2 are on subsequent lines then no edits are required - ok to exit
                            // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines
                            if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
                                return 0 /* None */;
                            }
                            // edit should not be applied if we have one line feed between elements
                            var lineDelta = currentStartLine - previousStartLine;
                            if (lineDelta !== 1) {
                                recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter);
                                return onLaterLine ? 0 /* None */ : 1 /* LineAdded */;
                            }
                            break;
                        case 2 /* Space */:
                            // exit early if we on different lines and rule cannot change number of newlines
                            if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
                                return 0 /* None */;
                            }
                            var posDelta = currentRange.pos - previousRange.end;
                            if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) {
                                recordReplace(previousRange.end, currentRange.pos - previousRange.end, " ");
                                return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
                            }
                    }
                    return 0 /* None */;
                }
            }
            var LineAction;
            (function (LineAction) {
                LineAction[LineAction["None"] = 0] = "None";
                LineAction[LineAction["LineAdded"] = 1] = "LineAdded";
                LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved";
            })(LineAction || (LineAction = {}));
            /**
             * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`.
             */
            function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword
            tokenAtPosition) {
                if (tokenAtPosition === void 0) {
                    tokenAtPosition = ts.getTokenAtPosition(sourceFile, position);
                }
                var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc);
                if (jsdoc)
                    tokenAtPosition = jsdoc.parent;
                var tokenStart = tokenAtPosition.getStart(sourceFile);
                if (tokenStart <= position && position < tokenAtPosition.getEnd()) {
                    return undefined;
                }
                precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken;
                // Between two consecutive tokens, all comments are either trailing on the former
                // or leading on the latter (and none are in both lists).
                var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end);
                var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile);
                var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken);
                return commentRanges && ts.find(commentRanges, function (range) {
                    return ts.rangeContainsPositionExclusive(range, position) ||
                        // The end marker of a single-line comment does not include the newline character.
                        // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
                        //
                        //    // asdf   ^\n
                        //
                        // But for closed multi-line comments, we don't want to be inside the comment in the following case:
                        //
                        //    /* asdf */^
                        //
                        // However, unterminated multi-line comments *do* contain their end.
                        //
                        // Internally, we represent the end of the comment at the newline and closing '/', respectively.
                        //
                        position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth());
                });
            }
            formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment;
            function getOpenTokenForList(node, list) {
                switch (node.kind) {
                    case 155 /* Constructor */:
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 195 /* ArrowFunction */:
                        if (node.typeParameters === list) {
                            return 27 /* LessThanToken */;
                        }
                        else if (node.parameters === list) {
                            return 19 /* OpenParenToken */;
                        }
                        break;
                    case 189 /* CallExpression */:
                    case 190 /* NewExpression */:
                        if (node.typeArguments === list) {
                            return 27 /* LessThanToken */;
                        }
                        else if (node.arguments === list) {
                            return 19 /* OpenParenToken */;
                        }
                        break;
                    case 162 /* TypeReference */:
                        if (node.typeArguments === list) {
                            return 27 /* LessThanToken */;
                        }
                }
                return 0 /* Unknown */;
            }
            function getCloseTokenForOpenToken(kind) {
                switch (kind) {
                    case 19 /* OpenParenToken */:
                        return 20 /* CloseParenToken */;
                    case 27 /* LessThanToken */:
                        return 29 /* GreaterThanToken */;
                }
                return 0 /* Unknown */;
            }
            var internedSizes;
            var internedTabsIndentation;
            var internedSpacesIndentation;
            function getIndentationString(indentation, options) {
                // reset interned strings if FormatCodeOptions were changed
                var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
                if (resetInternedStrings) {
                    internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
                    internedTabsIndentation = internedSpacesIndentation = undefined;
                }
                if (!options.convertTabsToSpaces) {
                    var tabs = Math.floor(indentation / options.tabSize);
                    var spaces = indentation - tabs * options.tabSize;
                    var tabString = void 0;
                    if (!internedTabsIndentation) {
                        internedTabsIndentation = [];
                    }
                    if (internedTabsIndentation[tabs] === undefined) {
                        internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs);
                    }
                    else {
                        tabString = internedTabsIndentation[tabs];
                    }
                    return spaces ? tabString + ts.repeatString(" ", spaces) : tabString;
                }
                else {
                    var spacesString = void 0;
                    var quotient = Math.floor(indentation / options.indentSize);
                    var remainder = indentation % options.indentSize;
                    if (!internedSpacesIndentation) {
                        internedSpacesIndentation = [];
                    }
                    if (internedSpacesIndentation[quotient] === undefined) {
                        spacesString = ts.repeatString(" ", options.indentSize * quotient);
                        internedSpacesIndentation[quotient] = spacesString;
                    }
                    else {
                        spacesString = internedSpacesIndentation[quotient];
                    }
                    return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString;
                }
            }
            formatting.getIndentationString = getIndentationString;
        })(formatting = ts.formatting || (ts.formatting = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var formatting;
        (function (formatting) {
            var SmartIndenter;
            (function (SmartIndenter) {
                var Value;
                (function (Value) {
                    Value[Value["Unknown"] = -1] = "Unknown";
                })(Value || (Value = {}));
                /**
                 * @param assumeNewLineBeforeCloseBrace
                 * `false` when called on text from a real source file.
                 * `true` when we need to assume `position` is on a newline.
                 *
                 * This is useful for codefixes. Consider
                 * ```
                 * function f() {
                 * |}
                 * ```
                 * with `position` at `|`.
                 *
                 * When inserting some text after an open brace, we would like to get indentation as if a newline was already there.
                 * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior.
                 */
                function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) {
                    if (assumeNewLineBeforeCloseBrace === void 0) {
                        assumeNewLineBeforeCloseBrace = false;
                    }
                    if (position > sourceFile.text.length) {
                        return getBaseIndentation(options); // past EOF
                    }
                    // no indentation when the indent style is set to none,
                    // so we can return fast
                    if (options.indentStyle === ts.IndentStyle.None) {
                        return 0;
                    }
                    var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true);
                    var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword
                    if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) {
                        return getCommentIndent(sourceFile, position, options, enclosingCommentRange);
                    }
                    if (!precedingToken) {
                        return getBaseIndentation(options);
                    }
                    // no indentation in string \regex\template literals
                    var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
                    if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) {
                        return 0;
                    }
                    var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
                    // indentation is first non-whitespace character in a previous line
                    // for block indentation, we should look for a line which contains something that's not
                    // whitespace.
                    if (options.indentStyle === ts.IndentStyle.Block) {
                        return getBlockIndent(sourceFile, position, options);
                    }
                    if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) {
                        // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
                        var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
                        if (actualIndentation !== -1 /* Unknown */) {
                            return actualIndentation;
                        }
                    }
                    return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options);
                }
                SmartIndenter.getIndentation = getIndentation;
                function getCommentIndent(sourceFile, position, options, enclosingCommentRange) {
                    var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1;
                    var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line;
                    ts.Debug.assert(commentStartLine >= 0);
                    if (previousLine <= commentStartLine) {
                        return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options);
                    }
                    var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile);
                    var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character;
                    if (column === 0) {
                        return column;
                    }
                    var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character);
                    return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column;
                }
                function getBlockIndent(sourceFile, position, options) {
                    // move backwards until we find a line with a non-whitespace character,
                    // then find the first non-whitespace character for that line.
                    var current = position;
                    while (current > 0) {
                        var char = sourceFile.text.charCodeAt(current);
                        if (!ts.isWhiteSpaceLike(char)) {
                            break;
                        }
                        current--;
                    }
                    var lineStart = ts.getLineStartPositionForPosition(current, sourceFile);
                    return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options);
                }
                function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) {
                    // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken'
                    // if such node is found - compute initial indentation for 'position' inside this node
                    var previous;
                    var current = precedingToken;
                    while (current) {
                        if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) {
                            var currentStart = getStartLineAndCharacterForNode(current, sourceFile);
                            var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile);
                            var indentationDelta = nextTokenKind !== 0 /* Unknown */
                                // handle cases when codefix is about to be inserted before the close brace
                                ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0
                                : lineAtPosition !== currentStart.line ? options.indentSize : 0;
                            return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217
                        }
                        // check if current node is a list item - if yes, take indentation from it
                        var actualIndentation = getActualIndentationForListItem(current, sourceFile, options);
                        if (actualIndentation !== -1 /* Unknown */) {
                            return actualIndentation;
                        }
                        actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
                        if (actualIndentation !== -1 /* Unknown */) {
                            return actualIndentation + options.indentSize; // TODO: GH#18217
                        }
                        previous = current;
                        current = current.parent;
                    }
                    // no parent was found - return the base indentation of the SourceFile
                    return getBaseIndentation(options);
                }
                function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
                    var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
                    return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options);
                }
                SmartIndenter.getIndentationForNode = getIndentationForNode;
                function getBaseIndentation(options) {
                    return options.baseIndentSize || 0;
                }
                SmartIndenter.getBaseIndentation = getBaseIndentation;
                function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) {
                    var parent = current.parent;
                    // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if
                    // * parent and child nodes start on the same line, or
                    // * parent is an IfStatement and child starts on the same line as an 'else clause'.
                    while (parent) {
                        var useActualIndentation = true;
                        if (ignoreActualIndentationRange) {
                            var start = current.getStart(sourceFile);
                            useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end;
                        }
                        if (useActualIndentation) {
                            // check if current node is a list item - if yes, take indentation from it
                            var actualIndentation = getActualIndentationForListItem(current, sourceFile, options);
                            if (actualIndentation !== -1 /* Unknown */) {
                                return actualIndentation + indentationDelta;
                            }
                        }
                        var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile);
                        var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line ||
                            childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile);
                        if (useActualIndentation) {
                            // try to fetch actual indentation for current node from source text
                            var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options);
                            if (actualIndentation !== -1 /* Unknown */) {
                                return actualIndentation + indentationDelta;
                            }
                            actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
                            if (actualIndentation !== -1 /* Unknown */) {
                                return actualIndentation + indentationDelta;
                            }
                        }
                        // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
                        if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) {
                            indentationDelta += options.indentSize;
                        }
                        // In our AST, a call argument's `parent` is the call-expression, not the argument list.
                        // We would like to increase indentation based on the relationship between an argument and its argument-list,
                        // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list.
                        // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression
                        // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation.
                        //
                        // Instead, when at an argument, we unspoof the starting position of the enclosing call expression
                        // *after* applying indentation for the argument.
                        var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile);
                        current = parent;
                        parent = current.parent;
                        currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart;
                    }
                    return indentationDelta + getBaseIndentation(options);
                }
                function getContainingListOrParentStart(parent, child, sourceFile) {
                    var containingList = getContainingList(child, sourceFile);
                    var startPos = containingList ? containingList.pos : parent.getStart(sourceFile);
                    return sourceFile.getLineAndCharacterOfPosition(startPos);
                }
                /*
                 * Function returns Value.Unknown if indentation cannot be determined
                 */
                function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) {
                    // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
                    var commaItemInfo = ts.findListItemInfo(commaToken);
                    if (commaItemInfo && commaItemInfo.listItemIndex > 0) {
                        return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options);
                    }
                    else {
                        // handle broken code gracefully
                        return -1 /* Unknown */;
                    }
                }
                /*
                 * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression)
                 */
                function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) {
                    // actual indentation is used for statements\declarations if one of cases below is true:
                    // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
                    // - parent and child are not on the same line
                    var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
                        (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine);
                    if (!useActualIndentation) {
                        return -1 /* Unknown */;
                    }
                    return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options);
                }
                var NextTokenKind;
                (function (NextTokenKind) {
                    NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown";
                    NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace";
                    NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
                })(NextTokenKind || (NextTokenKind = {}));
                function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
                    var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
                    if (!nextToken) {
                        return 0 /* Unknown */;
                    }
                    if (nextToken.kind === 17 /* OpenBraceToken */) {
                        // open braces are always indented at the parent level
                        return 1 /* OpenBrace */;
                    }
                    else if (nextToken.kind === 18 /* CloseBraceToken */) {
                        // close braces are indented at the parent level if they are located on the same line with cursor
                        // this means that if new line will be added at $ position, this case will be indented
                        // class A {
                        //    $
                        // }
                        /// and this one - not
                        // class A {
                        // $}
                        var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
                        return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */;
                    }
                    return 0 /* Unknown */;
                }
                function getStartLineAndCharacterForNode(n, sourceFile) {
                    return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
                }
                function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) {
                    if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) {
                        return false;
                    }
                    var expressionOfCallExpressionEnd = parent.expression.getEnd();
                    var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line;
                    return expressionOfCallExpressionEndLine === childStartLine;
                }
                SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled;
                function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) {
                    if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) {
                        var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile);
                        ts.Debug.assert(elseKeyword !== undefined);
                        var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
                        return elseKeywordStartLine === childStartLine;
                    }
                    return false;
                }
                SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
                function getListIfStartEndIsInListRange(list, start, end) {
                    return list && ts.rangeContainsStartEnd(list, start, end) ? list : undefined;
                }
                function getContainingList(node, sourceFile) {
                    if (node.parent) {
                        var end = node.end;
                        switch (node.parent.kind) {
                            case 162 /* TypeReference */:
                                return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
                            case 186 /* ObjectLiteralExpression */:
                                return node.parent.properties;
                            case 185 /* ArrayLiteralExpression */:
                                return node.parent.elements;
                            case 237 /* FunctionDeclaration */:
                            case 194 /* FunctionExpression */:
                            case 195 /* ArrowFunction */:
                            case 154 /* MethodDeclaration */:
                            case 153 /* MethodSignature */:
                            case 158 /* CallSignature */:
                            case 155 /* Constructor */:
                            case 164 /* ConstructorType */:
                            case 159 /* ConstructSignature */: {
                                var start = node.getStart(sourceFile);
                                return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
                                    getListIfStartEndIsInListRange(node.parent.parameters, start, end);
                            }
                            case 238 /* ClassDeclaration */:
                            case 207 /* ClassExpression */:
                            case 239 /* InterfaceDeclaration */:
                            case 240 /* TypeAliasDeclaration */:
                            case 301 /* JSDocTemplateTag */: {
                                var typeParameters = node.parent.typeParameters;
                                return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end);
                            }
                            case 190 /* NewExpression */:
                            case 189 /* CallExpression */: {
                                var start = node.getStart(sourceFile);
                                return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
                                    getListIfStartEndIsInListRange(node.parent.arguments, start, end);
                            }
                            case 236 /* VariableDeclarationList */:
                                return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
                            case 250 /* NamedImports */:
                            case 254 /* NamedExports */:
                                return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
                            case 182 /* ObjectBindingPattern */:
                            case 183 /* ArrayBindingPattern */:
                                return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
                        }
                    }
                    return undefined;
                }
                SmartIndenter.getContainingList = getContainingList;
                function getActualIndentationForListItem(node, sourceFile, options) {
                    var containingList = getContainingList(node, sourceFile);
                    if (containingList) {
                        var index = containingList.indexOf(node);
                        if (index !== -1) {
                            return deriveActualIndentationFromList(containingList, index, sourceFile, options);
                        }
                    }
                    return -1 /* Unknown */;
                }
                function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) {
                    // actual indentation should not be used when:
                    // - node is close parenthesis - this is the end of the expression
                    if (node.kind === 20 /* CloseParenToken */) {
                        return -1 /* Unknown */;
                    }
                    if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) {
                        var fullCallOrNewExpression = node.parent.expression;
                        var startingExpression = getStartingExpression(fullCallOrNewExpression);
                        if (fullCallOrNewExpression === startingExpression) {
                            return -1 /* Unknown */;
                        }
                        var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end);
                        var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end);
                        if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) {
                            return -1 /* Unknown */;
                        }
                        return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options);
                    }
                    return -1 /* Unknown */;
                    function getStartingExpression(node) {
                        while (true) {
                            switch (node.kind) {
                                case 189 /* CallExpression */:
                                case 190 /* NewExpression */:
                                case 187 /* PropertyAccessExpression */:
                                case 188 /* ElementAccessExpression */:
                                    node = node.expression;
                                    break;
                                default:
                                    return node;
                            }
                        }
                    }
                }
                function deriveActualIndentationFromList(list, index, sourceFile, options) {
                    ts.Debug.assert(index >= 0 && index < list.length);
                    var node = list[index];
                    // walk toward the start of the list starting from current node and check if the line is the same for all items.
                    // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i]
                    var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile);
                    for (var i = index - 1; i >= 0; i--) {
                        if (list[i].kind === 26 /* CommaToken */) {
                            continue;
                        }
                        // skip list items that ends on the same line with the current list element
                        var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
                        if (prevEndLine !== lineAndCharacter.line) {
                            return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options);
                        }
                        lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile);
                    }
                    return -1 /* Unknown */;
                }
                function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) {
                    var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
                    return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options);
                }
                /**
                 * Character is the actual index of the character since the beginning of the line.
                 * Column - position of the character after expanding tabs to spaces.
                 * "0\t2$"
                 * value of 'character' for '$' is 3
                 * value of 'column' for '$' is 6 (assuming that tab size is 4)
                 */
                function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) {
                    var character = 0;
                    var column = 0;
                    for (var pos = startPos; pos < endPos; pos++) {
                        var ch = sourceFile.text.charCodeAt(pos);
                        if (!ts.isWhiteSpaceSingleLine(ch)) {
                            break;
                        }
                        if (ch === 9 /* tab */) {
                            column += options.tabSize + (column % options.tabSize);
                        }
                        else {
                            column++;
                        }
                        character++;
                    }
                    return { column: column, character: character };
                }
                SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn;
                function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) {
                    return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column;
                }
                SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn;
                function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) {
                    var childKind = child ? child.kind : 0 /* Unknown */;
                    switch (parent.kind) {
                        case 219 /* ExpressionStatement */:
                        case 238 /* ClassDeclaration */:
                        case 207 /* ClassExpression */:
                        case 239 /* InterfaceDeclaration */:
                        case 241 /* EnumDeclaration */:
                        case 240 /* TypeAliasDeclaration */:
                        case 185 /* ArrayLiteralExpression */:
                        case 216 /* Block */:
                        case 243 /* ModuleBlock */:
                        case 186 /* ObjectLiteralExpression */:
                        case 166 /* TypeLiteral */:
                        case 179 /* MappedType */:
                        case 168 /* TupleType */:
                        case 244 /* CaseBlock */:
                        case 270 /* DefaultClause */:
                        case 269 /* CaseClause */:
                        case 193 /* ParenthesizedExpression */:
                        case 187 /* PropertyAccessExpression */:
                        case 189 /* CallExpression */:
                        case 190 /* NewExpression */:
                        case 217 /* VariableStatement */:
                        case 252 /* ExportAssignment */:
                        case 228 /* ReturnStatement */:
                        case 203 /* ConditionalExpression */:
                        case 183 /* ArrayBindingPattern */:
                        case 182 /* ObjectBindingPattern */:
                        case 260 /* JsxOpeningElement */:
                        case 263 /* JsxOpeningFragment */:
                        case 259 /* JsxSelfClosingElement */:
                        case 268 /* JsxExpression */:
                        case 153 /* MethodSignature */:
                        case 158 /* CallSignature */:
                        case 159 /* ConstructSignature */:
                        case 149 /* Parameter */:
                        case 163 /* FunctionType */:
                        case 164 /* ConstructorType */:
                        case 175 /* ParenthesizedType */:
                        case 191 /* TaggedTemplateExpression */:
                        case 199 /* AwaitExpression */:
                        case 254 /* NamedExports */:
                        case 250 /* NamedImports */:
                        case 255 /* ExportSpecifier */:
                        case 251 /* ImportSpecifier */:
                        case 152 /* PropertyDeclaration */:
                            return true;
                        case 235 /* VariableDeclaration */:
                        case 273 /* PropertyAssignment */:
                            if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217
                                return rangeIsOnOneLine(sourceFile, child);
                            }
                            return true;
                        case 221 /* DoStatement */:
                        case 222 /* WhileStatement */:
                        case 224 /* ForInStatement */:
                        case 225 /* ForOfStatement */:
                        case 223 /* ForStatement */:
                        case 220 /* IfStatement */:
                        case 237 /* FunctionDeclaration */:
                        case 194 /* FunctionExpression */:
                        case 154 /* MethodDeclaration */:
                        case 195 /* ArrowFunction */:
                        case 155 /* Constructor */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                            return childKind !== 216 /* Block */;
                        case 253 /* ExportDeclaration */:
                            return childKind !== 254 /* NamedExports */;
                        case 247 /* ImportDeclaration */:
                            return childKind !== 248 /* ImportClause */ ||
                                (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */);
                        case 258 /* JsxElement */:
                            return childKind !== 261 /* JsxClosingElement */;
                        case 262 /* JsxFragment */:
                            return childKind !== 264 /* JsxClosingFragment */;
                        case 172 /* IntersectionType */:
                        case 171 /* UnionType */:
                            if (childKind === 166 /* TypeLiteral */) {
                                return false;
                            }
                        // falls through
                    }
                    // No explicit rule for given nodes so the result will follow the default value argument
                    return indentByDefault;
                }
                SmartIndenter.nodeWillIndentChild = nodeWillIndentChild;
                function isControlFlowEndingStatement(kind, parent) {
                    switch (kind) {
                        case 228 /* ReturnStatement */:
                        case 232 /* ThrowStatement */:
                        case 226 /* ContinueStatement */:
                        case 227 /* BreakStatement */:
                            return parent.kind !== 216 /* Block */;
                        default:
                            return false;
                    }
                }
                /**
                 * True when the parent node should indent the given child by an explicit rule.
                 * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child.
                 */
                function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) {
                    if (isNextChild === void 0) {
                        isNextChild = false;
                    }
                    return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)
                        && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent));
                }
                SmartIndenter.shouldIndentChildNode = shouldIndentChildNode;
                function rangeIsOnOneLine(sourceFile, range) {
                    var rangeStart = ts.skipTrivia(sourceFile.text, range.pos);
                    var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line;
                    var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
                    return startLine === endLine;
                }
            })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {}));
        })(formatting = ts.formatting || (ts.formatting = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var textChanges;
        (function (textChanges_3) {
            /**
             * Currently for simplicity we store recovered positions on the node itself.
             * It can be changed to side-table later if we decide that current design is too invasive.
             */
            function getPos(n) {
                var result = n.__pos;
                ts.Debug.assert(typeof result === "number");
                return result;
            }
            function setPos(n, pos) {
                ts.Debug.assert(typeof pos === "number");
                n.__pos = pos;
            }
            function getEnd(n) {
                var result = n.__end;
                ts.Debug.assert(typeof result === "number");
                return result;
            }
            function setEnd(n, end) {
                ts.Debug.assert(typeof end === "number");
                n.__end = end;
            }
            var Position;
            (function (Position) {
                Position[Position["FullStart"] = 0] = "FullStart";
                Position[Position["Start"] = 1] = "Start";
            })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
            function skipWhitespacesAndLineBreaks(text, start) {
                return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
            }
            function hasCommentsBeforeLineBreak(text, start) {
                var i = start;
                while (i < text.length) {
                    var ch = text.charCodeAt(i);
                    if (ts.isWhiteSpaceSingleLine(ch)) {
                        i++;
                        continue;
                    }
                    return ch === 47 /* slash */;
                }
                return false;
            }
            textChanges_3.useNonAdjustedPositions = {
                useNonAdjustedStartPosition: true,
                useNonAdjustedEndPosition: true,
            };
            var ChangeKind;
            (function (ChangeKind) {
                ChangeKind[ChangeKind["Remove"] = 0] = "Remove";
                ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode";
                ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes";
                ChangeKind[ChangeKind["Text"] = 3] = "Text";
            })(ChangeKind || (ChangeKind = {}));
            function getAdjustedRange(sourceFile, startNode, endNode, options) {
                return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
            }
            function getAdjustedStartPosition(sourceFile, node, options, position) {
                if (options.useNonAdjustedStartPosition) {
                    return node.getStart(sourceFile);
                }
                var fullStart = node.getFullStart();
                var start = node.getStart(sourceFile);
                if (fullStart === start) {
                    return start;
                }
                var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile);
                var startLine = ts.getLineStartPositionForPosition(start, sourceFile);
                if (startLine === fullStartLine) {
                    // full start and start of the node are on the same line
                    //   a,     b;
                    //    ^     ^
                    //    |   start
                    // fullstart
                    // when b is replaced - we usually want to keep the leading trvia
                    // when b is deleted - we delete it
                    return position === Position.Start ? start : fullStart;
                }
                // get start position of the line following the line that contains fullstart position
                // (but only if the fullstart isn't the very beginning of the file)
                var nextLineStart = fullStart > 0 ? 1 : 0;
                var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile);
                // skip whitespaces/newlines
                adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
                return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
            }
            function getAdjustedEndPosition(sourceFile, node, options) {
                var end = node.end;
                if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
                    return end;
                }
                var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
                return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
                    ? newEnd
                    : end;
            }
            /**
             * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element
             */
            function isSeparator(node, candidate) {
                return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */));
            }
            function spaces(count) {
                var s = "";
                for (var i = 0; i < count; i++) {
                    s += " ";
                }
                return s;
            }
            var ChangeTracker = /** @class */ (function () {
                /** Public for tests only. Other callers should use `ChangeTracker.with`. */
                function ChangeTracker(newLineCharacter, formatContext) {
                    this.newLineCharacter = newLineCharacter;
                    this.formatContext = formatContext;
                    this.changes = [];
                    this.newFiles = [];
                    this.classesWithNodesInsertedAtStart = ts.createMap(); // Set<ClassDeclaration> implemented as Map<node id, ClassDeclaration>
                    this.deletedNodes = [];
                }
                ChangeTracker.fromContext = function (context) {
                    return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
                };
                ChangeTracker.with = function (context, cb) {
                    var tracker = ChangeTracker.fromContext(context);
                    cb(tracker);
                    return tracker.getChanges();
                };
                ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
                    this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
                    return this;
                };
                ChangeTracker.prototype.delete = function (sourceFile, node) {
                    this.deletedNodes.push({ sourceFile: sourceFile, node: node });
                };
                ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) {
                    this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
                };
                ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
                    if (options === void 0) {
                        options = {};
                    }
                    var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
                    var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
                    this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
                    return this;
                };
                ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
                    if (options === void 0) {
                        options = {};
                    }
                    var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
                    var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
                    this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
                };
                ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
                    if (options === void 0) {
                        options = {};
                    }
                    this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
                    return this;
                };
                ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
                    if (options === void 0) {
                        options = textChanges_3.useNonAdjustedPositions;
                    }
                    return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
                };
                ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
                    if (options === void 0) {
                        options = textChanges_3.useNonAdjustedPositions;
                    }
                    this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
                };
                ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
                    if (options === void 0) {
                        options = {};
                    }
                    this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
                    return this;
                };
                ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
                    if (options === void 0) {
                        options = textChanges_3.useNonAdjustedPositions;
                    }
                    return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
                };
                ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
                    if (options === void 0) {
                        options = textChanges_3.useNonAdjustedPositions;
                    }
                    return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
                };
                ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
                    var next = ts.findNextToken(node, node.parent, sourceFile);
                    return next && next.kind === 26 /* CommaToken */ ? next : undefined;
                };
                ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
                    var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
                    return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
                };
                ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
                    if (options === void 0) {
                        options = {};
                    }
                    this.replaceRange(sourceFile, ts.createRange(pos), newNode, options);
                };
                ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) {
                    if (options === void 0) {
                        options = {};
                    }
                    this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } });
                };
                ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) {
                    var pos = getInsertionPositionAtSourceFileTop(sourceFile);
                    this.insertNodeAt(sourceFile, pos, newNode, {
                        prefix: pos === 0 ? undefined : this.newLineCharacter,
                        suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""),
                    });
                };
                ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
                    if (blankLineBetween === void 0) {
                        blankLineBetween = false;
                    }
                    this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
                };
                ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
                    var pos = before.getStart(sourceFile);
                    this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " });
                };
                ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) {
                    if (!before.modifiers) {
                        this.insertModifierBefore(sourceFile, modifier, before);
                        return;
                    }
                    var pos = before.modifiers.end;
                    this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { prefix: " " });
                };
                ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) {
                    var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile);
                    var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
                    // First try to see if we can put the comment on the previous line.
                    // We need to make sure that we are not in the middle of a string literal or a comment.
                    // If so, we do not want to separate the node from its comment if we can.
                    // Otherwise, add an extra new line immediately before the error span.
                    var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
                    var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
                    var indent = sourceFile.text.slice(lineStartPosition, startPosition);
                    var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
                    this.insertText(sourceFile, token.getStart(sourceFile), text);
                };
                ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
                    this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text });
                };
                ChangeTracker.prototype.insertText = function (sourceFile, pos, text) {
                    this.replaceRangeWithText(sourceFile, ts.createRange(pos), text);
                };
                /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
                ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) {
                    var endNode;
                    if (ts.isFunctionLike(node)) {
                        endNode = ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile);
                        if (!endNode) {
                            if (!ts.isArrowFunction(node))
                                return; // Function missing parentheses, give up
                            // If no `)`, is an arrow function `x => x`, so use the end of the first parameter
                            endNode = ts.first(node.parameters);
                        }
                    }
                    else {
                        endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name;
                    }
                    this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " });
                };
                ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) {
                    // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter
                    var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile);
                    this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" });
                };
                ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) {
                    if (ts.isStatement(before) || ts.isClassElement(before)) {
                        return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
                    }
                    else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
                        return { suffix: ", " };
                    }
                    else if (ts.isParameter(before)) {
                        return {};
                    }
                    else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) {
                        return { suffix: ", " };
                    }
                    return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
                };
                ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
                    var firstStatement = ts.firstOrUndefined(ctr.body.statements);
                    if (!firstStatement || !ctr.body.multiLine) {
                        this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements));
                    }
                    else {
                        this.insertNodeBefore(sourceFile, firstStatement, newStatement);
                    }
                };
                ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) {
                    var lastStatement = ts.lastOrUndefined(ctr.body.statements);
                    if (!lastStatement || !ctr.body.multiLine) {
                        this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement]));
                    }
                    else {
                        this.insertNodeAfter(sourceFile, lastStatement, newStatement);
                    }
                };
                ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) {
                    this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
                };
                ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
                    var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
                    this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, {
                        prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
                        suffix: this.newLineCharacter
                    });
                };
                ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
                    this.insertNodeAtStartWorker(sourceFile, cls, newElement);
                };
                ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) {
                    this.insertNodeAtStartWorker(sourceFile, obj, newElement);
                };
                ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) {
                    var clsStart = cls.getStart(sourceFile);
                    var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
                        + this.formatContext.options.indentSize;
                    this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls)));
                };
                ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) {
                    var comma = ts.isObjectLiteralExpression(cls) ? "," : "";
                    if (getMembersOrProperties(cls).length === 0) {
                        if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) {
                            // For `class C {\n}`, don't add the trailing "\n"
                            var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any'
                            return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") };
                        }
                        else {
                            return { prefix: "", suffix: comma + this.newLineCharacter };
                        }
                    }
                    else {
                        return { prefix: this.newLineCharacter, suffix: comma };
                    }
                };
                ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) {
                    var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
                    this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
                };
                ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
                    var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
                    this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
                };
                ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) {
                    this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
                };
                ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
                    var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
                    this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
                };
                ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
                    if (needSemicolonBetween(after, newNode)) {
                        // check if previous statement ends with semicolon
                        // if not - insert semicolon to preserve the code from changing the meaning due to ASI
                        if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
                            this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */));
                        }
                    }
                    var endPosition = getAdjustedEndPosition(sourceFile, after, {});
                    return endPosition;
                };
                ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
                    var options = this.getInsertNodeAfterOptionsWorker(after);
                    return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
                };
                ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
                    switch (node.kind) {
                        case 238 /* ClassDeclaration */:
                        case 242 /* ModuleDeclaration */:
                            return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
                        case 235 /* VariableDeclaration */:
                        case 9 /* StringLiteral */:
                        case 71 /* Identifier */:
                            return { prefix: ", " };
                        case 273 /* PropertyAssignment */:
                            return { suffix: "," + this.newLineCharacter };
                        case 84 /* ExportKeyword */:
                            return { prefix: " " };
                        case 149 /* Parameter */:
                            return {};
                        default:
                            ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it
                            return { suffix: this.newLineCharacter };
                    }
                };
                ChangeTracker.prototype.insertName = function (sourceFile, node, name) {
                    ts.Debug.assert(!node.name);
                    if (node.kind === 195 /* ArrowFunction */) {
                        var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile);
                        var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile);
                        if (lparen) {
                            // `() => {}` --> `function f() {}`
                            this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " });
                            deleteNode(this, sourceFile, arrow);
                        }
                        else {
                            // `x => {}` -> `function f(x) {}`
                            this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "(");
                            // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)`
                            this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */));
                        }
                        if (node.body.kind !== 216 /* Block */) {
                            // `() => 0` => `function f() { return 0; }`
                            this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " });
                            this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " });
                        }
                    }
                    else {
                        var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end;
                        this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
                    }
                };
                ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
                    this.insertText(sourceFile, node.getStart(sourceFile), "export ");
                };
                /**
                 * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
                 * i.e. arguments in arguments lists, parameters in parameter lists etc.
                 * Note that separators are part of the node in statements and class elements.
                 */
                ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
                    if (containingList === void 0) {
                        containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
                    }
                    if (!containingList) {
                        ts.Debug.fail("node is not a list element");
                        return this;
                    }
                    var index = ts.indexOfNode(containingList, after);
                    if (index < 0) {
                        return this;
                    }
                    var end = after.getEnd();
                    if (index !== containingList.length - 1) {
                        // any element except the last one
                        // use next sibling as an anchor
                        var nextToken = ts.getTokenAtPosition(sourceFile, after.end);
                        if (nextToken && isSeparator(after, nextToken)) {
                            // for list
                            // a, b, c
                            // create change for adding 'e' after 'a' as
                            // - find start of next element after a (it is b)
                            // - use this start as start and end position in final change
                            // - build text of change by formatting the text of node + separator + whitespace trivia of b
                            // in multiline case it will work as
                            //   a,
                            //   b,
                            //   c,
                            // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#')
                            //   a,*
                            // ***insertedtext<separator>#
                            // ###b,
                            //   c,
                            // find line and character of the next element
                            var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart()));
                            // find line and character of the token that precedes next element (usually it is separator)
                            var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end);
                            var prefix = void 0;
                            var startPos = void 0;
                            if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) {
                                // next element is located on the same line with separator:
                                // a,$$$$b
                                //  ^    ^
                                //  |    |-next element
                                //  |-separator
                                // where $$$ is some leading trivia
                                // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces
                                // a,    x,$$$$b
                                //  ^    ^     ^
                                //  |    |     |-next element
                                //  |    |-new inserted node padded with spaces
                                //  |-separator
                                startPos = nextToken.end;
                                prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character);
                            }
                            else {
                                // next element is located on different line that separator
                                // let insert position be the beginning of the line that contains next element
                                startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile);
                            }
                            // write separator and leading trivia of the next element as suffix
                            var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile));
                            this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix });
                        }
                    }
                    else {
                        var afterStart = after.getStart(sourceFile);
                        var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile);
                        var separator = void 0;
                        var multilineList = false;
                        // insert element after the last element in the list that has more than one item
                        // pick the element preceding the after element to:
                        // - pick the separator
                        // - determine if list is a multiline
                        if (containingList.length === 1) {
                            // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise
                            // i.e. var x = 1 // this is x
                            //     | new element will be inserted at this position
                            separator = 26 /* CommaToken */;
                        }
                        else {
                            // element has more than one element, pick separator from the list
                            var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile);
                            separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 26 /* CommaToken */;
                            // determine if list is multiline by checking lines of after element and element that precedes it.
                            var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile);
                            multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition;
                        }
                        if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) {
                            // in this case we'll always treat containing list as multiline
                            multilineList = true;
                        }
                        if (multilineList) {
                            // insert separator immediately following the 'after' node to preserve comments in trailing trivia
                            this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator));
                            // use the same indentation as 'after' item
                            var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options);
                            // insert element before the line break on the line that contains 'after' element
                            var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false);
                            if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
                                insertPos--;
                            }
                            this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter });
                        }
                        else {
                            this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
                        }
                    }
                    return this;
                };
                ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
                    var _this = this;
                    this.classesWithNodesInsertedAtStart.forEach(function (_a) {
                        var node = _a.node, sourceFile = _a.sourceFile;
                        var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1];
                        // For `class C { }` remove the whitespace inside the braces.
                        if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) {
                            _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1));
                        }
                    });
                };
                ChangeTracker.prototype.finishDeleteDeclarations = function () {
                    var _this = this;
                    var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
                    var _loop_16 = function (sourceFile, node) {
                        if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
                            if (ts.isArray(node)) {
                                this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
                            }
                            else {
                                deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node);
                            }
                        }
                    };
                    var this_1 = this;
                    for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
                        var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
                        _loop_16(sourceFile, node);
                    }
                    deletedNodesInLists.forEach(function (node) {
                        var sourceFile = node.getSourceFile();
                        var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile);
                        if (node !== ts.last(list))
                            return;
                        var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2);
                        if (lastNonDeletedIndex !== -1) {
                            _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
                        }
                    });
                };
                /**
                 * Note: after calling this, the TextChanges object must be discarded!
                 * @param validate only for tests
                 *    The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
                 *    so we can only call this once and can't get the non-formatted text separately.
                 */
                ChangeTracker.prototype.getChanges = function (validate) {
                    this.finishDeleteDeclarations();
                    this.finishClassesWithNodesInsertedAtStart();
                    var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
                    for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
                        var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
                        changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext));
                    }
                    return changes;
                };
                ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
                    this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
                };
                return ChangeTracker;
            }());
            textChanges_3.ChangeTracker = ChangeTracker;
            // find first non-whitespace position in the leading trivia of the node
            function startPositionToDeleteNodeInList(sourceFile, node) {
                return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
            }
            function getClassOrObjectBraceEnds(cls, sourceFile) {
                return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end];
            }
            function getMembersOrProperties(cls) {
                return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members;
            }
            function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) {
                return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext);
            }
            textChanges_3.getNewFileText = getNewFileText;
            var changesToText;
            (function (changesToText) {
                function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
                    return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
                        var sourceFile = changesInFile[0].sourceFile;
                        // order changes by start position
                        // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
                        var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
                        var _loop_17 = function (i) {
                            ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
                                return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
                            });
                        };
                        // verify that change intervals do not overlap, except possibly at end points.
                        for (var i = 0; i < normalized.length - 1; i++) {
                            _loop_17(i);
                        }
                        var textChanges = normalized.map(function (c) {
                            return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
                        });
                        return { fileName: sourceFile.fileName, textChanges: textChanges };
                    });
                }
                changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
                function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) {
                    var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext);
                    return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true };
                }
                changesToText.newFileChanges = newFileChanges;
                function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
                    // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
                    var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
                    var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind);
                    var changes = ts.formatting.formatDocument(sourceFile, formatContext);
                    return applyChanges(nonFormattedText, changes);
                }
                changesToText.newFileChangesWorker = newFileChangesWorker;
                function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
                    if (change.kind === ChangeKind.Remove) {
                        return "";
                    }
                    if (change.kind === ChangeKind.Text) {
                        return change.text;
                    }
                    var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
                    var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
                    var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
                        ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217
                        : format(change.node);
                    // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
                    var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
                    return (options.prefix || "") + noIndent + (options.suffix || "");
                }
                /** Note: this may mutate `nodeIn`. */
                function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) {
                    var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta;
                    var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text;
                    if (validate)
                        validate(node, text);
                    var formatOptions = formatContext.options;
                    var initialIndentation = indentation !== undefined
                        ? indentation
                        : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos);
                    if (delta === undefined) {
                        delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatContext.options, nodeIn) ? (formatOptions.indentSize || 0) : 0;
                    }
                    var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
                    var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext);
                    return applyChanges(text, changes);
                }
                /** Note: output node may be mutated input node. */
                function getNonformattedText(node, sourceFile, newLineCharacter) {
                    var writer = new Writer(newLineCharacter);
                    var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
                    ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
                    return { text: writer.getText(), node: assignPositionsToNode(node) };
                }
            })(changesToText || (changesToText = {}));
            function applyChanges(text, changes) {
                for (var i = changes.length - 1; i >= 0; i--) {
                    var _a = changes[i], span = _a.span, newText = _a.newText;
                    text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span));
                }
                return text;
            }
            textChanges_3.applyChanges = applyChanges;
            function isTrivia(s) {
                return ts.skipTrivia(s, 0) === s.length;
            }
            function assignPositionsToNode(node) {
                var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217
                // create proxy node for non synthesized nodes
                var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited);
                newNode.pos = getPos(node);
                newNode.end = getEnd(node);
                return newNode;
            }
            function assignPositionsToNodeArray(nodes, visitor, test, start, count) {
                var visited = ts.visitNodes(nodes, visitor, test, start, count);
                if (!visited) {
                    return visited;
                }
                // clone nodearray if necessary
                var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited;
                nodeArray.pos = getPos(nodes);
                nodeArray.end = getEnd(nodes);
                return nodeArray;
            }
            var Writer = /** @class */ (function () {
                function Writer(newLine) {
                    var _this = this;
                    this.lastNonTriviaPosition = 0;
                    this.writer = ts.createTextWriter(newLine);
                    this.onEmitNode = function (hint, node, printCallback) {
                        if (node) {
                            setPos(node, _this.lastNonTriviaPosition);
                        }
                        printCallback(hint, node);
                        if (node) {
                            setEnd(node, _this.lastNonTriviaPosition);
                        }
                    };
                    this.onBeforeEmitNodeArray = function (nodes) {
                        if (nodes) {
                            setPos(nodes, _this.lastNonTriviaPosition);
                        }
                    };
                    this.onAfterEmitNodeArray = function (nodes) {
                        if (nodes) {
                            setEnd(nodes, _this.lastNonTriviaPosition);
                        }
                    };
                    this.onBeforeEmitToken = function (node) {
                        if (node) {
                            setPos(node, _this.lastNonTriviaPosition);
                        }
                    };
                    this.onAfterEmitToken = function (node) {
                        if (node) {
                            setEnd(node, _this.lastNonTriviaPosition);
                        }
                    };
                }
                Writer.prototype.setLastNonTriviaPosition = function (s, force) {
                    if (force || !isTrivia(s)) {
                        this.lastNonTriviaPosition = this.writer.getTextPos();
                        var i = 0;
                        while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) {
                            i++;
                        }
                        // trim trailing whitespaces
                        this.lastNonTriviaPosition -= i;
                    }
                };
                Writer.prototype.write = function (s) {
                    this.writer.write(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeKeyword = function (s) {
                    this.writer.writeKeyword(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeOperator = function (s) {
                    this.writer.writeOperator(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writePunctuation = function (s) {
                    this.writer.writePunctuation(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeParameter = function (s) {
                    this.writer.writeParameter(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeProperty = function (s) {
                    this.writer.writeProperty(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeSpace = function (s) {
                    this.writer.writeSpace(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeStringLiteral = function (s) {
                    this.writer.writeStringLiteral(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeSymbol = function (s, sym) {
                    this.writer.writeSymbol(s, sym);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeTextOfNode = function (text, node) {
                    this.writer.writeTextOfNode(text, node);
                };
                Writer.prototype.writeLine = function () {
                    this.writer.writeLine();
                };
                Writer.prototype.increaseIndent = function () {
                    this.writer.increaseIndent();
                };
                Writer.prototype.decreaseIndent = function () {
                    this.writer.decreaseIndent();
                };
                Writer.prototype.getText = function () {
                    return this.writer.getText();
                };
                Writer.prototype.rawWrite = function (s) {
                    this.writer.rawWrite(s);
                    this.setLastNonTriviaPosition(s, /*force*/ false);
                };
                Writer.prototype.writeLiteral = function (s) {
                    this.writer.writeLiteral(s);
                    this.setLastNonTriviaPosition(s, /*force*/ true);
                };
                Writer.prototype.getTextPos = function () {
                    return this.writer.getTextPos();
                };
                Writer.prototype.getLine = function () {
                    return this.writer.getLine();
                };
                Writer.prototype.getColumn = function () {
                    return this.writer.getColumn();
                };
                Writer.prototype.getIndent = function () {
                    return this.writer.getIndent();
                };
                Writer.prototype.isAtStartOfLine = function () {
                    return this.writer.isAtStartOfLine();
                };
                Writer.prototype.clear = function () {
                    this.writer.clear();
                    this.lastNonTriviaPosition = 0;
                };
                return Writer;
            }());
            function getInsertionPositionAtSourceFileTop(_a) {
                var text = _a.text;
                var shebang = ts.getShebang(text);
                var position = 0;
                if (shebang !== undefined) {
                    position = shebang.length;
                    advancePastLineBreak();
                }
                // For a source file, it is possible there are detached comments we should not skip
                var ranges = ts.getLeadingCommentRanges(text, position);
                if (!ranges)
                    return position;
                // However we should still skip a pinned comment at the top
                if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) {
                    position = ranges[0].end;
                    advancePastLineBreak();
                    ranges = ranges.slice(1);
                }
                // As well as any triple slash references
                for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) {
                    var range = ranges_1[_i];
                    if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) {
                        position = range.end;
                        advancePastLineBreak();
                        continue;
                    }
                    break;
                }
                return position;
                function advancePastLineBreak() {
                    if (position < text.length) {
                        var charCode = text.charCodeAt(position);
                        if (ts.isLineBreak(charCode)) {
                            position++;
                            if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) {
                                position++;
                            }
                        }
                    }
                }
            }
            function isValidLocationToAddComment(sourceFile, position) {
                return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position);
            }
            textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment;
            function needSemicolonBetween(a, b) {
                return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */
                    || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[`
            }
            var deleteDeclaration;
            (function (deleteDeclaration_1) {
                function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) {
                    switch (node.kind) {
                        case 149 /* Parameter */: {
                            var oldFunction = node.parent;
                            if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) {
                                // Lambdas with exactly one parameter are special because, after removal, there
                                // must be an empty parameter list (i.e. `()`) and this won't necessarily be the
                                // case if the parameter is simply removed (e.g. in `x => 1`).
                                var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, 
                                /*parameters*/ undefined, // TODO: GH#18217
                                oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body);
                                // Drop leading and trailing trivia of the new function because we're only going
                                // to replace the span (vs the full span) of the old function - the old leading
                                // and trailing trivia will remain.
                                ts.suppressLeadingAndTrailingTrivia(newFunction);
                                changes.replaceNode(sourceFile, oldFunction, newFunction);
                            }
                            else {
                                deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
                            }
                            break;
                        }
                        case 247 /* ImportDeclaration */:
                            deleteNode(changes, sourceFile, node, 
                            // For first import, leave header comment in place
                            node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
                            break;
                        case 184 /* BindingElement */:
                            var pattern = node.parent;
                            var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements);
                            if (preserveComma) {
                                deleteNode(changes, sourceFile, node);
                            }
                            else {
                                deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
                            }
                            break;
                        case 235 /* VariableDeclaration */:
                            deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node);
                            break;
                        case 148 /* TypeParameter */:
                            deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
                            break;
                        case 251 /* ImportSpecifier */:
                            var namedImports = node.parent;
                            if (namedImports.elements.length === 1) {
                                deleteImportBinding(changes, sourceFile, namedImports);
                            }
                            else {
                                deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
                            }
                            break;
                        case 249 /* NamespaceImport */:
                            deleteImportBinding(changes, sourceFile, node);
                            break;
                        default:
                            if (ts.isImportClause(node.parent) && node.parent.name === node) {
                                deleteDefaultImport(changes, sourceFile, node.parent);
                            }
                            else if (ts.isCallLikeExpression(node.parent)) {
                                deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
                            }
                            else {
                                deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
                            }
                    }
                }
                deleteDeclaration_1.deleteDeclaration = deleteDeclaration;
                function deleteDefaultImport(changes, sourceFile, importClause) {
                    if (!importClause.namedBindings) {
                        // Delete the whole import
                        deleteNode(changes, sourceFile, importClause.parent);
                    }
                    else {
                        // import |d,| * as ns from './file'
                        var start = importClause.name.getStart(sourceFile);
                        var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end);
                        if (nextToken && nextToken.kind === 26 /* CommaToken */) {
                            // shift first non-whitespace position after comma to the start position of the node
                            var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true);
                            changes.deleteRange(sourceFile, { pos: start, end: end });
                        }
                        else {
                            deleteNode(changes, sourceFile, importClause.name);
                        }
                    }
                }
                function deleteImportBinding(changes, sourceFile, node) {
                    if (node.parent.name) {
                        // Delete named imports while preserving the default import
                        // import d|, * as ns| from './file'
                        // import d|, { a }| from './file'
                        var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1));
                        changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
                    }
                    else {
                        // Delete the entire import declaration
                        // |import * as ns from './file'|
                        // |import { a } from './file'|
                        var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */);
                        deleteNode(changes, sourceFile, importDecl);
                    }
                }
                function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) {
                    var parent = node.parent;
                    if (parent.kind === 272 /* CatchClause */) {
                        // TODO: There's currently no unused diagnostic for this, could be a suggestion
                        changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile));
                        return;
                    }
                    if (parent.declarations.length !== 1) {
                        deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
                        return;
                    }
                    var gp = parent.parent;
                    switch (gp.kind) {
                        case 225 /* ForOfStatement */:
                        case 224 /* ForInStatement */:
                            changes.replaceNode(sourceFile, node, ts.createObjectLiteral());
                            break;
                        case 223 /* ForStatement */:
                            deleteNode(changes, sourceFile, parent);
                            break;
                        case 217 /* VariableStatement */:
                            deleteNode(changes, sourceFile, gp);
                            break;
                        default:
                            ts.Debug.assertNever(gp);
                    }
                }
            })(deleteDeclaration || (deleteDeclaration = {}));
            /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
            // Exported for tests only! (TODO: improve tests to not need this)
            function deleteNode(changes, sourceFile, node, options) {
                if (options === void 0) {
                    options = {};
                }
                var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
                var endPosition = getAdjustedEndPosition(sourceFile, node, options);
                changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
            }
            textChanges_3.deleteNode = deleteNode;
            function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) {
                var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile));
                var index = ts.indexOfNode(containingList, node);
                ts.Debug.assert(index !== -1);
                if (containingList.length === 1) {
                    deleteNode(changes, sourceFile, node);
                    return;
                }
                // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node.
                // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`.
                ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice");
                deletedNodesInLists.add(node);
                changes.deleteRange(sourceFile, {
                    pos: startPositionToDeleteNodeInList(sourceFile, node),
                    end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]),
                });
            }
        })(textChanges = ts.textChanges || (ts.textChanges = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var errorCodeToFixes = ts.createMultiMap();
            var fixIdToRegistration = ts.createMap();
            function diagnosticToString(diag) {
                return ts.isArray(diag)
                    ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1))
                    : ts.getLocaleSpecificMessage(diag);
            }
            function createCodeFixActionNoFixId(fixName, changes, description) {
                return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined);
            }
            codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId;
            function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) {
                return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command);
            }
            codefix.createCodeFixAction = createCodeFixAction;
            function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) {
                return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined };
            }
            function registerCodeFix(reg) {
                for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) {
                    var error = _a[_i];
                    errorCodeToFixes.add(String(error), reg);
                }
                if (reg.fixIds) {
                    for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) {
                        var fixId = _c[_b];
                        ts.Debug.assert(!fixIdToRegistration.has(fixId));
                        fixIdToRegistration.set(fixId, reg);
                    }
                }
            }
            codefix.registerCodeFix = registerCodeFix;
            function getSupportedErrorCodes() {
                return ts.arrayFrom(errorCodeToFixes.keys());
            }
            codefix.getSupportedErrorCodes = getSupportedErrorCodes;
            function getFixes(context) {
                return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); });
            }
            codefix.getFixes = getFixes;
            function getAllFixes(context) {
                // Currently fixId is always a string.
                return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context);
            }
            codefix.getAllFixes = getAllFixes;
            function createCombinedCodeActions(changes, commands) {
                return { changes: changes, commands: commands };
            }
            codefix.createCombinedCodeActions = createCombinedCodeActions;
            function createFileTextChanges(fileName, textChanges) {
                return { fileName: fileName, textChanges: textChanges };
            }
            codefix.createFileTextChanges = createFileTextChanges;
            function codeFixAll(context, errorCodes, use) {
                var commands = [];
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); });
                return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands);
            }
            codefix.codeFixAll = codeFixAll;
            function eachDiagnostic(_a, errorCodes, cb) {
                var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken;
                for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) {
                    var diag = _b[_i];
                    if (ts.contains(errorCodes, diag.code)) {
                        cb(diag);
                    }
                }
            }
            codefix.eachDiagnostic = eachDiagnostic;
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var refactor;
        (function (refactor_1) {
            // A map with the refactor code as key, the refactor itself as value
            // e.g.  nonSuggestableRefactors[refactorCode] -> the refactor you want
            var refactors = ts.createMap();
            /** @param name An unique code associated with each refactor. Does not have to be human-readable. */
            function registerRefactor(name, refactor) {
                refactors.set(name, refactor);
            }
            refactor_1.registerRefactor = registerRefactor;
            function getApplicableRefactors(context) {
                return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) {
                    return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context);
                }));
            }
            refactor_1.getApplicableRefactors = getApplicableRefactors;
            function getEditsForRefactor(context, refactorName, actionName) {
                var refactor = refactors.get(refactorName);
                return refactor && refactor.getEditsForAction(context, actionName);
            }
            refactor_1.getEditsForRefactor = getEditsForRefactor;
        })(refactor = ts.refactor || (ts.refactor = {}));
        function getRefactorContextSpan(_a) {
            var startPosition = _a.startPosition, endPosition = _a.endPosition;
            return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
        }
        ts.getRefactorContextSpan = getRefactorContextSpan;
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "addMissingInvocationForDecorator";
            var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
            });
            function makeChange(changeTracker, sourceFile, pos) {
                var token = ts.getTokenAtPosition(sourceFile, pos);
                var decorator = ts.findAncestor(token, ts.isDecorator);
                ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
                var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
                changeTracker.replaceNode(sourceFile, decorator.expression, replacement);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "annotateWithTypeFromJSDoc";
            var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var decl = getDeclaration(context.sourceFile, context.span.start);
                    if (!decl)
                        return;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var decl = getDeclaration(diag.file, diag.start);
                        if (decl)
                            doChange(changes, diag.file, decl);
                    });
                },
            });
            function getDeclaration(file, pos) {
                var name = ts.getTokenAtPosition(file, pos);
                // For an arrow function with no name, 'name' lands on the first parameter.
                return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
            }
            function parameterShouldGetTypeFromJSDoc(node) {
                return isDeclarationWithType(node) && hasUsableJSDoc(node);
            }
            codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
            function hasUsableJSDoc(decl) {
                return ts.isFunctionLikeDeclaration(decl)
                    ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
                    : !decl.type && !!ts.getJSDocType(decl);
            }
            function doChange(changes, sourceFile, decl) {
                if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
                    if (!decl.typeParameters) {
                        var typeParameters = ts.getJSDocTypeParameterDeclarations(decl);
                        if (typeParameters.length)
                            changes.insertTypeParameters(sourceFile, decl, typeParameters);
                    }
                    var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile);
                    if (needParens)
                        changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(19 /* OpenParenToken */));
                    for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) {
                        var param = _a[_i];
                        if (!param.type) {
                            var paramType = ts.getJSDocType(param);
                            if (paramType)
                                changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType));
                        }
                    }
                    if (needParens)
                        changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(20 /* CloseParenToken */));
                    if (!decl.type) {
                        var returnType = ts.getJSDocReturnType(decl);
                        if (returnType)
                            changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType));
                    }
                }
                else {
                    var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix
                    ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix.
                    changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType));
                }
            }
            function isDeclarationWithType(node) {
                return ts.isFunctionLikeDeclaration(node) ||
                    node.kind === 235 /* VariableDeclaration */ ||
                    node.kind === 151 /* PropertySignature */ ||
                    node.kind === 152 /* PropertyDeclaration */;
            }
            function transformJSDocType(node) {
                switch (node.kind) {
                    case 282 /* JSDocAllType */:
                    case 283 /* JSDocUnknownType */:
                        return ts.createTypeReferenceNode("any", ts.emptyArray);
                    case 286 /* JSDocOptionalType */:
                        return transformJSDocOptionalType(node);
                    case 285 /* JSDocNonNullableType */:
                        return transformJSDocType(node.type);
                    case 284 /* JSDocNullableType */:
                        return transformJSDocNullableType(node);
                    case 288 /* JSDocVariadicType */:
                        return transformJSDocVariadicType(node);
                    case 287 /* JSDocFunctionType */:
                        return transformJSDocFunctionType(node);
                    case 162 /* TypeReference */:
                        return transformJSDocTypeReference(node);
                    default:
                        var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217
                        ts.setEmitFlags(visited, 1 /* SingleLine */);
                        return visited;
                }
            }
            function transformJSDocOptionalType(node) {
                return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
            }
            function transformJSDocNullableType(node) {
                return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
            }
            function transformJSDocVariadicType(node) {
                return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
            }
            function transformJSDocFunctionType(node) {
                return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type);
            }
            function transformJSDocParameter(node) {
                var index = node.parent.parameters.indexOf(node);
                var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
                var name = node.name || (isRest ? "rest" : "arg" + index);
                var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
                return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
            }
            function transformJSDocTypeReference(node) {
                var name = node.typeName;
                var args = node.typeArguments;
                if (ts.isIdentifier(node.typeName)) {
                    if (ts.isJSDocIndexSignature(node)) {
                        return transformJSDocIndexSignature(node);
                    }
                    var text = node.typeName.text;
                    switch (node.typeName.text) {
                        case "String":
                        case "Boolean":
                        case "Object":
                        case "Number":
                            text = text.toLowerCase();
                            break;
                        case "array":
                        case "date":
                        case "promise":
                            text = text[0].toUpperCase() + text.slice(1);
                            break;
                    }
                    name = ts.createIdentifier(text);
                    if ((text === "Array" || text === "Promise") && !node.typeArguments) {
                        args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
                    }
                    else {
                        args = ts.visitNodes(node.typeArguments, transformJSDocType);
                    }
                }
                return ts.createTypeReferenceNode(name, args);
            }
            function transformJSDocIndexSignature(node) {
                var index = ts.createParameter(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, 
                /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "n" : "s", 
                /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 134 /* NumberKeyword */ ? "number" : "string", []), 
                /*initializer*/ undefined);
                var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
                ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
                return indexSignature;
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "convertFunctionToEs6Class";
            var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
            });
            function doChange(changes, sourceFile, position, checker) {
                var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position));
                if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
                    // Bad input
                    return undefined;
                }
                var ctorDeclaration = ctorSymbol.valueDeclaration;
                var precedingNode;
                var newClassDeclaration;
                switch (ctorDeclaration.kind) {
                    case 237 /* FunctionDeclaration */:
                        precedingNode = ctorDeclaration;
                        changes.delete(sourceFile, ctorDeclaration);
                        newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
                        break;
                    case 235 /* VariableDeclaration */:
                        precedingNode = ctorDeclaration.parent.parent;
                        newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
                        if (ctorDeclaration.parent.declarations.length === 1) {
                            ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
                            changes.delete(sourceFile, precedingNode);
                        }
                        else {
                            changes.delete(sourceFile, ctorDeclaration);
                        }
                        break;
                }
                if (!newClassDeclaration) {
                    return undefined;
                }
                ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
                // Because the preceding node could be touched, we need to insert nodes before delete nodes.
                changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
                function createClassElementsFromSymbol(symbol) {
                    var memberElements = [];
                    // all instance members are stored in the "member" array of symbol
                    if (symbol.members) {
                        symbol.members.forEach(function (member) {
                            var memberElement = createClassElement(member, /*modifiers*/ undefined);
                            if (memberElement) {
                                memberElements.push(memberElement);
                            }
                        });
                    }
                    // all static members are stored in the "exports" array of symbol
                    if (symbol.exports) {
                        symbol.exports.forEach(function (member) {
                            var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]);
                            if (memberElement) {
                                memberElements.push(memberElement);
                            }
                        });
                    }
                    return memberElements;
                    function shouldConvertDeclaration(_target, source) {
                        // Right now the only thing we can convert are function expressions - other values shouldn't get
                        // transformed. We can update this once ES public class properties are available.
                        return ts.isFunctionLike(source);
                    }
                    function createClassElement(symbol, modifiers) {
                        // Right now the only thing we can convert are function expressions, which are marked as methods
                        if (!(symbol.flags & 8192 /* Method */)) {
                            return;
                        }
                        var memberDeclaration = symbol.valueDeclaration;
                        var assignmentBinaryExpression = memberDeclaration.parent;
                        if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
                            return;
                        }
                        // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end
                        var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */
                            ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
                        changes.delete(sourceFile, nodeToDelete);
                        if (!assignmentBinaryExpression.right) {
                            return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, 
                            /*type*/ undefined, /*initializer*/ undefined);
                        }
                        switch (assignmentBinaryExpression.right.kind) {
                            case 194 /* FunctionExpression */: {
                                var functionExpression = assignmentBinaryExpression.right;
                                var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
                                var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, 
                                /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
                                ts.copyComments(assignmentBinaryExpression, method, sourceFile);
                                return method;
                            }
                            case 195 /* ArrowFunction */: {
                                var arrowFunction = assignmentBinaryExpression.right;
                                var arrowFunctionBody = arrowFunction.body;
                                var bodyBlock = void 0;
                                // case 1: () => { return [1,2,3] }
                                if (arrowFunctionBody.kind === 216 /* Block */) {
                                    bodyBlock = arrowFunctionBody;
                                }
                                // case 2: () => [1,2,3]
                                else {
                                    bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
                                }
                                var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */));
                                var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, 
                                /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
                                ts.copyComments(assignmentBinaryExpression, method, sourceFile);
                                return method;
                            }
                            default: {
                                // Don't try to declare members in JavaScript files
                                if (ts.isSourceFileJS(sourceFile)) {
                                    return;
                                }
                                var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, 
                                /*type*/ undefined, assignmentBinaryExpression.right);
                                ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
                                return prop;
                            }
                        }
                    }
                }
                function createClassFromVariableDeclaration(node) {
                    var initializer = node.initializer;
                    if (!initializer || initializer.kind !== 194 /* FunctionExpression */) {
                        return undefined;
                    }
                    if (node.name.kind !== 71 /* Identifier */) {
                        return undefined;
                    }
                    var memberElements = createClassElementsFromSymbol(node.symbol);
                    if (initializer.body) {
                        memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
                    }
                    var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */);
                    var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, 
                    /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
                    // Don't call copyComments here because we'll already leave them in place
                    return cls;
                }
                function createClassFromFunctionDeclaration(node) {
                    var memberElements = createClassElementsFromSymbol(ctorSymbol);
                    if (node.body) {
                        memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
                    }
                    var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */);
                    var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, 
                    /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
                    // Don't call copyComments here because we'll already leave them in place
                    return cls;
                }
            }
            function getModifierKindFromSource(source, kind) {
                return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "convertToAsyncFunction";
            var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code];
            var codeActionSucceeded = true;
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    codeActionSucceeded = true;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); });
                    return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : [];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); },
            });
            function convertToAsyncFunction(changes, sourceFile, position, checker, context) {
                // get the function declaration - returns a promise
                var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position);
                var functionToConvert;
                // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name
                if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) &&
                    tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) {
                    functionToConvert = tokenAtPosition.parent.initializer;
                }
                else {
                    functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration);
                }
                if (!functionToConvert) {
                    return;
                }
                var synthNamesMap = ts.createMap();
                var originalTypeMap = ts.createMap();
                var allVarNames = [];
                var isInJavascript = ts.isInJSFile(functionToConvert);
                var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
                var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames);
                var constIdentifiers = getConstIdentifiers(synthNamesMap);
                var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed);
                var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript };
                if (!returnStatements.length) {
                    return;
                }
                // add the async keyword
                changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert);
                function startTransformation(node, nodeToReplace) {
                    var newNodes = transformExpression(node, transformer, node);
                    changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
                }
                var _loop_18 = function (statement) {
                    ts.forEachChild(statement, function visit(node) {
                        if (ts.isCallExpression(node)) {
                            startTransformation(node, statement);
                        }
                        else if (!ts.isFunctionLike(node)) {
                            ts.forEachChild(node, visit);
                        }
                    });
                };
                for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
                    var statement = returnStatements_1[_i];
                    _loop_18(statement);
                }
            }
            // Returns the identifiers that are never reassigned in the refactor
            function getConstIdentifiers(synthNamesMap) {
                var constIdentifiers = [];
                synthNamesMap.forEach(function (val) {
                    if (val.numberOfAssignmentsOriginal === 0) {
                        constIdentifiers.push(val.identifier);
                    }
                });
                return constIdentifiers;
            }
            /*
                Finds all of the expressions of promise type that should not be saved in a variable during the refactor
            */
            function getAllPromiseExpressionsToReturn(func, checker) {
                if (!func.body) {
                    return ts.createMap();
                }
                var setOfExpressionsToReturn = ts.createMap();
                ts.forEachChild(func.body, function visit(node) {
                    if (isPromiseReturningExpression(node, checker, "then")) {
                        setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
                        ts.forEach(node.arguments, visit);
                    }
                    else if (isPromiseReturningExpression(node, checker, "catch")) {
                        setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
                        // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned
                        ts.forEachChild(node, visit);
                    }
                    else if (isPromiseReturningExpression(node, checker)) {
                        setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
                        // don't recurse here, since we won't refactor any children or arguments of the expression
                    }
                    else {
                        ts.forEachChild(node, visit);
                    }
                });
                return setOfExpressionsToReturn;
            }
            /*
                Returns true if node is a promise returning expression
                If name is not undefined, node is a promise returning call of name
            */
            function isPromiseReturningExpression(node, checker, name) {
                var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node);
                var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name));
                var nodeType = isExpressionOfName && checker.getTypeAtLocation(node);
                return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType));
            }
            function declaredInFile(symbol, sourceFile) {
                return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile;
            }
            /*
                Renaming of identifiers may be neccesary as the refactor changes scopes -
                This function collects all existing identifier names and names of identifiers that will be created in the refactor.
                It then checks for any collisions and renames them through getSynthesizedDeepClone
            */
            function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) {
                var identsToRenameMap = ts.createMap(); // key is the symbol id
                var collidingSymbolMap = ts.createMap();
                ts.forEachChild(nodeToRename, function visit(node) {
                    if (!ts.isIdentifier(node)) {
                        ts.forEachChild(node, visit);
                        return;
                    }
                    var symbol = checker.getSymbolAtLocation(node);
                    var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile);
                    if (symbol && isDefinedInFile) {
                        var type = checker.getTypeAtLocation(node);
                        var lastCallSignature = getLastCallSignature(type, checker);
                        var symbolIdString = ts.getSymbolId(symbol).toString();
                        // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg))
                        // Note - the choice of the last call signature is arbitrary
                        if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) {
                            var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters);
                            var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result");
                            var synthName = getNewNameIfConflict(ident, collidingSymbolMap);
                            synthNamesMap.set(symbolIdString, synthName);
                            allVarNames.push({ identifier: synthName.identifier, symbol: symbol });
                            addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol);
                        }
                        // we only care about identifiers that are parameters and declarations (don't care about other uses)
                        else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) {
                            var originalName = node.text;
                            var collidingSymbols = collidingSymbolMap.get(originalName);
                            // if the identifier name conflicts with a different identifier that we've already seen
                            if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) {
                                var newName = getNewNameIfConflict(node, collidingSymbolMap);
                                identsToRenameMap.set(symbolIdString, newName.identifier);
                                synthNamesMap.set(symbolIdString, newName);
                                allVarNames.push({ identifier: newName.identifier, symbol: symbol });
                                addNameToFrequencyMap(collidingSymbolMap, originalName, symbol);
                            }
                            else {
                                var identifier = ts.getSynthesizedDeepClone(node);
                                identsToRenameMap.set(symbolIdString, identifier);
                                synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ });
                                if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) {
                                    allVarNames.push({ identifier: identifier, symbol: symbol });
                                    addNameToFrequencyMap(collidingSymbolMap, originalName, symbol);
                                }
                            }
                        }
                    }
                });
                return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback);
                function isExpressionOrCallOnTypePromise(child) {
                    var node = child.parent;
                    if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) {
                        var nodeType = checker.getTypeAtLocation(node);
                        var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType);
                        return !!isPromise;
                    }
                    return false;
                }
                function deepCloneCallback(node, clone) {
                    if (ts.isIdentifier(node)) {
                        var symbol = checker.getSymbolAtLocation(node);
                        var symboldIdString = symbol && ts.getSymbolId(symbol).toString();
                        var renameInfo = symbol && synthNamesMap.get(symboldIdString);
                        if (renameInfo) {
                            var type = checker.getTypeAtLocation(node);
                            originalType.set(ts.getNodeId(clone).toString(), type);
                        }
                    }
                    var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString());
                    if (val !== undefined) {
                        setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString());
                        setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val);
                    }
                }
            }
            function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) {
                if (renamedVarNameFrequencyMap.has(originalName)) {
                    renamedVarNameFrequencyMap.get(originalName).push(symbol);
                }
                else {
                    renamedVarNameFrequencyMap.set(originalName, [symbol]);
                }
            }
            function getNewNameIfConflict(name, originalNames) {
                var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length;
                var numberOfAssignmentsOriginal = 0;
                var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName);
                return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal };
            }
            // dispatch function to recursively build the refactoring
            // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts
            function transformExpression(node, transformer, outermostParent, prevArgName) {
                if (!node) {
                    return ts.emptyArray;
                }
                var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString());
                var nodeType = originalType || transformer.checker.getTypeAtLocation(node);
                if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) {
                    return transformThen(node, transformer, outermostParent, prevArgName);
                }
                else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) {
                    return transformCatch(node, transformer, prevArgName);
                }
                else if (ts.isPropertyAccessExpression(node)) {
                    return transformExpression(node.expression, transformer, outermostParent, prevArgName);
                }
                else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) {
                    return transformPromiseCall(node, transformer, prevArgName);
                }
                codeActionSucceeded = false;
                return ts.emptyArray;
            }
            function transformCatch(node, transformer, prevArgName) {
                var func = node.arguments[0];
                var argName = getArgName(func, transformer);
                var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString());
                /*
                    If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block)
                    To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap
                    We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step
                */
                if (prevArgName && !shouldReturn) {
                    prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block
                    transformer.synthNamesMap.forEach(function (val, key) {
                        if (val.identifier.text === prevArgName.identifier.text) {
                            var newSynthName = createUniqueSynthName(prevArgName);
                            transformer.synthNamesMap.set(key, newSynthName);
                        }
                    });
                    // update the constIdentifiers list
                    if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) {
                        transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier);
                    }
                }
                var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName));
                var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer);
                var catchArg = argName ? argName.identifier.text : "e";
                var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody));
                /*
                    In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block)
                */
                var varDeclList;
                if (prevArgName && !shouldReturn) {
                    var typeArray = prevArgName.types;
                    var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */);
                    var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType);
                    var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)];
                    varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */));
                }
                var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined);
                return varDeclList ? [varDeclList, tryStatement] : [tryStatement];
            }
            function createUniqueSynthName(prevArgName) {
                var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text);
                var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 };
                return newSynthName;
            }
            function transformThen(node, transformer, outermostParent, prevArgName) {
                var _a = node.arguments, res = _a[0], rej = _a[1];
                if (!res) {
                    return transformExpression(node.expression, transformer, outermostParent);
                }
                var argNameRes = getArgName(res, transformer);
                var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer);
                if (rej) {
                    var argNameRej = getArgName(rej, transformer);
                    var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody));
                    var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer);
                    var catchArg = argNameRej ? argNameRej.identifier.text : "e";
                    var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2));
                    return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)];
                }
                return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody);
            }
            function getFlagOfIdentifier(node, constIdentifiers) {
                var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; });
                return inArr ? 2 /* Const */ : 1 /* Let */;
            }
            function transformPromiseCall(node, transformer, prevArgName) {
                var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString());
                // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call
                var originalNodeParent = node.original ? node.original.parent : node.parent;
                if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) {
                    return createTransformedStatement(prevArgName, ts.createAwait(node), transformer);
                }
                else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) {
                    return [ts.createStatement(ts.createAwait(node))];
                }
                return [ts.createReturn(ts.getSynthesizedDeepClone(node))];
            }
            function createTransformedStatement(prevArgName, rightHandSide, transformer) {
                if (!prevArgName || prevArgName.identifier.text.length === 0) {
                    // if there's no argName to assign to, there still might be side effects
                    return [ts.createStatement(rightHandSide)];
                }
                if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) {
                    // if the variable has already been declared, we don't need "let" or "const"
                    return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))];
                }
                return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))];
            }
            // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts
            function getTransformationBody(func, prevArgName, argName, parent, transformer) {
                var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString());
                switch (func.kind) {
                    case 95 /* NullKeyword */:
                        // do not produce a transformed statement for a null argument
                        break;
                    case 71 /* Identifier */: // identifier includes undefined
                        if (!argName) {
                            // undefined was argument passed to promise handler
                            break;
                        }
                        var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, argName ? [argName.identifier] : ts.emptyArray);
                        if (shouldReturn) {
                            return [ts.createReturn(synthCall)];
                        }
                        var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func);
                        var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */);
                        if (!callSignatures.length) {
                            // if identifier in handler has no call signatures, it's invalid
                            codeActionSucceeded = false;
                            break;
                        }
                        var returnType = callSignatures[0].getReturnType();
                        var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer);
                        if (prevArgName) {
                            prevArgName.types.push(returnType);
                        }
                        return varDeclOrAssignment;
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */: {
                        var funcBody = func.body;
                        // Arrow functions with block bodies { } will enter this control flow
                        if (ts.isBlock(funcBody)) {
                            var refactoredStmts = [];
                            var seenReturnStatement = false;
                            for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) {
                                var statement = _a[_i];
                                if (ts.isReturnStatement(statement)) {
                                    seenReturnStatement = true;
                                }
                                if (ts.getReturnStatementsWithPromiseHandlers(statement).length) {
                                    refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName));
                                }
                                else {
                                    refactoredStmts.push(statement);
                                }
                            }
                            return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) :
                                removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement);
                        }
                        else {
                            var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody));
                            var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName);
                            if (innerCbBody.length > 0) {
                                return innerCbBody;
                            }
                            if (!shouldReturn) {
                                var type_6 = transformer.checker.getTypeAtLocation(func);
                                var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType();
                                var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
                                var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
                                var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer);
                                if (prevArgName) {
                                    prevArgName.types.push(returnType_1);
                                }
                                return transformedStatement;
                            }
                            else {
                                return [ts.createReturn(ts.getSynthesizedDeepClone(funcBody))];
                            }
                        }
                    }
                    default:
                        // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code.
                        codeActionSucceeded = false;
                        break;
                }
                return ts.emptyArray;
            }
            function getLastCallSignature(type, checker) {
                var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */);
                return ts.lastOrUndefined(callSignatures);
            }
            function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) {
                var ret = [];
                for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) {
                    var stmt = stmts_1[_i];
                    if (ts.isReturnStatement(stmt)) {
                        if (stmt.expression) {
                            var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression;
                            if (prevArgName === undefined) {
                                ret.push(ts.createExpressionStatement(possiblyAwaitedExpression));
                            }
                            else {
                                ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers)))));
                            }
                        }
                    }
                    else {
                        ret.push(ts.getSynthesizedDeepClone(stmt));
                    }
                }
                // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables
                if (!seenReturnStatement && prevArgName !== undefined) {
                    ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers)))));
                }
                return ret;
            }
            function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) {
                var innerCbBody = [];
                for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) {
                    var stmt = innerRetStmts_1[_i];
                    ts.forEachChild(stmt, function visit(node) {
                        if (ts.isCallExpression(node)) {
                            var temp = transformExpression(node, transformer, node, prevArgName);
                            innerCbBody = innerCbBody.concat(temp);
                            if (innerCbBody.length > 0) {
                                return;
                            }
                        }
                        else if (!ts.isFunctionLike(node)) {
                            ts.forEachChild(node, visit);
                        }
                    });
                }
                return innerCbBody;
            }
            function getArgName(funcNode, transformer) {
                var numberOfAssignmentsOriginal = 0;
                var types = [];
                var name;
                if (ts.isFunctionLikeDeclaration(funcNode)) {
                    if (funcNode.parameters.length > 0) {
                        var param = funcNode.parameters[0].name;
                        name = getMapEntryOrDefault(param);
                    }
                }
                else if (ts.isIdentifier(funcNode)) {
                    name = getMapEntryOrDefault(funcNode);
                }
                // return undefined argName when arg is null or undefined
                if (!name || name.identifier.text === "undefined") {
                    return undefined;
                }
                return name;
                function getMapEntryOrDefault(identifier) {
                    var originalNode = getOriginalNode(identifier);
                    var symbol = getSymbol(originalNode);
                    if (!symbol) {
                        return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal };
                    }
                    var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString());
                    return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal };
                }
                function getSymbol(node) {
                    return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node);
                }
                function getOriginalNode(node) {
                    return node.original ? node.original : node;
                }
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            codefix.registerCodeFix({
                errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
                        var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences));
                        if (moduleExportsChangedToDefault) {
                            for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
                                var importingFile = _a[_i];
                                fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences));
                            }
                        }
                    });
                    // No support for fix-all since this applies to the whole file at once anyway.
                    return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)];
                },
            });
            function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) {
                for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
                    var moduleSpecifier = _a[_i];
                    var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
                    if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
                        continue;
                    }
                    var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
                    switch (importNode.kind) {
                        case 246 /* ImportEqualsDeclaration */:
                            changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference));
                            break;
                        case 189 /* CallExpression */:
                            if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
                                changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default"));
                            }
                            break;
                    }
                }
            }
            /** @returns Whether we converted a `module.exports =` to a default export. */
            function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) {
                var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
                var exports = collectExportRenames(sourceFile, checker, identifiers);
                convertExportsAccesses(sourceFile, exports, changes);
                var moduleExportsChangedToDefault = false;
                for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
                    var statement = _a[_i];
                    var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference);
                    moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
                }
                return moduleExportsChangedToDefault;
            }
            function collectExportRenames(sourceFile, checker, identifiers) {
                var res = ts.createMap();
                forEachExportReference(sourceFile, function (node) {
                    var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
                    if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
                        || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) {
                        // Unconditionally add an underscore in case `text` is a keyword.
                        res.set(text, makeUniqueName("_" + text, identifiers));
                    }
                });
                return res;
            }
            function convertExportsAccesses(sourceFile, exports, changes) {
                forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
                    if (isAssignmentLhs) {
                        return;
                    }
                    var text = node.name.text;
                    changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
                });
            }
            function forEachExportReference(sourceFile, cb) {
                sourceFile.forEachChild(function recur(node) {
                    if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
                        var parent = node.parent;
                        cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
                    }
                    node.forEachChild(recur);
                });
            }
            function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) {
                switch (statement.kind) {
                    case 217 /* VariableStatement */:
                        convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
                        return false;
                    case 219 /* ExpressionStatement */: {
                        var expression = statement.expression;
                        switch (expression.kind) {
                            case 189 /* CallExpression */: {
                                if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
                                    // For side-effecting require() call, just make a side-effecting import.
                                    changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference));
                                }
                                return false;
                            }
                            case 202 /* BinaryExpression */: {
                                var operatorToken = expression.operatorToken;
                                return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports);
                            }
                        }
                    }
                    // falls through
                    default:
                        return false;
                }
            }
            function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) {
                var declarationList = statement.declarationList;
                var foundImport = false;
                var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
                    var name = decl.name, initializer = decl.initializer;
                    if (initializer) {
                        if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
                            // `const alias = module.exports;` can be removed.
                            foundImport = true;
                            return [];
                        }
                        else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
                            foundImport = true;
                            return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference);
                        }
                        else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) {
                            foundImport = true;
                            return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference);
                        }
                    }
                    // Move it out to its own variable statement. (This will not be used if `!foundImport`)
                    return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
                });
                if (foundImport) {
                    // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
                    changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
                }
            }
            /** Converts `const name = require("moduleSpecifier").propertyName` */
            function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) {
                switch (name.kind) {
                    case 182 /* ObjectBindingPattern */:
                    case 183 /* ArrayBindingPattern */: {
                        // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
                        var tmp = makeUniqueName(propertyName, identifiers);
                        return [
                            makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference),
                            makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
                        ];
                    }
                    case 71 /* Identifier */:
                        // `const a = require("b").c` --> `import { c as a } from "./b";
                        return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)];
                    default:
                        return ts.Debug.assertNever(name);
                }
            }
            function convertAssignment(sourceFile, checker, assignment, changes, exports) {
                var left = assignment.left, right = assignment.right;
                if (!ts.isPropertyAccessExpression(left)) {
                    return false;
                }
                if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
                    if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
                        // `const alias = module.exports;` or `module.exports = alias;` can be removed.
                        changes.delete(sourceFile, assignment.parent);
                    }
                    else {
                        var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
                            : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
                                : undefined;
                        if (replacement) {
                            changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
                            return replacement[1];
                        }
                        else {
                            changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default");
                            return true;
                        }
                    }
                }
                else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
                    convertNamedExport(sourceFile, assignment, changes, exports);
                }
                return false;
            }
            /**
             * Convert `module.exports = { ... }` to individual exports..
             * We can't always do this if the module has interesting members -- then it will be a default export instead.
             */
            function tryChangeModuleExportsObject(object) {
                var statements = ts.mapAllOrFail(object.properties, function (prop) {
                    switch (prop.kind) {
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                        // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
                        case 274 /* ShorthandPropertyAssignment */:
                        case 275 /* SpreadAssignment */:
                            return undefined;
                        case 273 /* PropertyAssignment */:
                            return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer);
                        case 154 /* MethodDeclaration */:
                            return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
                        default:
                            ts.Debug.assertNever(prop);
                    }
                });
                return statements && [statements, false];
            }
            function convertNamedExport(sourceFile, assignment, changes, exports) {
                // If "originalKeywordKind" was set, this is e.g. `exports.
                var text = assignment.left.name.text;
                var rename = exports.get(text);
                if (rename !== undefined) {
                    /*
                    const _class = 0;
                    export { _class as class };
                    */
                    var newNodes = [
                        makeConst(/*modifiers*/ undefined, rename, assignment.right),
                        makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
                    ];
                    changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
                }
                else {
                    convertExportsPropertyAssignment(assignment, sourceFile, changes);
                }
            }
            function convertReExportAll(reExported, checker) {
                // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
                var moduleSpecifier = reExported.text;
                var moduleSymbol = checker.getSymbolAtLocation(reExported);
                var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
                return exports.has("export=")
                    ? [[reExportDefault(moduleSpecifier)], true]
                    : !exports.has("default")
                        ? [[reExportStar(moduleSpecifier)], false]
                        // If there's some non-default export, must include both `export *` and `export default`.
                        : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
            }
            function reExportStar(moduleSpecifier) {
                return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
            }
            function reExportDefault(moduleSpecifier) {
                return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
            }
            function convertExportsPropertyAssignment(_a, sourceFile, changes) {
                var left = _a.left, right = _a.right, parent = _a.parent;
                var name = left.name.text;
                if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) {
                    // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`.
                    changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(84 /* ExportKeyword */), { suffix: " " });
                    if (!right.name)
                        changes.insertName(sourceFile, right, name);
                    var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile);
                    if (semi)
                        changes.delete(sourceFile, semi);
                }
                else {
                    // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const `
                    changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 23 /* DotToken */, sourceFile), [ts.createToken(84 /* ExportKeyword */), ts.createToken(76 /* ConstKeyword */)], { joiner: " ", suffix: " " });
                }
            }
            // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node.
            function convertExportsDotXEquals_replaceNode(name, exported) {
                var modifiers = [ts.createToken(84 /* ExportKeyword */)];
                switch (exported.kind) {
                    case 194 /* FunctionExpression */: {
                        var expressionName = exported.name;
                        if (expressionName && expressionName.text !== name) {
                            // `exports.f = function g() {}` -> `export const f = function g() {}`
                            return exportConst();
                        }
                    }
                    // falls through
                    case 195 /* ArrowFunction */:
                        // `exports.f = function() {}` --> `export function f() {}`
                        return functionExpressionToDeclaration(name, modifiers, exported);
                    case 207 /* ClassExpression */:
                        // `exports.C = class {}` --> `export class C {}`
                        return classExpressionToDeclaration(name, modifiers, exported);
                    default:
                        return exportConst();
                }
                function exportConst() {
                    // `exports.x = 0;` --> `export const x = 0;`
                    return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217
                }
            }
            /**
             * Converts `const <<name>> = require("x");`.
             * Returns nodes that will replace the variable declaration for the commonjs import.
             * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
             */
            function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) {
                switch (name.kind) {
                    case 182 /* ObjectBindingPattern */: {
                        var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) {
                            return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name)
                                ? undefined
                                : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
                        }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217)
                        if (importSpecifiers) {
                            return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)];
                        }
                    }
                    // falls through -- object destructuring has an interesting pattern and must be a variable declaration
                    case 183 /* ArrayBindingPattern */: {
                        /*
                        import x from "x";
                        const [a, b, c] = x;
                        */
                        var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
                        return [
                            ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference),
                            makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
                        ];
                    }
                    case 71 /* Identifier */:
                        return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference);
                    default:
                        return ts.Debug.assertNever(name);
                }
            }
            /**
             * Convert `import x = require("x").`
             * Also converts uses like `x.y()` to `y()` and uses a named import.
             */
            function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) {
                var nameSymbol = checker.getSymbolAtLocation(name);
                // Maps from module property name to name actually used. (The same if there isn't shadowing.)
                var namedBindingsNames = ts.createMap();
                // True if there is some non-property use like `x()` or `f(x)`.
                var needDefaultImport = false;
                for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
                    var use = _a[_i];
                    if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
                        // This was a use of a different symbol with the same name, due to shadowing. Ignore.
                        continue;
                    }
                    var parent = use.parent;
                    if (ts.isPropertyAccessExpression(parent)) {
                        var expression = parent.expression, propertyName = parent.name.text;
                        ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers`
                        var idName = namedBindingsNames.get(propertyName);
                        if (idName === undefined) {
                            idName = makeUniqueName(propertyName, identifiers);
                            namedBindingsNames.set(propertyName, idName);
                        }
                        changes.replaceNode(file, parent, ts.createIdentifier(idName));
                    }
                    else {
                        needDefaultImport = true;
                    }
                }
                var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
                    var propertyName = _a[0], idName = _a[1];
                    return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
                }));
                if (!namedBindings) {
                    // If it was unused, ensure that we at least import *something*.
                    needDefaultImport = true;
                }
                return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)];
            }
            // Identifiers helpers
            function makeUniqueName(name, identifiers) {
                while (identifiers.original.has(name) || identifiers.additional.has(name)) {
                    name = "_" + name;
                }
                identifiers.additional.set(name, true);
                return name;
            }
            function collectFreeIdentifiers(file) {
                var map = ts.createMultiMap();
                forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); });
                return map;
            }
            /**
             * A free identifier is an identifier that can be accessed through name lookup as a local variable.
             * In the expression `x.y`, `x` is a free identifier, but `y` is not.
             */
            function forEachFreeIdentifier(node, cb) {
                if (ts.isIdentifier(node) && isFreeIdentifier(node))
                    cb(node);
                node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); });
            }
            function isFreeIdentifier(node) {
                var parent = node.parent;
                switch (parent.kind) {
                    case 187 /* PropertyAccessExpression */:
                        return parent.name !== node;
                    case 184 /* BindingElement */:
                        return parent.propertyName !== node;
                    case 251 /* ImportSpecifier */:
                        return parent.propertyName !== node;
                    default:
                        return true;
                }
            }
            // Node helpers
            function functionExpressionToDeclaration(name, additionalModifiers, fn) {
                return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
                ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body)));
            }
            function classExpressionToDeclaration(name, additionalModifiers, cls) {
                return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
                ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
            }
            function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) {
                return propertyName === "default"
                    ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference)
                    : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference);
            }
            function makeImportSpecifier(propertyName, name) {
                return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
            }
            function makeConst(modifiers, name, init) {
                return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
            }
            function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
                return ts.createExportDeclaration(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "correctQualifiedNameToIndexedAccessType";
            var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var qualifiedName = getQualifiedName(context.sourceFile, context.span.start);
                    if (!qualifiedName)
                        return undefined;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); });
                    var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]";
                    return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var q = getQualifiedName(diag.file, diag.start);
                        if (q) {
                            doChange(changes, diag.file, q);
                        }
                    });
                },
            });
            function getQualifiedName(sourceFile, pos) {
                var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName);
                ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name.");
                return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined;
            }
            function doChange(changeTracker, sourceFile, qualifiedName) {
                var rightText = qualifiedName.right.text;
                var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText)));
                changeTracker.replaceNode(sourceFile, qualifiedName, replacement);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code,
                ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code];
            var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember?
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var program = context.program, sourceFile = context.sourceFile, span = context.span;
                    var classDeclaration = getClass(sourceFile, span.start);
                    var checker = program.getTypeChecker();
                    return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) {
                        var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); });
                        return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces);
                    });
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    var seenClassDeclarations = ts.createMap();
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var classDeclaration = getClass(diag.file, diag.start);
                        if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
                            for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) {
                                var implementedTypeNode = _a[_i];
                                addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences);
                            }
                        }
                    });
                },
            });
            function getClass(sourceFile, pos) {
                return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos)));
            }
            function symbolPointsToNonPrivateMember(symbol) {
                return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */);
            }
            function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) {
                var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker);
                // Note that this is ultimately derived from a map indexed by symbol names,
                // so duplicates cannot occur.
                var implementedType = checker.getTypeAtLocation(implementedTypeNode);
                var implementedTypeSymbols = checker.getPropertiesOfType(implementedType);
                var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); }));
                var classType = checker.getTypeAtLocation(classDeclaration);
                if (!classType.getNumberIndexType()) {
                    createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */);
                }
                if (!classType.getStringIndexType()) {
                    createMissingIndexSignatureDeclaration(implementedType, 0 /* String */);
                }
                codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); });
                function createMissingIndexSignatureDeclaration(type, kind) {
                    var indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
                    if (indexInfoOfKind) {
                        changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration));
                    }
                }
            }
            function getHeritageClauseSymbolTable(classDeclaration, checker) {
                var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration);
                if (!heritageClauseNode)
                    return ts.createSymbolTable();
                var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode);
                var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType);
                return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember));
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            codefix.importFixId = "fixMissingImport";
            var errorCodes = [
                ts.Diagnostics.Cannot_find_name_0.code,
                ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
                ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
                ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
                ts.Diagnostics.Cannot_find_namespace_0.code,
                ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
                ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
            ];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span;
                    var info = getFixesInfo(context, errorCode, span.start);
                    if (!info)
                        return undefined;
                    var fixes = info.fixes, symbolName = info.symbolName;
                    var quotePreference = ts.getQuotePreference(sourceFile, preferences);
                    return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); });
                },
                fixIds: [codefix.importFixId],
                getAllCodeActions: function (context) {
                    var sourceFile = context.sourceFile, preferences = context.preferences;
                    // Namespace fixes don't conflict, so just build a list.
                    var addToNamespace = [];
                    var importType = [];
                    // Keys are import clause node IDs.
                    var addToExisting = ts.createMap();
                    // Keys are module specifiers.
                    var newImports = ts.createMap();
                    codefix.eachDiagnostic(context, errorCodes, function (diag) {
                        var info = getFixesInfo(context, diag.code, diag.start);
                        if (!info || !info.fixes.length)
                            return;
                        var fixes = info.fixes, symbolName = info.symbolName;
                        var fix = ts.first(fixes);
                        switch (fix.kind) {
                            case 0 /* UseNamespace */:
                                addToNamespace.push(fix);
                                break;
                            case 1 /* ImportType */:
                                importType.push(fix);
                                break;
                            case 2 /* AddToExisting */: {
                                var importClause = fix.importClause, importKind = fix.importKind;
                                var key = String(ts.getNodeId(importClause));
                                var entry = addToExisting.get(key);
                                if (!entry) {
                                    addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] });
                                }
                                if (importKind === 0 /* Named */) {
                                    ts.pushIfUnique(entry.namedImports, symbolName);
                                }
                                else {
                                    ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName);
                                    entry.defaultImport = symbolName;
                                }
                                break;
                            }
                            case 3 /* AddNew */: {
                                var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind;
                                var entry = newImports.get(moduleSpecifier);
                                if (!entry) {
                                    newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined });
                                }
                                switch (importKind) {
                                    case 1 /* Default */:
                                        ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName);
                                        entry.defaultImport = symbolName;
                                        break;
                                    case 0 /* Named */:
                                        ts.pushIfUnique(entry.namedImports, symbolName);
                                        break;
                                    case 3 /* Equals */:
                                    case 2 /* Namespace */:
                                        ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName);
                                        entry.namespaceLikeImport = { importKind: importKind, name: symbolName };
                                        break;
                                }
                                break;
                            }
                            default:
                                ts.Debug.assertNever(fix);
                        }
                    });
                    return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
                        var quotePreference = ts.getQuotePreference(sourceFile, preferences);
                        for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) {
                            var fix = addToNamespace_1[_i];
                            addNamespaceQualifier(changes, sourceFile, fix);
                        }
                        for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) {
                            var fix = importType_1[_a];
                            addImportType(changes, sourceFile, fix, quotePreference);
                        }
                        addToExisting.forEach(function (_a) {
                            var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports;
                            doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports);
                        });
                        newImports.forEach(function (imports, moduleSpecifier) {
                            addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports);
                        });
                    }));
                },
            });
            // Sorted with the preferred fix coming first.
            var ImportFixKind;
            (function (ImportFixKind) {
                ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace";
                ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType";
                ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting";
                ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew";
            })(ImportFixKind || (ImportFixKind = {}));
            var ImportKind;
            (function (ImportKind) {
                ImportKind[ImportKind["Named"] = 0] = "Named";
                ImportKind[ImportKind["Default"] = 1] = "Default";
                ImportKind[ImportKind["Namespace"] = 2] = "Namespace";
                ImportKind[ImportKind["Equals"] = 3] = "Equals";
            })(ImportKind || (ImportKind = {}));
            function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) {
                var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles());
                ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }));
                // We sort the best codefixes first, so taking `first` is best for completions.
                var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier;
                var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences));
                return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) };
            }
            codefix.getImportCompletionAction = getImportCompletionAction;
            function codeFixActionToCodeAction(_a) {
                var description = _a.description, changes = _a.changes, commands = _a.commands;
                return { description: description, changes: changes, commands: commands };
            }
            function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) {
                var result = [];
                forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) {
                    // Don't import from a re-export when looking "up" like to `./index` or `../index`.
                    if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) {
                        return;
                    }
                    var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions);
                    if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) {
                        result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) });
                    }
                    for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) {
                        var exported = _a[_i];
                        if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) {
                            result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) });
                        }
                    }
                });
                return result;
            }
            function isTypeOnlySymbol(s, checker) {
                return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */);
            }
            function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) {
                var checker = program.getTypeChecker();
                var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); });
                var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker);
                var addToExisting = tryAddToExistingImport(existingImports);
                // Don't bother providing an action to add a new import if we can add to an existing one.
                var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences);
                return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport);
            }
            function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) {
                // It is possible that multiple import statements with the same specifier exist in the file.
                // e.g.
                //
                //     import * as ns from "foo";
                //     import { member1, member2 } from "foo";
                //
                //     member3/**/ <-- cusor here
                //
                // in this case we should provie 2 actions:
                //     1. change "member3" to "ns.member3"
                //     2. add "member3" to the second import statement's import list
                // and it is up to the user to decide which one fits best.
                return ts.firstDefined(existingImports, function (_a) {
                    var declaration = _a.declaration;
                    var namespace = getNamespaceImportName(declaration);
                    if (namespace) {
                        var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace));
                        if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) {
                            return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position };
                        }
                    }
                });
            }
            function tryAddToExistingImport(existingImports) {
                return ts.firstDefined(existingImports, function (_a) {
                    var declaration = _a.declaration, importKind = _a.importKind;
                    if (declaration.kind !== 247 /* ImportDeclaration */)
                        return undefined;
                    var importClause = declaration.importClause;
                    if (!importClause)
                        return undefined;
                    var name = importClause.name, namedBindings = importClause.namedBindings;
                    return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */)
                        ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind }
                        : undefined;
                });
            }
            function getNamespaceImportName(declaration) {
                if (declaration.kind === 247 /* ImportDeclaration */) {
                    var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings;
                    return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined;
                }
                else {
                    return declaration.name;
                }
            }
            function getExistingImportDeclarations(_a, checker, sourceFile) {
                var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
                // Can't use an es6 import for a type in JS.
                return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) {
                    var i = ts.importFromModuleSpecifier(moduleSpecifier);
                    return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */)
                        && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined;
                });
            }
            function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) {
                var isJs = ts.isSourceFileJS(sourceFile);
                var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
                    var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
                    return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap)
                        .map(function (moduleSpecifier) {
                        // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
                        return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind };
                    });
                });
                // Sort to keep the shortest paths first
                return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; });
            }
            function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) {
                var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier);
                return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences);
            }
            function newImportInfoFromExistingSpecifier(_a) {
                var declaration = _a.declaration, importKind = _a.importKind;
                var expression = declaration.kind === 247 /* ImportDeclaration */
                    ? declaration.moduleSpecifier
                    : declaration.moduleReference.kind === 257 /* ExternalModuleReference */
                        ? declaration.moduleReference.expression
                        : undefined;
                return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined;
            }
            function getFixesInfo(context, errorCode, pos) {
                var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos);
                var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
                    ? getFixesInfoForUMDImport(context, symbolToken)
                    : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined;
                return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) });
            }
            function getFixesInfoForUMDImport(_a, token) {
                var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences;
                var checker = program.getTypeChecker();
                var umdSymbol = getUmdSymbol(token, checker);
                if (!umdSymbol)
                    return undefined;
                var symbol = checker.getAliasedSymbol(umdSymbol);
                var symbolName = umdSymbol.name;
                var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }];
                var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences);
                return { fixes: fixes, symbolName: symbolName };
            }
            function getUmdSymbol(token, checker) {
                // try the identifier to see if it is the umd symbol
                var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined;
                if (ts.isUMDExportSymbol(umdSymbol))
                    return umdSymbol;
                // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
                var parent = token.parent;
                return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent)
                    ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol)
                    : undefined;
            }
            function getUmdImportKind(compilerOptions) {
                // Import a synthetic `default` if enabled.
                if (ts.getAllowSyntheticDefaultImports(compilerOptions)) {
                    return 1 /* Default */;
                }
                // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it.
                var moduleKind = ts.getEmitModuleKind(compilerOptions);
                switch (moduleKind) {
                    case ts.ModuleKind.AMD:
                    case ts.ModuleKind.CommonJS:
                    case ts.ModuleKind.UMD:
                        return 3 /* Equals */;
                    case ts.ModuleKind.System:
                    case ts.ModuleKind.ES2015:
                    case ts.ModuleKind.ESNext:
                    case ts.ModuleKind.None:
                        // Fall back to the `import * as ns` style import.
                        return 2 /* Namespace */;
                    default:
                        return ts.Debug.assertNever(moduleKind);
                }
            }
            function getFixesInfoForNonUMDImport(_a, symbolToken) {
                var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences;
                var checker = program.getTypeChecker();
                // If we're at `<Foo/>`, we must check if `Foo` is already in scope, and if so, get an import for `React` instead.
                var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent)
                    && symbolToken.parent.tagName === symbolToken
                    && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false))
                    ? checker.getJsxNamespace()
                    : symbolToken.text;
                // "default" is a keyword and not a legal identifier for the import, so we don't expect it here
                ts.Debug.assert(symbolName !== "default" /* Default */);
                var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) {
                    var _ = _a[0], exportInfos = _a[1];
                    return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences);
                }));
                return { fixes: fixes, symbolName: symbolName };
            }
            // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported.
            function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) {
                // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once.
                // Maps symbol id to info for modules providing that symbol (original export + re-exports).
                var originalSymbolToExportInfos = ts.createMultiMap();
                function addSymbol(moduleSymbol, exportedSymbol, importKind) {
                    originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) });
                }
                forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) {
                    cancellationToken.throwIfCancellationRequested();
                    var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions());
                    if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) {
                        addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind);
                    }
                    // check exports with the same name
                    var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol);
                    if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
                        addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */);
                    }
                });
                return originalSymbolToExportInfos;
            }
            function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) {
                var exported = getDefaultLikeExportWorker(moduleSymbol, checker);
                if (!exported)
                    return undefined;
                var symbol = exported.symbol, kind = exported.kind;
                var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions);
                return info && __assign({ symbol: symbol, kind: kind }, info);
            }
            function getDefaultLikeExportWorker(moduleSymbol, checker) {
                var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
                if (defaultExport)
                    return { symbol: defaultExport, kind: 1 /* Default */ };
                var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
                return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ };
            }
            function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) {
                var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
                if (localSymbol)
                    return { symbolForMeaning: localSymbol, name: localSymbol.name };
                var name = getNameForExportDefault(defaultExport);
                if (name !== undefined)
                    return { symbolForMeaning: defaultExport, name: name };
                if (defaultExport.flags & 2097152 /* Alias */) {
                    var aliased = checker.getImmediateAliasedSymbol(defaultExport);
                    return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions);
                }
                else {
                    return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) };
                }
            }
            function getNameForExportDefault(symbol) {
                return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) {
                    if (ts.isExportAssignment(declaration)) {
                        if (ts.isIdentifier(declaration.expression)) {
                            return declaration.expression.text;
                        }
                    }
                    else if (ts.isExportSpecifier(declaration)) {
                        ts.Debug.assert(declaration.name.text === "default" /* Default */);
                        return declaration.propertyName && declaration.propertyName.text;
                    }
                });
            }
            function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) {
                var diag;
                var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
                    diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference);
                });
                return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports);
            }
            function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) {
                switch (fix.kind) {
                    case 0 /* UseNamespace */:
                        addNamespaceQualifier(changes, sourceFile, fix);
                        return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName];
                    case 1 /* ImportType */:
                        addImportType(changes, sourceFile, fix, quotePreference);
                        return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName];
                    case 2 /* AddToExisting */: {
                        var importClause = fix.importClause, importKind = fix.importKind;
                        doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray);
                        var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText());
                        return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too!
                    }
                    case 3 /* AddNew */: {
                        var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier;
                        addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined }
                            : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined }
                                : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } });
                        return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier];
                    }
                    default:
                        return ts.Debug.assertNever(fix);
                }
            }
            function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) {
                if (defaultImport) {
                    ts.Debug.assert(!clause.name);
                    changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " });
                }
                if (namedImports.length) {
                    var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); });
                    if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) {
                        for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) {
                            var spec = specifiers_1[_i];
                            changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec);
                        }
                    }
                    else {
                        if (specifiers.length) {
                            var namedImports_1 = ts.createNamedImports(specifiers);
                            if (clause.namedBindings) {
                                changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1);
                            }
                            else {
                                changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1);
                            }
                        }
                    }
                }
            }
            function addNamespaceQualifier(changes, sourceFile, _a) {
                var namespacePrefix = _a.namespacePrefix, position = _a.position;
                changes.insertText(sourceFile, position, namespacePrefix + ".");
            }
            function addImportType(changes, sourceFile, _a, quotePreference) {
                var moduleSpecifier = _a.moduleSpecifier, position = _a.position;
                changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference));
            }
            function getImportTypePrefix(moduleSpecifier, quotePreference) {
                var quote = ts.getQuoteFromPreference(quotePreference);
                return "import(" + quote + moduleSpecifier + quote + ").";
            }
            function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) {
                var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport;
                var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference);
                if (defaultImport !== undefined || namedImports.length) {
                    ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference));
                }
                if (namespaceLikeImport) {
                    ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */
                        ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier))
                        : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier));
                }
            }
            function symbolHasMeaning(_a, meaning) {
                var declarations = _a.declarations;
                return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); });
            }
            function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) {
                forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) {
                    if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) {
                        cb(module);
                    }
                });
            }
            codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom;
            function forEachExternalModule(checker, allSourceFiles, cb) {
                for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) {
                    var ambient = _a[_i];
                    cb(ambient, /*sourceFile*/ undefined);
                }
                for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) {
                    var sourceFile = allSourceFiles_1[_b];
                    if (ts.isExternalOrCommonJsModule(sourceFile)) {
                        cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
                    }
                }
            }
            /**
             * Don't include something from a `node_modules` that isn't actually reachable by a global import.
             * A relative import to node_modules is usually a bad idea.
             */
            function isImportablePath(fromPath, toPath) {
                // If it's in a `node_modules` but is not reachable from here via a global import, don't bother.
                var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; });
                return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules));
            }
            function moduleSymbolToValidIdentifier(moduleSymbol, target) {
                return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target);
            }
            codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier;
            function moduleSpecifierToValidIdentifier(moduleSpecifier, target) {
                var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index"));
                var res = "";
                var lastCharWasValid = true;
                var firstCharCode = baseName.charCodeAt(0);
                if (ts.isIdentifierStart(firstCharCode, target)) {
                    res += String.fromCharCode(firstCharCode);
                }
                else {
                    lastCharWasValid = false;
                }
                for (var i = 1; i < baseName.length; i++) {
                    var ch = baseName.charCodeAt(i);
                    var isValid = ts.isIdentifierPart(ch, target);
                    if (isValid) {
                        var char = String.fromCharCode(ch);
                        if (!lastCharWasValid) {
                            char = char.toUpperCase();
                        }
                        res += char;
                    }
                    lastCharWasValid = isValid;
                }
                // Need `|| "_"` to ensure result isn't empty.
                return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res;
            }
            codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier;
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "fixSpelling";
            var errorCodes = [
                ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
                ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
                ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
                ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
                ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code,
            ];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile;
                    var info = getInfo(sourceFile, context.span.start, context);
                    if (!info)
                        return undefined;
                    var node = info.node, suggestion = info.suggestion;
                    var target = context.host.getCompilationSettings().target;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); });
                    return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var info = getInfo(diag.file, diag.start, context);
                        var target = context.host.getCompilationSettings().target;
                        if (info)
                            doChange(changes, context.sourceFile, info.node, info.suggestion, target);
                    });
                },
            });
            function getInfo(sourceFile, pos, context) {
                // This is the identifier of the misspelled word. eg:
                // this.speling = 1;
                //      ^^^^^^^
                var node = ts.getTokenAtPosition(sourceFile, pos);
                var checker = context.program.getTypeChecker();
                var suggestion;
                if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) {
                    ts.Debug.assert(node.kind === 71 /* Identifier */);
                    var containingType = checker.getTypeAtLocation(node.parent.expression);
                    suggestion = checker.getSuggestionForNonexistentProperty(node, containingType);
                }
                else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) {
                    ts.Debug.assert(node.kind === 71 /* Identifier */);
                    var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration);
                    var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration);
                    if (resolvedSourceFile && resolvedSourceFile.symbol) {
                        suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol);
                    }
                }
                else {
                    var meaning = ts.getMeaningFromLocation(node);
                    var name = ts.getTextOfNode(node);
                    ts.Debug.assert(name !== undefined, "name should be defined");
                    suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
                }
                return suggestion === undefined ? undefined : { node: node, suggestion: suggestion };
            }
            function doChange(changes, sourceFile, node, suggestion, target) {
                if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) {
                    changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion)));
                }
                else {
                    changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion));
                }
            }
            function convertSemanticMeaningToSymbolFlags(meaning) {
                var flags = 0;
                if (meaning & 4 /* Namespace */) {
                    flags |= 1920 /* Namespace */;
                }
                if (meaning & 2 /* Type */) {
                    flags |= 67897832 /* Type */;
                }
                if (meaning & 1 /* Value */) {
                    flags |= 67220415 /* Value */;
                }
                return flags;
            }
            function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) {
                if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier))
                    return undefined;
                var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text);
                if (!resolvedModule)
                    return undefined;
                return context.program.getSourceFile(resolvedModule.resolvedFileName);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixName = "addMissingMember";
            var errorCodes = [
                ts.Diagnostics.Property_0_does_not_exist_on_type_1.code,
                ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
            ];
            var fixId = "addMissingMember";
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker());
                    if (!info)
                        return undefined;
                    if (info.kind === 0 /* Enum */) {
                        var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration;
                        var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); });
                        return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)];
                    }
                    var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
                    var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences);
                    var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ?
                        ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) :
                        getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic);
                    return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember);
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    var program = context.program, preferences = context.preferences;
                    var checker = program.getTypeChecker();
                    var seen = ts.createMap();
                    var typeDeclToMembers = new ts.NodeMap();
                    return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
                        codefix.eachDiagnostic(context, errorCodes, function (diag) {
                            var info = getInfo(diag.file, diag.start, checker);
                            if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
                                return;
                            }
                            if (info.kind === 0 /* Enum */) {
                                var token = info.token, parentDeclaration = info.parentDeclaration;
                                addEnumMemberDeclaration(changes, checker, token, parentDeclaration);
                            }
                            else {
                                var parentDeclaration = info.parentDeclaration, token_2 = info.token;
                                var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; });
                                if (!infos.some(function (i) { return i.token.text === token_2.text; }))
                                    infos.push(info);
                            }
                        });
                        typeDeclToMembers.forEach(function (infos, classDeclaration) {
                            var supers = getAllSupers(classDeclaration, checker);
                            var _loop_19 = function (info) {
                                // If some superclass added this property, don't add it again.
                                if (supers.some(function (superClassOrInterface) {
                                    var superInfos = typeDeclToMembers.get(superClassOrInterface);
                                    return !!superInfos && superInfos.some(function (_a) {
                                        var token = _a.token;
                                        return token.text === info.token.text;
                                    });
                                }))
                                    return "continue";
                                var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
                                // Always prefer to add a method declaration if possible.
                                if (call) {
                                    addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences);
                                }
                                else {
                                    if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) {
                                        addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic);
                                    }
                                    else {
                                        var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token);
                                        addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic);
                                    }
                                }
                            };
                            for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
                                var info = infos_1[_i];
                                _loop_19(info);
                            }
                        });
                    }));
                },
            });
            function getAllSupers(decl, checker) {
                var res = [];
                while (decl) {
                    var superElement = ts.getClassExtendsHeritageElement(decl);
                    var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
                    var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike);
                    if (superDecl) {
                        res.push(superDecl);
                    }
                    decl = superDecl;
                }
                return res;
            }
            var InfoKind;
            (function (InfoKind) {
                InfoKind[InfoKind["Enum"] = 0] = "Enum";
                InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface";
            })(InfoKind || (InfoKind = {}));
            function getInfo(tokenSourceFile, tokenPos, checker) {
                // The identifier of the missing property. eg:
                // this.missing = 1;
                //      ^^^^^^^
                var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos);
                if (!ts.isIdentifier(token)) {
                    return undefined;
                }
                var parent = token.parent;
                if (!ts.isPropertyAccessExpression(parent))
                    return undefined;
                var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression));
                var symbol = leftExpressionType.symbol;
                if (!symbol || !symbol.declarations)
                    return undefined;
                // Prefer to change the class instead of the interface if they are merged
                var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration);
                if (classOrInterface) {
                    var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
                    var declSourceFile = classOrInterface.getSourceFile();
                    var inJs = ts.isSourceFileJS(declSourceFile);
                    var call = ts.tryCast(parent.parent, ts.isCallExpression);
                    return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call };
                }
                var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration);
                if (enumDeclaration) {
                    return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration };
                }
                return undefined;
            }
            function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) {
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); });
                return changes.length === 0 ? undefined
                    : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members);
            }
            function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) {
                if (makeStatic) {
                    if (classDeclaration.kind === 207 /* ClassExpression */) {
                        return;
                    }
                    var className = classDeclaration.name.getText();
                    var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName);
                    changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization);
                }
                else {
                    var classConstructor = ts.getFirstConstructorWithBody(classDeclaration);
                    if (!classConstructor) {
                        return;
                    }
                    var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName);
                    changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization);
                }
            }
            function initializePropertyToUndefined(obj, propertyName) {
                return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined")));
            }
            function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) {
                var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token);
                var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode);
                return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)];
            }
            function getTypeNode(checker, classDeclaration, token) {
                var typeNode;
                if (token.parent.parent.kind === 202 /* BinaryExpression */) {
                    var binaryExpression = token.parent.parent;
                    var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
                    var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression)));
                    typeNode = checker.typeToTypeNode(widenedType, classDeclaration);
                }
                return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */);
            }
            function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) {
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); });
                return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members);
            }
            function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) {
                var property = ts.createProperty(
                /*decorators*/ undefined, 
                /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, 
                /*questionToken*/ undefined, typeNode, 
                /*initializer*/ undefined);
                var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
                if (lastProp) {
                    changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
                }
                else {
                    changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
                }
            }
            // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
            function getNodeToInsertPropertyAfter(cls) {
                var res;
                for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
                    var member = _a[_i];
                    if (!ts.isPropertyDeclaration(member))
                        break;
                    res = member;
                }
                return res;
            }
            function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) {
                // Index signatures cannot have the static modifier.
                var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */);
                var indexingParameter = ts.createParameter(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, 
                /*dotDotDotToken*/ undefined, "x", 
                /*questionToken*/ undefined, stringTypeNode, 
                /*initializer*/ undefined);
                var indexSignature = ts.createIndexSignature(
                /*decorators*/ undefined, 
                /*modifiers*/ undefined, [indexingParameter], typeNode);
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); });
                // No fixId here because code-fix-all currently only works on adding individual named properties.
                return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]);
            }
            function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) {
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); });
                return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
            }
            function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) {
                var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl));
                var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */);
                if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) {
                    changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration);
                }
                else {
                    changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration);
                }
            }
            function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) {
                /**
                 * create initializer only literal enum that has string initializer.
                 * value of initializer is a string literal that equal to name of enum member.
                 * numeric enum or empty enum will not create initializer.
                 */
                var hasStringInitializer = ts.some(enumDeclaration.members, function (member) {
                    var type = checker.getTypeAtLocation(member);
                    return !!(type && type.flags & 68 /* StringLike */);
                });
                var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined);
                changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember))));
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixName = "fixCannotFindModule";
            var fixIdInstallTypesPackage = "installTypesPackage";
            var fixIdGenerateTypes = "generateTypes";
            var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code;
            var errorCodes = [
                errorCodeCannotFindModule,
                ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code,
            ];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var host = context.host, sourceFile = context.sourceFile, start = context.span.start;
                    var packageName = tryGetImportedPackageName(sourceFile, start);
                    if (packageName === undefined)
                        return undefined;
                    var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode);
                    return typesPackageName === undefined
                        ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName))
                        : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))];
                },
                fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes],
                getAllCodeActions: function (context) {
                    var savedTypesDir = null; // tslint:disable-line no-null-keyword
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) {
                        var packageName = tryGetImportedPackageName(diag.file, diag.start);
                        if (packageName === undefined)
                            return undefined;
                        switch (context.fixId) {
                            case fixIdInstallTypesPackage: {
                                var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code);
                                if (pkg) {
                                    commands.push(getInstallCommand(diag.file.fileName, pkg));
                                }
                                break;
                            }
                            case fixIdGenerateTypes: {
                                var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context);
                                var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context);
                                if (command)
                                    commands.push(command);
                                break;
                            }
                            default:
                                ts.Debug.fail("Bad fixId: " + context.fixId);
                        }
                    });
                },
            });
            function tryGetGenerateTypesAction(context, packageName) {
                var command;
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
                    var typesDir = getOrCreateTypesDirectory(t, context);
                    command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context);
                });
                return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command);
            }
            function tryGenerateTypes(typesDir, packageName, context) {
                var file = context.sourceFile.fileName;
                var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217
                if (fileToGenerateTypesFor === undefined)
                    return undefined;
                var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts");
                if (context.host.fileExists(outputFileName))
                    return undefined;
                return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName };
            }
            // If no types directory exists yet, adds it to tsconfig.json
            function getOrCreateTypesDirectory(changes, context) {
                var configFile = context.program.getCompilerOptions().configFile;
                if (!configFile)
                    return undefined;
                var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
                if (!tsconfigObjectLiteral)
                    return undefined;
                var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions");
                if (!compilerOptionsProperty) {
                    var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]);
                    changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions));
                    return defaultTypesDirectoryName;
                }
                var compilerOptions = compilerOptionsProperty.initializer;
                if (!ts.isObjectLiteralExpression(compilerOptions))
                    return defaultTypesDirectoryName;
                var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions);
                var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions);
                return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping);
            }
            var defaultBaseUrl = ".";
            function makeDefaultBaseUrl() {
                return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl));
            }
            function getOrAddBaseUrl(changes, tsconfig, compilerOptions) {
                var baseUrlProp = findProperty(compilerOptions, "baseUrl");
                if (baseUrlProp) {
                    return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl;
                }
                else {
                    changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl());
                    return defaultBaseUrl;
                }
            }
            var defaultTypesDirectoryName = "types";
            function makeDefaultPathMapping() {
                return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")]));
            }
            function makeDefaultPaths() {
                return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()]));
            }
            function getOrAddPathMapping(changes, tsconfig, compilerOptions) {
                var paths = findProperty(compilerOptions, "paths");
                if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) {
                    changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths());
                    return defaultTypesDirectoryName;
                }
                // Look for an existing path mapping. Should look like `"*": "foo/*"`.
                var existing = ts.firstDefined(paths.initializer.properties, function (prop) {
                    return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer)
                        ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; })
                        : undefined;
                });
                if (existing)
                    return existing;
                changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping());
                return defaultTypesDirectoryName;
            }
            function createJsonPropertyAssignment(name, initializer) {
                return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer);
            }
            function findProperty(obj, name) {
                return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; });
            }
            function getInstallCommand(fileName, packageName) {
                return { type: "install package", file: fileName, packageName: packageName };
            }
            function tryGetImportedPackageName(sourceFile, pos) {
                var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text;
                var packageName = ts.parsePackageName(moduleName).packageName;
                return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName;
            }
            function getTypesPackageNameToInstall(packageName, host, diagCode) {
                return diagCode === errorCodeCannotFindModule
                    ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined)
                    : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var errorCodes = [
                ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code,
                ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code,
            ];
            var fixId = "fixClassDoesntImplementInheritedAbstractMember";
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var program = context.program, sourceFile = context.sourceFile, span = context.span;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
                        return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences);
                    });
                    return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    var seenClassDeclarations = ts.createMap();
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var classDeclaration = getClass(diag.file, diag.start);
                        if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
                            addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences);
                        }
                    });
                },
            });
            function getClass(sourceFile, pos) {
                // Token is the identifier in the case of a class declaration
                // or the class keyword token in the case of a class expression.
                var token = ts.getTokenAtPosition(sourceFile, pos);
                return ts.cast(token.parent, ts.isClassLike);
            }
            function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) {
                var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration);
                var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
                // Note that this is ultimately derived from a map indexed by symbol names,
                // so duplicates cannot occur.
                var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
                codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); });
            }
            function symbolPointsToNonPrivateAndAbstractMember(symbol) {
                // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files
                // (now named `codeFixClassExtendAbstractPrivateProperty.ts`)
                var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations()));
                return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "classSuperMustPrecedeThisAccess";
            var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, span = context.span;
                    var nodes = getNodes(sourceFile, span.start);
                    if (!nodes)
                        return undefined;
                    var constructor = nodes.constructor, superCall = nodes.superCall;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    var sourceFile = context.sourceFile;
                    var seenClasses = ts.createMap(); // Ensure we only do this once per class.
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var nodes = getNodes(diag.file, diag.start);
                        if (!nodes)
                            return;
                        var constructor = nodes.constructor, superCall = nodes.superCall;
                        if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) {
                            doChange(changes, sourceFile, constructor, superCall);
                        }
                    });
                },
            });
            function doChange(changes, sourceFile, constructor, superCall) {
                changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall);
                changes.delete(sourceFile, superCall);
            }
            function getNodes(sourceFile, pos) {
                var token = ts.getTokenAtPosition(sourceFile, pos);
                if (token.kind !== 99 /* ThisKeyword */)
                    return undefined;
                var constructor = ts.getContainingFunction(token);
                var superCall = findSuperCall(constructor.body);
                // figure out if the `this` access is actually inside the supercall
                // i.e. super(this.a), since in that case we won't suggest a fix
                return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined;
            }
            function findSuperCall(n) {
                return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression)
                    ? n
                    : ts.isFunctionLike(n)
                        ? undefined
                        : ts.forEachChild(n, findSuperCall);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "constructorForDerivedNeedSuperCall";
            var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, span = context.span;
                    var ctr = getNode(sourceFile, span.start);
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        return doChange(changes, context.sourceFile, getNode(diag.file, diag.start));
                    });
                },
            });
            function getNode(sourceFile, pos) {
                var token = ts.getTokenAtPosition(sourceFile, pos);
                ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */);
                return token.parent;
            }
            function doChange(changes, sourceFile, ctr) {
                var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray));
                changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "extendsInterfaceBecomesImplements";
            var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile;
                    var nodes = getNodes(sourceFile, context.span.start);
                    if (!nodes)
                        return undefined;
                    var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var nodes = getNodes(diag.file, diag.start);
                        if (nodes)
                            doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses);
                    });
                },
            });
            function getNodes(sourceFile, pos) {
                var token = ts.getTokenAtPosition(sourceFile, pos);
                var heritageClauses = ts.getContainingClass(token).heritageClauses;
                var extendsToken = heritageClauses[0].getFirstToken();
                return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined;
            }
            function doChanges(changes, sourceFile, extendsToken, heritageClauses) {
                changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */));
                // If there is already an implements clause, replace the implements keyword with a comma.
                if (heritageClauses.length === 2 &&
                    heritageClauses[0].token === 85 /* ExtendsKeyword */ &&
                    heritageClauses[1].token === 108 /* ImplementsKeyword */) {
                    var implementsToken = heritageClauses[1].getFirstToken();
                    var implementsFullStart = implementsToken.getFullStart();
                    changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */));
                    // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive.
                    // (Trailing because leading might be indentation, which is more sensitive.)
                    var text = sourceFile.text;
                    var end = implementsToken.end;
                    while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) {
                        end++;
                    }
                    changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end });
                }
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "forgottenThisPropertyAccess";
            var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code;
            var errorCodes = [
                ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
                didYouMeanStaticMemberCode,
            ];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile;
                    var info = getInfo(sourceFile, context.span.start, context.errorCode);
                    if (!info) {
                        return undefined;
                    }
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
                    return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var info = getInfo(diag.file, diag.start, diag.code);
                        if (info)
                            doChange(changes, context.sourceFile, info);
                    });
                },
            });
            function getInfo(sourceFile, pos, diagCode) {
                var node = ts.getTokenAtPosition(sourceFile, pos);
                if (!ts.isIdentifier(node))
                    return undefined;
                return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined };
            }
            function doChange(changes, sourceFile, _a) {
                var node = _a.node, className = _a.className;
                // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper
                ts.suppressLeadingAndTrailingTrivia(node);
                changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node));
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixName = "unusedIdentifier";
            var fixIdPrefix = "unusedIdentifier_prefix";
            var fixIdDelete = "unusedIdentifier_delete";
            var fixIdInfer = "unusedIdentifier_infer";
            var errorCodes = [
                ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code,
                ts.Diagnostics._0_is_declared_but_never_used.code,
                ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
                ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
                ts.Diagnostics.All_destructured_elements_are_unused.code,
                ts.Diagnostics.All_variables_are_unused.code,
                ts.Diagnostics.All_type_parameters_are_unused.code,
            ];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program;
                    var checker = program.getTypeChecker();
                    var sourceFiles = program.getSourceFiles();
                    var token = ts.getTokenAtPosition(sourceFile, context.span.start);
                    if (ts.isJSDocTemplateTag(token)) {
                        return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)];
                    }
                    if (token.kind === 27 /* LessThanToken */) {
                        var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); });
                        return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)];
                    }
                    var importDecl = tryGetFullImport(token);
                    if (importDecl) {
                        var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); });
                        return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])];
                    }
                    var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) {
                        return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false);
                    });
                    if (delDestructure.length) {
                        return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)];
                    }
                    var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); });
                    if (delVar.length) {
                        return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)];
                    }
                    var result = [];
                    if (token.kind === 126 /* InferKeyword */) {
                        var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); });
                        var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text;
                        result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown));
                    }
                    else {
                        var deletion = ts.textChanges.ChangeTracker.with(context, function (t) {
                            return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false);
                        });
                        if (deletion.length) {
                            var name = ts.isComputedPropertyName(token.parent) ? token.parent : token;
                            result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)]));
                        }
                    }
                    var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); });
                    if (prefix.length) {
                        result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible));
                    }
                    return result;
                },
                fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer],
                getAllCodeActions: function (context) {
                    var sourceFile = context.sourceFile, program = context.program;
                    var checker = program.getTypeChecker();
                    var sourceFiles = program.getSourceFiles();
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var token = ts.getTokenAtPosition(sourceFile, diag.start);
                        switch (context.fixId) {
                            case fixIdPrefix:
                                tryPrefixDeclaration(changes, diag.code, sourceFile, token);
                                break;
                            case fixIdDelete: {
                                if (token.kind === 126 /* InferKeyword */)
                                    break; // Can't delete
                                var importDecl = tryGetFullImport(token);
                                if (importDecl) {
                                    changes.delete(sourceFile, importDecl);
                                }
                                else if (ts.isJSDocTemplateTag(token)) {
                                    changes.delete(sourceFile, token);
                                }
                                else if (token.kind === 27 /* LessThanToken */) {
                                    deleteTypeParameters(changes, sourceFile, token);
                                }
                                else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) &&
                                    !tryDeleteFullVariableStatement(sourceFile, token, changes)) {
                                    tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true);
                                }
                                break;
                            }
                            case fixIdInfer:
                                if (token.kind === 126 /* InferKeyword */) {
                                    changeInferToUnknown(changes, sourceFile, token);
                                }
                                break;
                            default:
                                ts.Debug.fail(JSON.stringify(context.fixId));
                        }
                    });
                },
            });
            function changeInferToUnknown(changes, sourceFile, token) {
                changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */));
            }
            function createDeleteFix(changes, diag) {
                return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations);
            }
            function deleteTypeParameters(changes, sourceFile, token) {
                changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters));
            }
            // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
            function tryGetFullImport(token) {
                return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined;
            }
            function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
                if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent))
                    return false;
                var decl = token.parent.parent;
                if (decl.kind === 149 /* Parameter */) {
                    tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll);
                }
                else {
                    changes.delete(sourceFile, decl);
                }
                return true;
            }
            function tryDeleteFullVariableStatement(sourceFile, token, changes) {
                var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList);
                if (declarationList && declarationList.getChildren(sourceFile)[0] === token) {
                    changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList);
                    return true;
                }
                return false;
            }
            function tryPrefixDeclaration(changes, errorCode, sourceFile, token) {
                // Don't offer to prefix a property.
                if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code)
                    return;
                if (token.kind === 126 /* InferKeyword */) {
                    token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name;
                }
                if (ts.isIdentifier(token) && canPrefix(token)) {
                    changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text));
                }
            }
            function canPrefix(token) {
                switch (token.parent.kind) {
                    case 149 /* Parameter */:
                    case 148 /* TypeParameter */:
                        return true;
                    case 235 /* VariableDeclaration */: {
                        var varDecl = token.parent;
                        switch (varDecl.parent.parent.kind) {
                            case 225 /* ForOfStatement */:
                            case 224 /* ForInStatement */:
                                return true;
                        }
                    }
                }
                return false;
            }
            function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) {
                tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll);
                if (ts.isIdentifier(token))
                    deleteAssignments(changes, sourceFile, token, checker);
            }
            function deleteAssignments(changes, sourceFile, token, checker) {
                ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) {
                    if (ref.parent.kind === 187 /* PropertyAccessExpression */)
                        ref = ref.parent;
                    if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) {
                        changes.delete(sourceFile, ref.parent.parent);
                    }
                });
            }
            function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
                var parent = token.parent;
                if (ts.isParameter(parent)) {
                    tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll);
                }
                else {
                    changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent);
                }
            }
            function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) {
                if (mayDeleteParameter(p, checker, isFixAll)) {
                    changes.delete(sourceFile, p);
                    deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker);
                }
            }
            function mayDeleteParameter(p, checker, isFixAll) {
                var parent = p.parent;
                switch (parent.kind) {
                    case 154 /* MethodDeclaration */:
                        // Don't remove a parameter if this overrides something.
                        var symbol = checker.getSymbolAtLocation(parent.name);
                        if (ts.isMemberSymbolInBaseType(symbol, checker))
                            return false;
                    // falls through
                    case 155 /* Constructor */:
                    case 237 /* FunctionDeclaration */:
                        return true;
                    case 194 /* FunctionExpression */:
                    case 195 /* ArrowFunction */: {
                        // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused.
                        var parameters = parent.parameters;
                        var index = parameters.indexOf(p);
                        ts.Debug.assert(index !== -1);
                        return isFixAll
                            ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 71 /* Identifier */ && !p.symbol.isReferenced; })
                            : index === parameters.length - 1;
                    }
                    case 157 /* SetAccessor */:
                        // Setter must have a parameter
                        return false;
                    default:
                        return ts.Debug.failBadSyntaxKind(parent);
                }
            }
            function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) {
                ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) {
                    var index = deletedParameter.parent.parameters.indexOf(deletedParameter);
                    if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments.
                        changes.delete(sourceFile, call.arguments[index]);
                    }
                });
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "fixUnreachableCode";
            var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); },
            });
            function doChange(changes, sourceFile, start, length) {
                var token = ts.getTokenAtPosition(sourceFile, start);
                var statement = ts.findAncestor(token, ts.isStatement);
                ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile));
                var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent;
                if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) {
                    switch (container.kind) {
                        case 220 /* IfStatement */:
                            if (container.elseStatement) {
                                if (ts.isBlock(statement.parent)) {
                                    break;
                                }
                                else {
                                    changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray));
                                }
                                return;
                            }
                        // falls through
                        case 222 /* WhileStatement */:
                        case 223 /* ForStatement */:
                            changes.delete(sourceFile, container);
                            return;
                    }
                }
                if (ts.isBlock(statement.parent)) {
                    var end_2 = start + length;
                    var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; }));
                    changes.deleteNodeRange(sourceFile, statement, lastStatement);
                }
                else {
                    changes.delete(sourceFile, statement);
                }
            }
            function lastWhere(a, pred) {
                var last;
                for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
                    var value = a_1[_i];
                    if (!pred(value))
                        break;
                    last = value;
                }
                return last;
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "fixUnusedLabel";
            var errorCodes = [ts.Diagnostics.Unused_label.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
            });
            function doChange(changes, sourceFile, start) {
                var token = ts.getTokenAtPosition(sourceFile, start);
                var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
                var pos = token.getStart(sourceFile);
                var statementPos = labeledStatement.statement.getStart(sourceFile);
                // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
                var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
                    : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
                changes.deleteRange(sourceFile, { pos: pos, end: end });
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixIdPlain = "fixJSDocTypes_plain";
            var fixIdNullable = "fixJSDocTypes_nullable";
            var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile;
                    var checker = context.program.getTypeChecker();
                    var info = getInfo(sourceFile, context.span.start, checker);
                    if (!info)
                        return undefined;
                    var typeNode = info.typeNode, type = info.type;
                    var original = typeNode.getText(sourceFile);
                    var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
                    if (typeNode.kind === 284 /* JSDocNullableType */) {
                        // for nullable types, suggest the flow-compatible `T | null | undefined`
                        // in addition to the jsdoc/closure-compatible `T | null`
                        actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
                    }
                    return actions;
                    function fix(type, fixId, fixAllDescription) {
                        var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); });
                        return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription);
                    }
                },
                fixIds: [fixIdPlain, fixIdNullable],
                getAllCodeActions: function (context) {
                    var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile;
                    var checker = program.getTypeChecker();
                    return codefix.codeFixAll(context, errorCodes, function (changes, err) {
                        var info = getInfo(err.file, err.start, checker);
                        if (!info)
                            return;
                        var typeNode = info.typeNode, type = info.type;
                        var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type;
                        doChange(changes, sourceFile, typeNode, fixedType, checker);
                    });
                }
            });
            function doChange(changes, sourceFile, oldTypeNode, newType, checker) {
                changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217
            }
            function getInfo(sourceFile, pos, checker) {
                var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer);
                var typeNode = decl && decl.type;
                return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) };
            }
            function isTypeContainer(node) {
                // NOTE: Some locations are not handled yet:
                // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments
                switch (node.kind) {
                    case 210 /* AsExpression */:
                    case 158 /* CallSignature */:
                    case 159 /* ConstructSignature */:
                    case 237 /* FunctionDeclaration */:
                    case 156 /* GetAccessor */:
                    case 160 /* IndexSignature */:
                    case 179 /* MappedType */:
                    case 154 /* MethodDeclaration */:
                    case 153 /* MethodSignature */:
                    case 149 /* Parameter */:
                    case 152 /* PropertyDeclaration */:
                    case 151 /* PropertySignature */:
                    case 157 /* SetAccessor */:
                    case 240 /* TypeAliasDeclaration */:
                    case 192 /* TypeAssertionExpression */:
                    case 235 /* VariableDeclaration */:
                        return true;
                    default:
                        return false;
                }
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "fixAwaitInSyncFunction";
            var errorCodes = [
                ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code,
                ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code,
            ];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, span = context.span;
                    var nodes = getNodes(sourceFile, span.start);
                    if (!nodes)
                        return undefined;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var nodes = getNodes(diag.file, diag.start);
                        if (!nodes)
                            return;
                        doChange(changes, context.sourceFile, nodes);
                    });
                },
            });
            function getReturnType(expr) {
                if (expr.type) {
                    return expr.type;
                }
                if (ts.isVariableDeclaration(expr.parent) &&
                    expr.parent.type &&
                    ts.isFunctionTypeNode(expr.parent.type)) {
                    return expr.parent.type.type;
                }
            }
            function getNodes(sourceFile, start) {
                var token = ts.getTokenAtPosition(sourceFile, start);
                var containingFunction = ts.getContainingFunction(token);
                if (!containingFunction) {
                    return;
                }
                var insertBefore;
                switch (containingFunction.kind) {
                    case 154 /* MethodDeclaration */:
                        insertBefore = containingFunction.name;
                        break;
                    case 237 /* FunctionDeclaration */:
                    case 194 /* FunctionExpression */:
                        insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile);
                        break;
                    case 195 /* ArrowFunction */:
                        insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters);
                        break;
                    default:
                        return;
                }
                return insertBefore && {
                    insertBefore: insertBefore,
                    returnType: getReturnType(containingFunction)
                };
            }
            function doChange(changes, sourceFile, _a) {
                var insertBefore = _a.insertBefore, returnType = _a.returnType;
                if (returnType) {
                    var entityName = ts.getEntityNameFromTypeNode(returnType);
                    if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") {
                        changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType])));
                    }
                }
                changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixName = "disableJsDiagnostics";
            var fixId = "disableJsDiagnostics";
            var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) {
                var diag = ts.Diagnostics[key];
                return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined;
            });
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext;
                    if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
                        return undefined;
                    }
                    var fixes = [
                        // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file.
                        codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [
                                ts.createTextChange(sourceFile.checkJsDirective
                                    ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end)
                                    : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)),
                            ])], ts.Diagnostics.Disable_checking_for_this_file),
                    ];
                    if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) {
                        fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages));
                    }
                    return fixes;
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    var seenLines = ts.createMap();
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) {
                            makeChange(changes, diag.file, diag.start, seenLines);
                        }
                    });
                },
            });
            function makeChange(changes, sourceFile, position, seenLines) {
                var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line;
                // Only need to add `// @ts-ignore` for a line once.
                if (!seenLines || ts.addToSeen(seenLines, lineNumber)) {
                    changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
                }
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            /**
             * Finds members of the resolved type that are missing in the class pointed to by class decl
             * and generates source code for the missing members.
             * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for.
             * @returns Empty string iff there are no member insertions.
             */
            function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) {
                var classMembers = classDeclaration.symbol.members;
                for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) {
                    var symbol = possiblyMissingSymbols_1[_i];
                    if (!classMembers.has(symbol.escapedName)) {
                        addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out);
                    }
                }
            }
            codefix.createMissingMemberNodes = createMissingMemberNodes;
            /**
             * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`.
             */
            function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) {
                var declarations = symbol.getDeclarations();
                if (!(declarations && declarations.length)) {
                    return undefined;
                }
                var declaration = declarations[0];
                var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false);
                var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration));
                var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined;
                var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
                var optional = !!(symbol.flags & 16777216 /* Optional */);
                switch (declaration.kind) {
                    case 156 /* GetAccessor */:
                    case 157 /* SetAccessor */:
                    case 151 /* PropertySignature */:
                    case 152 /* PropertyDeclaration */:
                        var typeNode = checker.typeToTypeNode(type, enclosingDeclaration);
                        out(ts.createProperty(
                        /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, 
                        /*initializer*/ undefined));
                        break;
                    case 153 /* MethodSignature */:
                    case 154 /* MethodDeclaration */:
                        // The signature for the implementation appears as an entry in `signatures` iff
                        // there is only one signature.
                        // If there are overloads and an implementation signature, it appears as an
                        // extra declaration that isn't a signature for `type`.
                        // If there is more than one overload but no implementation signature
                        // (eg: an abstract method or interface declaration), there is a 1-1
                        // correspondence of declarations and signatures.
                        var signatures = checker.getSignaturesOfType(type, 0 /* Call */);
                        if (!ts.some(signatures)) {
                            break;
                        }
                        if (declarations.length === 1) {
                            ts.Debug.assert(signatures.length === 1);
                            var signature = signatures[0];
                            outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
                            break;
                        }
                        for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
                            var signature = signatures_8[_i];
                            // Need to ensure nodes are fresh each time so they can have different positions.
                            outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false));
                        }
                        if (declarations.length > signatures.length) {
                            var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]);
                            outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
                        }
                        else {
                            ts.Debug.assert(declarations.length === signatures.length);
                            out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences));
                        }
                        break;
                }
                function outputMethod(signature, modifiers, name, body) {
                    var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body);
                    if (method)
                        out(method);
                }
            }
            function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) {
                var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 154 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */);
                if (!signatureDeclaration) {
                    return undefined;
                }
                signatureDeclaration.decorators = undefined;
                signatureDeclaration.modifiers = modifiers;
                signatureDeclaration.name = name;
                signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined;
                signatureDeclaration.body = body;
                return signatureDeclaration;
            }
            function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) {
                var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent;
                var checker = context.program.getTypeChecker();
                var types = ts.map(args, function (arg) {
                    // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
                    return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)));
                });
                var names = ts.map(args, function (arg) {
                    return ts.isIdentifier(arg) ? arg.text :
                        ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
                });
                var contextualType = checker.getContextualType(call);
                var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */);
                return ts.createMethod(
                /*decorators*/ undefined, 
                /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, 
                /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(39 /* AsteriskToken */) : undefined, methodName, 
                /*questionToken*/ undefined, 
                /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) {
                    return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
                }), 
                /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), 
                /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined);
            }
            codefix.createMethodFromCallExpression = createMethodFromCallExpression;
            function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
                var parameters = [];
                for (var i = 0; i < argCount; i++) {
                    var newParameter = ts.createParameter(
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, 
                    /*dotDotDotToken*/ undefined, 
                    /*name*/ names && names[i] || "arg" + i, 
                    /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, 
                    /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), 
                    /*initializer*/ undefined);
                    parameters.push(newParameter);
                }
                return parameters;
            }
            function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) {
                /** This is *a* signature with the maximal number of arguments,
                 * such that if there is a "maximal" signature without rest arguments,
                 * this is one of them.
                 */
                var maxArgsSignature = signatures[0];
                var minArgumentCount = signatures[0].minArgumentCount;
                var someSigHasRestParameter = false;
                for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
                    var sig = signatures_9[_i];
                    minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
                    if (sig.hasRestParameter) {
                        someSigHasRestParameter = true;
                    }
                    if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) {
                        maxArgsSignature = sig;
                    }
                }
                var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0);
                var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; });
                var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false);
                if (someSigHasRestParameter) {
                    var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */));
                    var restParameter = ts.createParameter(
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", 
                    /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyArrayType, 
                    /*initializer*/ undefined);
                    parameters.push(restParameter);
                }
                return createStubbedMethod(modifiers, name, optional, 
                /*typeParameters*/ undefined, parameters, 
                /*returnType*/ undefined, preferences);
            }
            function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) {
                return ts.createMethod(
                /*decorators*/ undefined, modifiers, 
                /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences));
            }
            function createStubbedMethodBody(preferences) {
                return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), 
                    /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], 
                /*multiline*/ true);
            }
            function createVisibilityModifier(flags) {
                if (flags & 4 /* Public */) {
                    return ts.createToken(114 /* PublicKeyword */);
                }
                else if (flags & 16 /* Protected */) {
                    return ts.createToken(113 /* ProtectedKeyword */);
                }
                return undefined;
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "inferFromUsage";
            var errorCodes = [
                // Variable declarations
                ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code,
                // Variable uses
                ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code,
                // Parameter declarations
                ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code,
                ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code,
                // Get Accessor declarations
                ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code,
                ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code,
                // Set Accessor declarations
                ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code,
                // Property declarations
                ts.Diagnostics.Member_0_implicitly_has_an_1_type.code,
            ];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken;
                    if (ts.isSourceFileJS(sourceFile)) {
                        return undefined; // TODO: GH#20113
                    }
                    var token = ts.getTokenAtPosition(sourceFile, start);
                    var declaration;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); });
                    var name = declaration && ts.getNameOfDeclaration(declaration);
                    return !name || changes.length === 0 ? undefined
                        : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
                    var markSeen = ts.nodeSeenTracker();
                    return codefix.codeFixAll(context, errorCodes, function (changes, err) {
                        doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen);
                    });
                },
            });
            function getDiagnostic(errorCode, token) {
                switch (errorCode) {
                    case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
                        return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217
                    case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
                        return ts.Diagnostics.Infer_parameter_types_from_usage;
                    default:
                        return ts.Diagnostics.Infer_type_of_0_from_usage;
                }
            }
            function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) {
                if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) {
                    return undefined;
                }
                var parent = token.parent;
                switch (errorCode) {
                    // Variable and Property declarations
                    case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code:
                    case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
                        if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
                            annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken);
                            return parent;
                        }
                        return undefined;
                    case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
                        var symbol = program.getTypeChecker().getSymbolAtLocation(token);
                        if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
                            annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken);
                            return symbol.valueDeclaration;
                        }
                        return undefined;
                    }
                }
                var containingFunction = ts.getContainingFunction(token);
                if (containingFunction === undefined) {
                    return undefined;
                }
                switch (errorCode) {
                    // Parameter declarations
                    case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
                        if (ts.isSetAccessor(containingFunction)) {
                            annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken);
                            return containingFunction;
                        }
                    // falls through
                    case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
                        if (markSeen(containingFunction)) {
                            var param = ts.cast(parent, ts.isParameter);
                            annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken);
                            return param;
                        }
                        return undefined;
                    // Get Accessor declarations
                    case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code:
                    case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code:
                        if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) {
                            annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program);
                            return containingFunction;
                        }
                        return undefined;
                    // Set Accessor declarations
                    case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
                        if (ts.isSetAccessor(containingFunction)) {
                            annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken);
                            return containingFunction;
                        }
                        return undefined;
                    default:
                        return ts.Debug.fail(String(errorCode));
                }
            }
            function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) {
                if (ts.isIdentifier(declaration.name)) {
                    annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program);
                }
            }
            function isApplicableFunctionForInference(declaration) {
                switch (declaration.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 154 /* MethodDeclaration */:
                    case 155 /* Constructor */:
                        return true;
                    case 194 /* FunctionExpression */:
                        return !!declaration.name;
                }
                return false;
            }
            function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) {
                if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) {
                    return;
                }
                var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) ||
                    containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; });
                // We didn't actually find a set of type inference positions matching each parameter position
                if (!types || containingFunction.parameters.length !== types.length) {
                    return;
                }
                ts.zipWith(containingFunction.parameters, types, function (parameter, type) {
                    if (!parameter.type && !parameter.initializer) {
                        annotate(changes, sourceFile, parameter, type, program);
                    }
                });
            }
            function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) {
                var param = ts.firstOrUndefined(setAccessorDeclaration.parameters);
                if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) {
                    var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) ||
                        inferTypeForVariableFromUsage(param.name, program, cancellationToken);
                    annotate(changes, sourceFile, param, type, program);
                }
            }
            function annotate(changes, sourceFile, declaration, type, program) {
                var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker());
                if (typeNode)
                    changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
            }
            function getTypeNodeIfAccessible(type, enclosingScope, checker) {
                var typeIsAccessible = true;
                var notAccessible = function () { typeIsAccessible = false; };
                var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
                    trackSymbol: function (symbol, declaration, meaning) {
                        // TODO: GH#18217
                        typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
                    },
                    reportInaccessibleThisError: notAccessible,
                    reportPrivateInBaseOfClassExpression: notAccessible,
                    reportInaccessibleUniqueSymbolError: notAccessible,
                });
                return typeIsAccessible ? res : undefined;
            }
            function getReferences(token, program, cancellationToken) {
                // Position shouldn't matter since token is not a SourceFile.
                return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
                    return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined;
                });
            }
            function inferTypeForVariableFromUsage(token, program, cancellationToken) {
                return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken);
            }
            function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) {
                switch (containingFunction.kind) {
                    case 155 /* Constructor */:
                    case 194 /* FunctionExpression */:
                    case 237 /* FunctionDeclaration */:
                    case 154 /* MethodDeclaration */:
                        var isConstructor = containingFunction.kind === 155 /* Constructor */;
                        var searchToken = isConstructor ?
                            ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) :
                            containingFunction.name;
                        if (searchToken) {
                            return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken);
                        }
                }
            }
            var InferFromReference;
            (function (InferFromReference) {
                function inferTypeFromReferences(references, checker, cancellationToken) {
                    var usageContext = {};
                    for (var _i = 0, references_1 = references; _i < references_1.length; _i++) {
                        var reference = references_1[_i];
                        cancellationToken.throwIfCancellationRequested();
                        inferTypeFromContext(reference, checker, usageContext);
                    }
                    return getTypeFromUsageContext(usageContext, checker);
                }
                InferFromReference.inferTypeFromReferences = inferTypeFromReferences;
                function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) {
                    if (references.length === 0) {
                        return undefined;
                    }
                    if (!declaration.parameters) {
                        return undefined;
                    }
                    var usageContext = {};
                    for (var _i = 0, references_2 = references; _i < references_2.length; _i++) {
                        var reference = references_2[_i];
                        cancellationToken.throwIfCancellationRequested();
                        inferTypeFromContext(reference, checker, usageContext);
                    }
                    var isConstructor = declaration.kind === 155 /* Constructor */;
                    var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
                    return callContexts && declaration.parameters.map(function (parameter, parameterIndex) {
                        var types = [];
                        var isRest = ts.isRestParameter(parameter);
                        for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) {
                            var callContext = callContexts_1[_i];
                            if (callContext.argumentTypes.length <= parameterIndex) {
                                continue;
                            }
                            if (isRest) {
                                for (var i = parameterIndex; i < callContext.argumentTypes.length; i++) {
                                    types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i]));
                                }
                            }
                            else {
                                types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex]));
                            }
                        }
                        if (!types.length) {
                            return undefined;
                        }
                        var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */));
                        return isRest ? checker.createArrayType(type) : type;
                    });
                }
                InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences;
                function inferTypeFromContext(node, checker, usageContext) {
                    while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
                        node = node.parent;
                    }
                    switch (node.parent.kind) {
                        case 201 /* PostfixUnaryExpression */:
                            usageContext.isNumber = true;
                            break;
                        case 200 /* PrefixUnaryExpression */:
                            inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext);
                            break;
                        case 202 /* BinaryExpression */:
                            inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext);
                            break;
                        case 269 /* CaseClause */:
                        case 270 /* DefaultClause */:
                            inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext);
                            break;
                        case 189 /* CallExpression */:
                        case 190 /* NewExpression */:
                            if (node.parent.expression === node) {
                                inferTypeFromCallExpressionContext(node.parent, checker, usageContext);
                            }
                            else {
                                inferTypeFromContextualType(node, checker, usageContext);
                            }
                            break;
                        case 187 /* PropertyAccessExpression */:
                            inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext);
                            break;
                        case 188 /* ElementAccessExpression */:
                            inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext);
                            break;
                        case 235 /* VariableDeclaration */: {
                            var _a = node.parent, name = _a.name, initializer = _a.initializer;
                            if (node === name) {
                                if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error.
                                    addCandidateType(usageContext, checker.getTypeAtLocation(initializer));
                                }
                                break;
                            }
                        }
                        // falls through
                        default:
                            return inferTypeFromContextualType(node, checker, usageContext);
                    }
                }
                function inferTypeFromContextualType(node, checker, usageContext) {
                    if (ts.isExpressionNode(node)) {
                        addCandidateType(usageContext, checker.getContextualType(node));
                    }
                }
                function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) {
                    switch (node.operator) {
                        case 43 /* PlusPlusToken */:
                        case 44 /* MinusMinusToken */:
                        case 38 /* MinusToken */:
                        case 52 /* TildeToken */:
                            usageContext.isNumber = true;
                            break;
                        case 37 /* PlusToken */:
                            usageContext.isNumberOrString = true;
                            break;
                        // case SyntaxKind.ExclamationToken:
                        // no inferences here;
                    }
                }
                function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) {
                    switch (parent.operatorToken.kind) {
                        // ExponentiationOperator
                        case 40 /* AsteriskAsteriskToken */:
                        // MultiplicativeOperator
                        case 39 /* AsteriskToken */:
                        case 41 /* SlashToken */:
                        case 42 /* PercentToken */:
                        // ShiftOperator
                        case 45 /* LessThanLessThanToken */:
                        case 46 /* GreaterThanGreaterThanToken */:
                        case 47 /* GreaterThanGreaterThanGreaterThanToken */:
                        // BitwiseOperator
                        case 48 /* AmpersandToken */:
                        case 49 /* BarToken */:
                        case 50 /* CaretToken */:
                        // CompoundAssignmentOperator
                        case 60 /* MinusEqualsToken */:
                        case 62 /* AsteriskAsteriskEqualsToken */:
                        case 61 /* AsteriskEqualsToken */:
                        case 63 /* SlashEqualsToken */:
                        case 64 /* PercentEqualsToken */:
                        case 68 /* AmpersandEqualsToken */:
                        case 69 /* BarEqualsToken */:
                        case 70 /* CaretEqualsToken */:
                        case 65 /* LessThanLessThanEqualsToken */:
                        case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                        case 66 /* GreaterThanGreaterThanEqualsToken */:
                        // AdditiveOperator
                        case 38 /* MinusToken */:
                        // RelationalOperator
                        case 27 /* LessThanToken */:
                        case 30 /* LessThanEqualsToken */:
                        case 29 /* GreaterThanToken */:
                        case 31 /* GreaterThanEqualsToken */:
                            var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
                            if (operandType.flags & 544 /* EnumLike */) {
                                addCandidateType(usageContext, operandType);
                            }
                            else {
                                usageContext.isNumber = true;
                            }
                            break;
                        case 59 /* PlusEqualsToken */:
                        case 37 /* PlusToken */:
                            var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
                            if (otherOperandType.flags & 544 /* EnumLike */) {
                                addCandidateType(usageContext, otherOperandType);
                            }
                            else if (otherOperandType.flags & 168 /* NumberLike */) {
                                usageContext.isNumber = true;
                            }
                            else if (otherOperandType.flags & 68 /* StringLike */) {
                                usageContext.isString = true;
                            }
                            else {
                                usageContext.isNumberOrString = true;
                            }
                            break;
                        //  AssignmentOperators
                        case 58 /* EqualsToken */:
                        case 32 /* EqualsEqualsToken */:
                        case 34 /* EqualsEqualsEqualsToken */:
                        case 35 /* ExclamationEqualsEqualsToken */:
                        case 33 /* ExclamationEqualsToken */:
                            addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left));
                            break;
                        case 92 /* InKeyword */:
                            if (node === parent.left) {
                                usageContext.isString = true;
                            }
                            break;
                        // LogicalOperator
                        case 54 /* BarBarToken */:
                            if (node === parent.left &&
                                (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) {
                                // var x = x || {};
                                // TODO: use getFalsyflagsOfType
                                addCandidateType(usageContext, checker.getTypeAtLocation(parent.right));
                            }
                            break;
                        case 53 /* AmpersandAmpersandToken */:
                        case 26 /* CommaToken */:
                        case 93 /* InstanceOfKeyword */:
                            // nothing to infer here
                            break;
                    }
                }
                function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) {
                    addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression));
                }
                function inferTypeFromCallExpressionContext(parent, checker, usageContext) {
                    var callContext = {
                        argumentTypes: [],
                        returnType: {}
                    };
                    if (parent.arguments) {
                        for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) {
                            var argument = _a[_i];
                            callContext.argumentTypes.push(checker.getTypeAtLocation(argument));
                        }
                    }
                    inferTypeFromContext(parent, checker, callContext.returnType);
                    if (parent.kind === 189 /* CallExpression */) {
                        (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext);
                    }
                    else {
                        (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext);
                    }
                }
                function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) {
                    var name = ts.escapeLeadingUnderscores(parent.name.text);
                    if (!usageContext.properties) {
                        usageContext.properties = ts.createUnderscoreEscapedMap();
                    }
                    var propertyUsageContext = usageContext.properties.get(name) || {};
                    inferTypeFromContext(parent, checker, propertyUsageContext);
                    usageContext.properties.set(name, propertyUsageContext);
                }
                function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) {
                    if (node === parent.argumentExpression) {
                        usageContext.isNumberOrString = true;
                        return;
                    }
                    else {
                        var indexType = checker.getTypeAtLocation(parent.argumentExpression);
                        var indexUsageContext = {};
                        inferTypeFromContext(parent, checker, indexUsageContext);
                        if (indexType.flags & 168 /* NumberLike */) {
                            usageContext.numberIndexContext = indexUsageContext;
                        }
                        else {
                            usageContext.stringIndexContext = indexUsageContext;
                        }
                    }
                }
                function getTypeFromUsageContext(usageContext, checker) {
                    if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) {
                        return checker.getUnionType([checker.getNumberType(), checker.getStringType()]);
                    }
                    else if (usageContext.isNumber) {
                        return checker.getNumberType();
                    }
                    else if (usageContext.isString) {
                        return checker.getStringType();
                    }
                    else if (usageContext.candidateTypes) {
                        return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */));
                    }
                    else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
                        var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
                        var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
                        return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType());
                    }
                    else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
                        return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker));
                    }
                    else if (usageContext.numberIndexContext) {
                        return checker.createArrayType(recur(usageContext.numberIndexContext));
                    }
                    else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
                        var members_6 = ts.createUnderscoreEscapedMap();
                        var callSignatures = [];
                        var constructSignatures = [];
                        var stringIndexInfo = void 0;
                        if (usageContext.properties) {
                            usageContext.properties.forEach(function (context, name) {
                                var symbol = checker.createSymbol(4 /* Property */, name);
                                symbol.type = recur(context);
                                members_6.set(name, symbol);
                            });
                        }
                        if (usageContext.callContexts) {
                            for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) {
                                var callContext = _a[_i];
                                callSignatures.push(getSignatureFromCallContext(callContext, checker));
                            }
                        }
                        if (usageContext.constructContexts) {
                            for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) {
                                var constructContext = _c[_b];
                                constructSignatures.push(getSignatureFromCallContext(constructContext, checker));
                            }
                        }
                        if (usageContext.stringIndexContext) {
                            stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
                        }
                        return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217
                    }
                    else {
                        return undefined;
                    }
                    function recur(innerContext) {
                        return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType();
                    }
                }
                function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) {
                    var types = [];
                    if (callContexts) {
                        for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) {
                            var callContext = callContexts_2[_i];
                            if (callContext.argumentTypes.length > parameterIndex) {
                                if (isRestParameter) {
                                    types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); }));
                                }
                                else {
                                    types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex]));
                                }
                            }
                        }
                    }
                    if (types.length) {
                        var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */));
                        return isRestParameter ? checker.createArrayType(type) : type;
                    }
                    return undefined;
                }
                function getSignatureFromCallContext(callContext, checker) {
                    var parameters = [];
                    for (var i = 0; i < callContext.argumentTypes.length; i++) {
                        var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i));
                        symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i]));
                        parameters.push(symbol);
                    }
                    var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType();
                    // TODO: GH#18217
                    return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
                }
                function addCandidateType(context, type) {
                    if (type && !(type.flags & 1 /* Any */) && !(type.flags & 32768 /* Never */)) {
                        (context.candidateTypes || (context.candidateTypes = [])).push(type);
                    }
                }
                function hasCallContext(usageContext) {
                    return !!usageContext && !!usageContext.callContexts;
                }
            })(InferFromReference || (InferFromReference = {}));
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixName = "invalidImportSyntax";
            function getCodeFixesForImportDeclaration(context, node) {
                var sourceFile = ts.getSourceFileOfNode(node);
                var namespace = ts.getNamespaceDeclarationNode(node);
                var opts = context.program.getCompilerOptions();
                var variations = [];
                // import Bluebird from "bluebird";
                variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences))));
                if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
                    // import Bluebird = require("bluebird");
                    variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
                    /*decorators*/ undefined, 
                    /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier))));
                }
                return variations;
            }
            function createAction(context, sourceFile, node, replacement) {
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); });
                return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]);
            }
            codefix.registerCodeFix({
                errorCodes: [
                    ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code,
                    ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code,
                ],
                getCodeActions: getActionsForUsageOfInvalidImport
            });
            function getActionsForUsageOfInvalidImport(context) {
                var sourceFile = context.sourceFile;
                var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */;
                var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
                if (!node) {
                    return [];
                }
                var expr = node.expression;
                return getImportCodeFixesForExpression(context, expr);
            }
            codefix.registerCodeFix({
                errorCodes: [
                    // The following error codes cover pretty much all assignability errors that could involve an expression
                    ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
                    ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code,
                    ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
                    ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
                    ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code,
                    ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code,
                    ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code,
                    ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code,
                    ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code,
                    ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
                    ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code,
                    ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code,
                ],
                getCodeActions: getActionsForInvalidImportLocation
            });
            function getActionsForInvalidImportLocation(context) {
                var sourceFile = context.sourceFile;
                var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
                if (!node) {
                    return [];
                }
                return getImportCodeFixesForExpression(context, node);
            }
            function getImportCodeFixesForExpression(context, expr) {
                var type = context.program.getTypeChecker().getTypeAtLocation(expr);
                if (!(type.symbol && type.symbol.originatingImport)) {
                    return [];
                }
                var fixes = [];
                var relatedImport = type.symbol.originatingImport; // TODO: GH#18217
                if (!ts.isImportCall(relatedImport)) {
                    ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
                }
                if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
                    var sourceFile_3 = context.sourceFile;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); });
                    fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
                }
                return fixes;
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixName = "strictClassInitialization";
            var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
            var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
            var fixIdAddInitializer = "addMissingPropertyInitializer";
            var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
                    if (!propertyDeclaration)
                        return;
                    var result = [
                        getActionForAddMissingUndefinedType(context, propertyDeclaration),
                        getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration)
                    ];
                    ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration));
                    return result;
                },
                fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
                        if (!propertyDeclaration)
                            return;
                        switch (context.fixId) {
                            case fixIdAddDefiniteAssignmentAssertions:
                                addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration);
                                break;
                            case fixIdAddUndefinedType:
                                addUndefinedType(changes, diag.file, propertyDeclaration);
                                break;
                            case fixIdAddInitializer:
                                var checker = context.program.getTypeChecker();
                                var initializer = getInitializer(checker, propertyDeclaration);
                                if (!initializer)
                                    return;
                                addInitializer(changes, diag.file, propertyDeclaration, initializer);
                                break;
                            default:
                                ts.Debug.fail(JSON.stringify(context.fixId));
                        }
                    });
                },
            });
            function getPropertyDeclaration(sourceFile, pos) {
                var token = ts.getTokenAtPosition(sourceFile, pos);
                return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
            }
            function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) {
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); });
                return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties);
            }
            function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
                var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer);
                changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
            }
            function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
                return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties);
            }
            function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
                var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */);
                var type = propertyDeclaration.type; // TODO: GH#18217
                var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode];
                changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types));
            }
            function getActionForAddMissingInitializer(context, propertyDeclaration) {
                var checker = context.program.getTypeChecker();
                var initializer = getInitializer(checker, propertyDeclaration);
                if (!initializer)
                    return undefined;
                var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); });
                return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties);
            }
            function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) {
                var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
                changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
            }
            function getInitializer(checker, propertyDeclaration) {
                return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217
            }
            function getDefaultValueFromType(checker, type) {
                if (type.flags & 256 /* BooleanLiteral */) {
                    return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue();
                }
                else if (type.isLiteral()) {
                    return ts.createLiteral(type.value);
                }
                else if (type.isUnion()) {
                    return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
                }
                else if (type.isClass()) {
                    var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
                    if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */))
                        return undefined;
                    var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration);
                    if (constructorDeclaration && constructorDeclaration.parameters.length)
                        return undefined;
                    return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
                }
                else if (checker.isArrayLikeType(type)) {
                    return ts.createArrayLiteral();
                }
                return undefined;
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        function generateTypesForModule(name, moduleValue, formatSettings) {
            return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings);
        }
        ts.generateTypesForModule = generateTypesForModule;
        function valueInfoToDeclarationFileText(valueInfo, formatSettings) {
            return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings));
        }
        ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
        var OutputKind;
        (function (OutputKind) {
            OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
            OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport";
            OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember";
        })(OutputKind || (OutputKind = {}));
        function toNamespaceMemberStatements(info) {
            return toStatements(info, 2 /* NamespaceMember */);
        }
        function toStatements(info, kind) {
            var isDefault = info.name === "default" /* Default */;
            var name = isDefault ? "_default" : info.name;
            if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */)
                return ts.emptyArray;
            var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)]
                : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)]
                    : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)]
                        : undefined;
            var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; };
            var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; };
            switch (info.kind) {
                case 2 /* FunctionOrClass */:
                    return exportEquals().concat(functionOrClassToStatements(modifiers, name, info));
                case 3 /* Object */:
                    var members = info.members;
                    if (kind === 0 /* ExportEquals */) {
                        return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); });
                    }
                    if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) {
                        // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration.
                        return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]);
                    }
                // falls through
                case 0 /* Const */:
                case 1 /* Array */: {
                    var comment = info.kind === 0 /* Const */ ? info.comment : undefined;
                    var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */));
                    return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]);
                }
                default:
                    return ts.Debug.assertNever(info);
            }
        }
        function exportEqualsOrDefault(name, isExportEquals) {
            return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name));
        }
        function functionOrClassToStatements(modifiers, name, _a) {
            var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers;
            var fnAst = parseClassOrFunctionBody(source);
            var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType;
            var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray;
            var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined;
            var namespaceStatements = ts.flatMap(namespaceMembers, function (info) {
                if (!isValidIdentifier(info.name))
                    return undefined;
                if (classStaticMembers) {
                    switch (info.kind) {
                        case 3 /* Object */:
                            if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) {
                                break;
                            }
                        // falls through
                        case 1 /* Array */:
                        case 0 /* Const */:
                            classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined));
                            return undefined;
                        case 2 /* FunctionOrClass */:
                            if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace.
                                var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]);
                                if (sig) {
                                    classStaticMembers.push(sig);
                                    return undefined;
                                }
                            }
                    }
                }
                return toStatements(info, 2 /* NamespaceMember */);
            });
            var decl = classStaticMembers
                ? ts.createClassDeclaration(
                /*decorators*/ undefined, modifiers, name, 
                /*typeParameters*/ undefined, 
                /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; })))
                : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined);
            return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)]));
        }
        function tryGetMethod(_a, modifiers) {
            var name = _a.name, source = _a.source;
            if (!isValidIdentifier(name))
                return undefined;
            var fnAst = parseClassOrFunctionBody(source);
            if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */))
                return undefined;
            var sig = getParametersAndReturnType(fnAst);
            return sig && ts.createMethod(
            /*decorators*/ undefined, modifiers, 
            /*asteriskToken*/ undefined, name, 
            /*questionToken*/ undefined, 
            /*typeParameters*/ undefined, sig.parameters, sig.returnType, 
            /*body*/ undefined);
        }
        function toType(info) {
            switch (info.kind) {
                case 0 /* Const */:
                    return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined);
                case 1 /* Array */:
                    return ts.createArrayTypeNode(toType(info.inner));
                case 2 /* FunctionOrClass */:
                    return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array.
                case 3 /* Object */:
                    return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); }));
                default:
                    return ts.Debug.assertNever(info);
            }
        }
        // Parses assignments to "this.x" in the constructor into class property declarations
        function getConstructorFunctionInstanceProperties(fnAst) {
            var members = [];
            forEachOwnNodeOfFunction(fnAst, function (node) {
                if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) &&
                    ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) {
                    var name = node.left.name.text;
                    if (!ts.isJsPrivate(name))
                        members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined));
                }
            });
            return members;
        }
        function getParametersAndReturnType(fnAst) {
            if (typeof fnAst === "number") {
                return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() };
            }
            var usedArguments = false, hasReturn = false;
            forEachOwnNodeOfFunction(fnAst, function (node) {
                usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments";
                hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */;
            });
            var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray));
            return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) };
        }
        function makeParameter(name, type) {
            return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type);
        }
        function makeRestParameter() {
            return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType()));
        }
        /** Returns 'undefined' for class with no declared constructor */
        function parseClassOrFunctionBody(source) {
            if (typeof source === "number")
                return source;
            var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); });
            return classOrFunction
                ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction
                // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal.
                : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration);
        }
        function parseExpression(expr) {
            var text = "const _ = " + expr;
            var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true);
            return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer;
        }
        function inferParameterType(_fn, _param) {
            // TODO: Inspect function body for clues (see inferFromUsage.ts)
            return anyType();
        }
        // Descends through all nodes in a function, but not in nested functions.
        function forEachOwnNodeOfFunction(fnAst, cb) {
            fnAst.body.forEachChild(function recur(node) {
                cb(node);
                if (!ts.isFunctionLike(node))
                    node.forEachChild(recur);
            });
        }
        function isValidIdentifier(name) {
            var keyword = ts.stringToToken(name);
            return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */);
        }
        function addComment(node, comment) {
            if (comment !== undefined)
                ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment);
            return node;
        }
        function anyType() {
            return ts.createKeywordTypeNode(119 /* AnyKeyword */);
        }
        function createNamespace(modifiers, name, statements) {
            return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */);
        }
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "requireInTs";
            var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); },
            });
            function doChange(changes, sourceFile, pos, program) {
                var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required;
                changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())
                    ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required)
                    : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required)));
            }
            function getInfo(sourceFile, pos) {
                var parent = ts.getTokenAtPosition(sourceFile, pos).parent;
                if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true))
                    throw ts.Debug.failBadSyntaxKind(parent);
                var decl = ts.cast(parent.parent, ts.isVariableDeclaration);
                return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] };
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixId = "useDefaultImport";
            var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, start = context.span.start;
                    var info = getInfo(sourceFile, start);
                    if (!info)
                        return undefined;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var info = getInfo(diag.file, diag.start);
                        if (info)
                            doChange(changes, diag.file, info, context.preferences);
                    });
                },
            });
            function getInfo(sourceFile, pos) {
                var name = ts.getTokenAtPosition(sourceFile, pos);
                if (!ts.isIdentifier(name))
                    return undefined; // bad input
                var parent = name.parent;
                if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
                    return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
                }
                else if (ts.isNamespaceImport(parent)) {
                    var importNode = parent.parent.parent;
                    return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
                }
            }
            function doChange(changes, sourceFile, info, preferences) {
                changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences)));
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof";
            var fixId = fixIdAddMissingTypeof;
            var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, span = context.span;
                    var importType = getImportTypeNode(sourceFile, span.start);
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); });
                    return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start));
                    });
                },
            });
            function getImportTypeNode(sourceFile, pos) {
                var token = ts.getTokenAtPosition(sourceFile, pos);
                ts.Debug.assert(token.kind === 91 /* ImportKeyword */);
                ts.Debug.assert(token.parent.kind === 181 /* ImportType */);
                return token.parent;
            }
            function doChange(changes, sourceFile, importType) {
                var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true);
                changes.replaceNode(sourceFile, importType, newTypeNode);
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var codefix;
        (function (codefix) {
            var fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
            var fixId = fixIdAddMissingTypeof;
            var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
            codefix.registerCodeFix({
                errorCodes: errorCodes,
                getCodeActions: function (context) {
                    var sourceFile = context.sourceFile, span = context.span;
                    var info = getInfo(sourceFile, span.start);
                    if (!info)
                        return undefined;
                    var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
                    var name = ts.idText(info.container.name);
                    return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])];
                },
                fixIds: [fixId],
                getAllCodeActions: function (context) {
                    return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
                        var info = getInfo(diag.file, diag.start);
                        if (info)
                            doChange(changes, diag.file, info);
                    });
                }
            });
            function getInfo(sourceFile, pos) {
                var token = ts.getTokenAtPosition(sourceFile, pos);
                var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration);
                if (ts.isClassDeclaration(indexSignature.parent))
                    return undefined;
                var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration);
                return { indexSignature: indexSignature, container: container };
            }
            function createTypeAliasFromInterface(declaration, type) {
                return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
            }
            function doChange(changes, sourceFile, _a) {
                var indexSignature = _a.indexSignature, container = _a.container;
                var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members;
                var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); });
                var parameter = ts.first(indexSignature.parameters);
                var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type);
                var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type);
                var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([
                    mappedIntersectionType
                ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray)));
                changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
            }
        })(codefix = ts.codefix || (ts.codefix = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var refactor;
        (function (refactor) {
            var refactorName = "Convert export";
            var actionNameDefaultToNamed = "Convert default export to named export";
            var actionNameNamedToDefault = "Convert named export to default export";
            refactor.registerRefactor(refactorName, {
                getAvailableActions: function (context) {
                    var info = getInfo(context);
                    if (!info)
                        return undefined;
                    var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message;
                    var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault;
                    return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
                },
                getEditsForAction: function (context, actionName) {
                    ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault);
                    var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); });
                    return { edits: edits, renameFilename: undefined, renameLocation: undefined };
                },
            });
            function getInfo(context) {
                var file = context.file;
                var span = ts.getRefactorContextSpan(context);
                var token = ts.getTokenAtPosition(file, span.start);
                var exportNode = ts.getParentNodeInSpan(token, file, span);
                if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) {
                    return undefined;
                }
                var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol;
                var flags = ts.getModifierFlags(exportNode);
                var wasDefault = !!(flags & 512 /* Default */);
                // If source file already has a default export, don't offer refactor.
                if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) {
                    return undefined;
                }
                switch (exportNode.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 242 /* ModuleDeclaration */: {
                        var node = exportNode;
                        return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
                    }
                    case 217 /* VariableStatement */: {
                        var vs = exportNode;
                        // Must be `export const x = something;`.
                        if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) {
                            return undefined;
                        }
                        var decl = ts.first(vs.declarationList.declarations);
                        if (!decl.initializer)
                            return undefined;
                        ts.Debug.assert(!wasDefault);
                        return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
                    }
                    default:
                        return undefined;
                }
            }
            function doChange(exportingSourceFile, program, info, changes, cancellationToken) {
                changeExport(exportingSourceFile, info, changes, program.getTypeChecker());
                changeImports(program, info, changes, cancellationToken);
            }
            function changeExport(exportingSourceFile, _a, changes, checker) {
                var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName;
                if (wasDefault) {
                    changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */)));
                }
                else {
                    var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */));
                    switch (exportNode.kind) {
                        case 237 /* FunctionDeclaration */:
                        case 238 /* ClassDeclaration */:
                        case 239 /* InterfaceDeclaration */:
                            changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */));
                            break;
                        case 217 /* VariableStatement */:
                            // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;`
                            if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) {
                                // We checked in `getInfo` that an initializer exists.
                                changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer)));
                                break;
                            }
                        // falls through
                        case 241 /* EnumDeclaration */:
                        case 240 /* TypeAliasDeclaration */:
                        case 242 /* ModuleDeclaration */:
                            // `export type T = number;` -> `type T = number; export default T;`
                            changes.deleteModifier(exportingSourceFile, exportKeyword);
                            changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text)));
                            break;
                        default:
                            ts.Debug.assertNever(exportNode);
                    }
                }
            }
            function changeImports(program, _a, changes, cancellationToken) {
                var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol;
                var checker = program.getTypeChecker();
                var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName));
                ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) {
                    var importingSourceFile = ref.getSourceFile();
                    if (wasDefault) {
                        changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text);
                    }
                    else {
                        changeNamedToDefaultImport(importingSourceFile, ref, changes);
                    }
                });
            }
            function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) {
                var parent = ref.parent;
                switch (parent.kind) {
                    case 187 /* PropertyAccessExpression */:
                        // `a.default` --> `a.foo`
                        changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName));
                        break;
                    case 251 /* ImportSpecifier */:
                    case 255 /* ExportSpecifier */: {
                        var spec = parent;
                        // `default as foo` --> `foo`, `default as bar` --> `foo as bar`
                        changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text));
                        break;
                    }
                    case 248 /* ImportClause */: {
                        var clause = parent;
                        ts.Debug.assert(clause.name === ref);
                        var spec = makeImportSpecifier(exportName, ref.text);
                        var namedBindings = clause.namedBindings;
                        if (!namedBindings) {
                            // `import foo from "./a";` --> `import { foo } from "./a";`
                            changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec]));
                        }
                        else if (namedBindings.kind === 249 /* NamespaceImport */) {
                            // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";`
                            changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) });
                            var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */;
                            var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference);
                            changes.insertNodeAfter(importingSourceFile, clause.parent, newImport);
                        }
                        else {
                            // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";`
                            changes.delete(importingSourceFile, ref);
                            changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec);
                        }
                        break;
                    }
                    default:
                        ts.Debug.failBadSyntaxKind(parent);
                }
            }
            function changeNamedToDefaultImport(importingSourceFile, ref, changes) {
                var parent = ref.parent;
                switch (parent.kind) {
                    case 187 /* PropertyAccessExpression */:
                        // `a.foo` --> `a.default`
                        changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default"));
                        break;
                    case 251 /* ImportSpecifier */:
                    case 255 /* ExportSpecifier */: {
                        var spec = parent;
                        if (spec.kind === 251 /* ImportSpecifier */) {
                            // `import { foo } from "./a";` --> `import foo from "./a";`
                            // `import { foo as bar } from "./a";` --> `import bar from "./a";`
                            var defaultImport = ts.createIdentifier(spec.name.text);
                            if (spec.parent.elements.length === 1) {
                                changes.replaceNode(importingSourceFile, spec.parent, defaultImport);
                            }
                            else {
                                changes.delete(importingSourceFile, spec);
                                changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport);
                            }
                        }
                        else {
                            // `export { foo } from "./a";` --> `export { default as foo } from "./a";`
                            // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";`
                            // `export { foo as default } from "./a";` --> `export { default } from "./a";`
                            // (Because `export foo from "./a";` isn't valid syntax.)
                            changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text));
                        }
                        break;
                    }
                    default:
                        ts.Debug.failBadSyntaxKind(parent);
                }
            }
            function makeImportSpecifier(propertyName, name) {
                return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
            }
            function makeExportSpecifier(propertyName, name) {
                return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
            }
        })(refactor = ts.refactor || (ts.refactor = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var refactor;
        (function (refactor) {
            var refactorName = "Convert import";
            var actionNameNamespaceToNamed = "Convert namespace import to named imports";
            var actionNameNamedToNamespace = "Convert named imports to namespace import";
            refactor.registerRefactor(refactorName, {
                getAvailableActions: function (context) {
                    var i = getImportToConvert(context);
                    if (!i)
                        return undefined;
                    var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message;
                    var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace;
                    return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
                },
                getEditsForAction: function (context, actionName) {
                    ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace);
                    var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); });
                    return { edits: edits, renameFilename: undefined, renameLocation: undefined };
                }
            });
            // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`.
            function getImportToConvert(context) {
                var file = context.file;
                var span = ts.getRefactorContextSpan(context);
                var token = ts.getTokenAtPosition(file, span.start);
                var importDecl = ts.getParentNodeInSpan(token, file, span);
                if (!importDecl || !ts.isImportDeclaration(importDecl))
                    return undefined;
                var importClause = importDecl.importClause;
                return importClause && importClause.namedBindings;
            }
            function doChange(sourceFile, program, changes, toConvert) {
                var checker = program.getTypeChecker();
                if (toConvert.kind === 249 /* NamespaceImport */) {
                    doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()));
                }
                else {
                    doChangeNamedToNamespace(sourceFile, checker, changes, toConvert);
                }
            }
            function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
                var usedAsNamespaceOrDefault = false;
                var nodesToReplace = [];
                var conflictingNames = ts.createMap();
                ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) {
                    if (!ts.isPropertyAccessExpression(id.parent)) {
                        usedAsNamespaceOrDefault = true;
                    }
                    else {
                        var parent = ts.cast(id.parent, ts.isPropertyAccessExpression);
                        var exportName = parent.name.text;
                        if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) {
                            conflictingNames.set(exportName, true);
                        }
                        ts.Debug.assert(parent.expression === id);
                        nodesToReplace.push(parent);
                    }
                });
                // We may need to change `mod.x` to `_x` to avoid a name conflict.
                var exportNameToImportName = ts.createMap();
                for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) {
                    var propertyAccess = nodesToReplace_1[_i];
                    var exportName = propertyAccess.name.text;
                    var importName = exportNameToImportName.get(exportName);
                    if (importName === undefined) {
                        exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName);
                    }
                    changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName));
                }
                var importSpecifiers = [];
                exportNameToImportName.forEach(function (name, propertyName) {
                    importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)));
                });
                var importDecl = toConvert.parent.parent;
                if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) {
                    // Need to leave the namespace import alone
                    changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers));
                }
                else {
                    changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers));
                }
            }
            function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) {
                var importDecl = toConvert.parent.parent;
                var moduleSpecifier = importDecl.moduleSpecifier;
                var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module";
                var namespaceNameConflicts = toConvert.elements.some(function (element) {
                    return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
                        return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true);
                    }) || false;
                });
                var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
                var neededNamedImports = [];
                var _loop_20 = function (element) {
                    var propertyName = (element.propertyName || element.name).text;
                    ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
                        var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
                        if (ts.isShorthandPropertyAssignment(id.parent)) {
                            changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access));
                        }
                        else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) {
                            if (!neededNamedImports.some(function (n) { return n.name === element.name; })) {
                                neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text)));
                            }
                        }
                        else {
                            changes.replaceNode(sourceFile, id, access);
                        }
                    });
                };
                for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
                    var element = _a[_i];
                    _loop_20(element);
                }
                changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
                if (neededNamedImports.length) {
                    changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports));
                }
            }
            function updateImport(old, defaultImportName, elements) {
                return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier);
            }
        })(refactor = ts.refactor || (ts.refactor = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var refactor;
        (function (refactor) {
            var extractSymbol;
            (function (extractSymbol) {
                var refactorName = "Extract Symbol";
                refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction });
                /**
                 * Compute the associated code actions
                 * Exported for tests.
                 */
                function getAvailableActions(context) {
                    var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
                    var targetRange = rangeToExtract.targetRange;
                    if (targetRange === undefined) {
                        return undefined;
                    }
                    var extractions = getPossibleExtractions(targetRange, context);
                    if (extractions === undefined) {
                        // No extractions possible
                        return undefined;
                    }
                    var functionActions = [];
                    var usedFunctionNames = ts.createMap();
                    var constantActions = [];
                    var usedConstantNames = ts.createMap();
                    var i = 0;
                    for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) {
                        var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction;
                        // Skip these since we don't have a way to report errors yet
                        if (functionExtraction.errors.length === 0) {
                            // Don't issue refactorings with duplicated names.
                            // Scopes come back in "innermost first" order, so extractions will
                            // preferentially go into nearer scopes
                            var description = functionExtraction.description;
                            if (!usedFunctionNames.has(description)) {
                                usedFunctionNames.set(description, true);
                                functionActions.push({
                                    description: description,
                                    name: "function_scope_" + i
                                });
                            }
                        }
                        // Skip these since we don't have a way to report errors yet
                        if (constantExtraction.errors.length === 0) {
                            // Don't issue refactorings with duplicated names.
                            // Scopes come back in "innermost first" order, so extractions will
                            // preferentially go into nearer scopes
                            var description = constantExtraction.description;
                            if (!usedConstantNames.has(description)) {
                                usedConstantNames.set(description, true);
                                constantActions.push({
                                    description: description,
                                    name: "constant_scope_" + i
                                });
                            }
                        }
                        // *do* increment i anyway because we'll look for the i-th scope
                        // later when actually doing the refactoring if the user requests it
                        i++;
                    }
                    var infos = [];
                    if (functionActions.length) {
                        infos.push({
                            name: refactorName,
                            description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
                            actions: functionActions
                        });
                    }
                    if (constantActions.length) {
                        infos.push({
                            name: refactorName,
                            description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant),
                            actions: constantActions
                        });
                    }
                    return infos.length ? infos : undefined;
                }
                extractSymbol.getAvailableActions = getAvailableActions;
                /* Exported for tests */
                function getEditsForAction(context, actionName) {
                    var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
                    var targetRange = rangeToExtract.targetRange; // TODO:GH#18217
                    var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
                    if (parsedFunctionIndexMatch) {
                        var index = +parsedFunctionIndexMatch[1];
                        ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index");
                        return getFunctionExtractionAtIndex(targetRange, context, index);
                    }
                    var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName);
                    if (parsedConstantIndexMatch) {
                        var index = +parsedConstantIndexMatch[1];
                        ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index");
                        return getConstantExtractionAtIndex(targetRange, context, index);
                    }
                    ts.Debug.fail("Unrecognized action name");
                }
                extractSymbol.getEditsForAction = getEditsForAction;
                // Move these into diagnostic messages if they become user-facing
                var Messages;
                (function (Messages) {
                    function createMessage(message) {
                        return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message };
                    }
                    Messages.cannotExtractRange = createMessage("Cannot extract range.");
                    Messages.cannotExtractImport = createMessage("Cannot extract import statement.");
                    Messages.cannotExtractSuper = createMessage("Cannot extract super call.");
                    Messages.cannotExtractEmpty = createMessage("Cannot extract empty range.");
                    Messages.expressionExpected = createMessage("expression expected.");
                    Messages.uselessConstantType = createMessage("No reason to extract constant of type.");
                    Messages.statementOrExpressionExpected = createMessage("Statement or expression expected.");
                    Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements.");
                    Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement.");
                    Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
                    Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
                    Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
                    Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
                    Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier.");
                    Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
                    Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
                    Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
                    Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
                    Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
                    Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function");
                    Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
                    Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
                })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {}));
                var RangeFacts;
                (function (RangeFacts) {
                    RangeFacts[RangeFacts["None"] = 0] = "None";
                    RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn";
                    RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator";
                    RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction";
                    RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis";
                    /**
                     * The range is in a function which needs the 'static' modifier in a class
                     */
                    RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion";
                })(RangeFacts || (RangeFacts = {}));
                /**
                 * getRangeToExtract takes a span inside a text file and returns either an expression or an array
                 * of statements representing the minimum set of nodes needed to extract the entire span. This
                 * process may fail, in which case a set of errors is returned instead (these are currently
                 * not shown to the user, but can be used by us diagnostically)
                 */
                // exported only for tests
                function getRangeToExtract(sourceFile, span) {
                    var length = span.length;
                    if (length === 0) {
                        return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] };
                    }
                    // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.
                    // This may fail (e.g. you select two statements in the root of a source file)
                    var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span);
                    // Do the same for the ending position
                    var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span);
                    var declarations = [];
                    // We'll modify these flags as we walk the tree to collect data
                    // about what things need to be done as part of the extraction.
                    var rangeFacts = RangeFacts.None;
                    if (!start || !end) {
                        // cannot find either start or end node
                        return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
                    }
                    if (start.parent !== end.parent) {
                        // start and end nodes belong to different subtrees
                        return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
                    }
                    if (start !== end) {
                        // start and end should be statements and parent should be either block or a source file
                        if (!isBlockLike(start.parent)) {
                            return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
                        }
                        var statements = [];
                        var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248
                        for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) {
                            var statement = _a[_i];
                            if (statement === start || statements.length) {
                                var errors_1 = checkNode(statement);
                                if (errors_1) {
                                    return { errors: errors_1 };
                                }
                                statements.push(statement);
                            }
                            if (statement === end) {
                                break;
                            }
                        }
                        if (!statements.length) {
                            // https://github.com/Microsoft/TypeScript/issues/20559
                            // Ranges like [|case 1: break;|] will fail to populate `statements` because
                            // they will never find `start` in `start.parent.statements`.
                            // Consider: We could support ranges like [|case 1:|] by refining them to just
                            // the expression.
                            return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
                        }
                        return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } };
                    }
                    if (ts.isReturnStatement(start) && !start.expression) {
                        // Makes no sense to extract an expression-less return statement.
                        return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
                    }
                    // We have a single node (start)
                    var node = refineNode(start);
                    var errors = checkRootNode(node) || checkNode(node);
                    if (errors) {
                        return { errors: errors };
                    }
                    return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217
                    /**
                     * Attempt to refine the extraction node (generally, by shrinking it) to produce better results.
                     * @param node The unrefined extraction node.
                     */
                    function refineNode(node) {
                        if (ts.isReturnStatement(node)) {
                            if (node.expression) {
                                return node.expression;
                            }
                        }
                        else if (ts.isVariableStatement(node)) {
                            var numInitializers = 0;
                            var lastInitializer = void 0;
                            for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
                                var declaration = _a[_i];
                                if (declaration.initializer) {
                                    numInitializers++;
                                    lastInitializer = declaration.initializer;
                                }
                            }
                            if (numInitializers === 1) {
                                return lastInitializer;
                            }
                            // No special handling if there are multiple initializers.
                        }
                        else if (ts.isVariableDeclaration(node)) {
                            if (node.initializer) {
                                return node.initializer;
                            }
                        }
                        return node;
                    }
                    function checkRootNode(node) {
                        if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) {
                            return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)];
                        }
                        return undefined;
                    }
                    function checkForStaticContext(nodeToCheck, containingClass) {
                        var current = nodeToCheck;
                        while (current !== containingClass) {
                            if (current.kind === 152 /* PropertyDeclaration */) {
                                if (ts.hasModifier(current, 32 /* Static */)) {
                                    rangeFacts |= RangeFacts.InStaticRegion;
                                }
                                break;
                            }
                            else if (current.kind === 149 /* Parameter */) {
                                var ctorOrMethod = ts.getContainingFunction(current);
                                if (ctorOrMethod.kind === 155 /* Constructor */) {
                                    rangeFacts |= RangeFacts.InStaticRegion;
                                }
                                break;
                            }
                            else if (current.kind === 154 /* MethodDeclaration */) {
                                if (ts.hasModifier(current, 32 /* Static */)) {
                                    rangeFacts |= RangeFacts.InStaticRegion;
                                }
                            }
                            current = current.parent;
                        }
                    }
                    // Verifies whether we can actually extract this node or not.
                    function checkNode(nodeToCheck) {
                        var PermittedJumps;
                        (function (PermittedJumps) {
                            PermittedJumps[PermittedJumps["None"] = 0] = "None";
                            PermittedJumps[PermittedJumps["Break"] = 1] = "Break";
                            PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue";
                            PermittedJumps[PermittedJumps["Return"] = 4] = "Return";
                        })(PermittedJumps || (PermittedJumps = {}));
                        // We believe it's true because the node is from the (unmodified) tree.
                        ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
                        // For understanding how skipTrivia functioned:
                        ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
                        if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) {
                            return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
                        }
                        if (nodeToCheck.flags & 4194304 /* Ambient */) {
                            return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
                        }
                        // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default)
                        var containingClass = ts.getContainingClass(nodeToCheck);
                        if (containingClass) {
                            checkForStaticContext(nodeToCheck, containingClass);
                        }
                        var errors;
                        var permittedJumps = 4 /* Return */;
                        var seenLabels;
                        visit(nodeToCheck);
                        return errors;
                        function visit(node) {
                            if (errors) {
                                // already found an error - can stop now
                                return true;
                            }
                            if (ts.isDeclaration(node)) {
                                var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node;
                                if (ts.hasModifier(declaringNode, 1 /* Export */)) {
                                    // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`)
                                    // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`!
                                    // Also TODO: GH#19956
                                    (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity));
                                    return true;
                                }
                                declarations.push(node.symbol);
                            }
                            // Some things can't be extracted in certain situations
                            switch (node.kind) {
                                case 247 /* ImportDeclaration */:
                                    (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport));
                                    return true;
                                case 97 /* SuperKeyword */:
                                    // For a super *constructor call*, we have to be extracting the entire class,
                                    // but a super *method call* simply implies a 'this' reference
                                    if (node.parent.kind === 189 /* CallExpression */) {
                                        // Super constructor call
                                        var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217
                                        if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) {
                                            (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper));
                                            return true;
                                        }
                                    }
                                    else {
                                        rangeFacts |= RangeFacts.UsesThis;
                                    }
                                    break;
                            }
                            if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) {
                                switch (node.kind) {
                                    case 237 /* FunctionDeclaration */:
                                    case 238 /* ClassDeclaration */:
                                        if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
                                            // You cannot extract global declarations
                                            (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
                                        }
                                        break;
                                }
                                // do not dive into functions or classes
                                return false;
                            }
                            var savedPermittedJumps = permittedJumps;
                            switch (node.kind) {
                                case 220 /* IfStatement */:
                                    permittedJumps = 0 /* None */;
                                    break;
                                case 233 /* TryStatement */:
                                    // forbid all jumps inside try blocks
                                    permittedJumps = 0 /* None */;
                                    break;
                                case 216 /* Block */:
                                    if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) {
                                        // allow unconditional returns from finally blocks
                                        permittedJumps = 4 /* Return */;
                                    }
                                    break;
                                case 269 /* CaseClause */:
                                    // allow unlabeled break inside case clauses
                                    permittedJumps |= 1 /* Break */;
                                    break;
                                default:
                                    if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) {
                                        // allow unlabeled break/continue inside loops
                                        permittedJumps |= 1 /* Break */ | 2 /* Continue */;
                                    }
                                    break;
                            }
                            switch (node.kind) {
                                case 176 /* ThisType */:
                                case 99 /* ThisKeyword */:
                                    rangeFacts |= RangeFacts.UsesThis;
                                    break;
                                case 231 /* LabeledStatement */:
                                    {
                                        var label = node.label;
                                        (seenLabels || (seenLabels = [])).push(label.escapedText);
                                        ts.forEachChild(node, visit);
                                        seenLabels.pop();
                                        break;
                                    }
                                case 227 /* BreakStatement */:
                                case 226 /* ContinueStatement */:
                                    {
                                        var label = node.label;
                                        if (label) {
                                            if (!ts.contains(seenLabels, label.escapedText)) {
                                                // attempts to jump to label that is not in range to be extracted
                                                (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
                                            }
                                        }
                                        else {
                                            if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
                                                // attempt to break or continue in a forbidden context
                                                (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
                                            }
                                        }
                                        break;
                                    }
                                case 199 /* AwaitExpression */:
                                    rangeFacts |= RangeFacts.IsAsyncFunction;
                                    break;
                                case 205 /* YieldExpression */:
                                    rangeFacts |= RangeFacts.IsGenerator;
                                    break;
                                case 228 /* ReturnStatement */:
                                    if (permittedJumps & 4 /* Return */) {
                                        rangeFacts |= RangeFacts.HasReturn;
                                    }
                                    else {
                                        (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement));
                                    }
                                    break;
                                default:
                                    ts.forEachChild(node, visit);
                                    break;
                            }
                            permittedJumps = savedPermittedJumps;
                        }
                    }
                }
                extractSymbol.getRangeToExtract = getRangeToExtract;
                function getStatementOrExpressionRange(node) {
                    if (ts.isStatement(node)) {
                        return [node];
                    }
                    else if (ts.isExpressionNode(node)) {
                        // If our selection is the expression in an ExpressionStatement, expand
                        // the selection to include the enclosing Statement (this stops us
                        // from trying to care about the return value of the extracted function
                        // and eliminates double semicolon insertion in certain scenarios)
                        return ts.isExpressionStatement(node.parent) ? [node.parent] : node;
                    }
                    return undefined;
                }
                function isScope(node) {
                    return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node);
                }
                /**
                 * Computes possible places we could extract the function into. For example,
                 * you may be able to extract into a class method *or* local closure *or* namespace function,
                 * depending on what's in the extracted body.
                 */
                function collectEnclosingScopes(range) {
                    var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
                    if (range.facts & RangeFacts.UsesThis) {
                        // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class
                        var containingClass = ts.getContainingClass(current);
                        if (containingClass) {
                            var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration);
                            return containingFunction
                                ? [containingFunction, containingClass]
                                : [containingClass];
                        }
                    }
                    var scopes = [];
                    while (true) {
                        current = current.parent;
                        // A function parameter's initializer is actually in the outer scope, not the function declaration
                        if (current.kind === 149 /* Parameter */) {
                            // Skip all the way to the outer scope of the function that declared this parameter
                            current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent;
                        }
                        // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of.
                        // Walk up to the closest parent of a place where we can logically put a sibling:
                        //  * Function declaration
                        //  * Class declaration or expression
                        //  * Module/namespace or source file
                        if (isScope(current)) {
                            scopes.push(current);
                            if (current.kind === 277 /* SourceFile */) {
                                return scopes;
                            }
                        }
                    }
                }
                function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) {
                    var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
                    ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
                    context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217
                    return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
                }
                function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) {
                    var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
                    ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
                    ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
                    context.cancellationToken.throwIfCancellationRequested();
                    var expression = ts.isExpression(target)
                        ? target
                        : target.statements[0].expression;
                    return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context);
                }
                /**
                 * Given a piece of text to extract ('targetRange'), computes a list of possible extractions.
                 * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes
                 * or an error explaining why we can't extract into that scope.
                 */
                function getPossibleExtractions(targetRange, context) {
                    var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope;
                    // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547
                    var extractions = scopes.map(function (scope, i) {
                        var functionDescriptionPart = getDescriptionForFunctionInScope(scope);
                        var constantDescriptionPart = getDescriptionForConstantInScope(scope);
                        var scopeDescription = ts.isFunctionLikeDeclaration(scope)
                            ? getDescriptionForFunctionLikeDeclaration(scope)
                            : ts.isClassLike(scope)
                                ? getDescriptionForClassLikeDeclaration(scope)
                                : getDescriptionForModuleLikeDeclaration(scope);
                        var functionDescription;
                        var constantDescription;
                        if (scopeDescription === 1 /* Global */) {
                            functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]);
                            constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]);
                        }
                        else if (scopeDescription === 0 /* Module */) {
                            functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]);
                            constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]);
                        }
                        else {
                            functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]);
                            constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]);
                        }
                        // Customize the phrasing for the innermost scope to increase clarity.
                        if (i === 0 && !ts.isClassLike(scope)) {
                            constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]);
                        }
                        return {
                            functionExtraction: {
                                description: functionDescription,
                                errors: functionErrorsPerScope[i],
                            },
                            constantExtraction: {
                                description: constantDescription,
                                errors: constantErrorsPerScope[i],
                            },
                        };
                    });
                    return extractions;
                }
                function getPossibleExtractionsWorker(targetRange, context) {
                    var sourceFile = context.file;
                    var scopes = collectEnclosingScopes(targetRange);
                    var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile);
                    var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken);
                    return { scopes: scopes, readsAndWrites: readsAndWrites };
                }
                function getDescriptionForFunctionInScope(scope) {
                    return ts.isFunctionLikeDeclaration(scope)
                        ? "inner function"
                        : ts.isClassLike(scope)
                            ? "method"
                            : "function";
                }
                function getDescriptionForConstantInScope(scope) {
                    return ts.isClassLike(scope)
                        ? "readonly field"
                        : "constant";
                }
                function getDescriptionForFunctionLikeDeclaration(scope) {
                    switch (scope.kind) {
                        case 155 /* Constructor */:
                            return "constructor";
                        case 194 /* FunctionExpression */:
                        case 237 /* FunctionDeclaration */:
                            return scope.name
                                ? "function '" + scope.name.text + "'"
                                : "anonymous function";
                        case 195 /* ArrowFunction */:
                            return "arrow function";
                        case 154 /* MethodDeclaration */:
                            return "method '" + scope.name.getText();
                        case 156 /* GetAccessor */:
                            return "'get " + scope.name.getText() + "'";
                        case 157 /* SetAccessor */:
                            return "'set " + scope.name.getText() + "'";
                        default:
                            throw ts.Debug.assertNever(scope);
                    }
                }
                function getDescriptionForClassLikeDeclaration(scope) {
                    return scope.kind === 238 /* ClassDeclaration */
                        ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration"
                        : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression";
                }
                function getDescriptionForModuleLikeDeclaration(scope) {
                    return scope.kind === 243 /* ModuleBlock */
                        ? "namespace '" + scope.parent.name.getText() + "'"
                        : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */;
                }
                var SpecialScope;
                (function (SpecialScope) {
                    SpecialScope[SpecialScope["Module"] = 0] = "Module";
                    SpecialScope[SpecialScope["Global"] = 1] = "Global";
                })(SpecialScope || (SpecialScope = {}));
                /**
                 * Result of 'extractRange' operation for a specific scope.
                 * Stores either a list of changes that should be applied to extract a range or a list of errors
                 */
                function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) {
                    var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions;
                    var checker = context.program.getTypeChecker();
                    // Make a unique name for the extracted function
                    var file = scope.getSourceFile();
                    var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file);
                    var isJS = ts.isInJSFile(scope);
                    var functionName = ts.createIdentifier(functionNameText);
                    var returnType;
                    var parameters = [];
                    var callArguments = [];
                    var writes;
                    usagesInScope.forEach(function (usage, name) {
                        var typeNode;
                        if (!isJS) {
                            var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
                            // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
                            type = checker.getBaseTypeOfLiteralType(type);
                            typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */);
                        }
                        var paramDecl = ts.createParameter(
                        /*decorators*/ undefined, 
                        /*modifiers*/ undefined, 
                        /*dotDotDotToken*/ undefined, 
                        /*name*/ name, 
                        /*questionToken*/ undefined, typeNode);
                        parameters.push(paramDecl);
                        if (usage.usage === 2 /* Write */) {
                            (writes || (writes = [])).push(usage);
                        }
                        callArguments.push(ts.createIdentifier(name));
                    });
                    var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); });
                    var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder);
                    var typeParameters = sortedTypeParametersAndDeclarations.length === 0
                        ? undefined
                        : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; });
                    // Strictly speaking, we should check whether each name actually binds to the appropriate type
                    // parameter.  In cases of shadowing, they may not.
                    var callTypeArguments = typeParameters !== undefined
                        ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); })
                        : undefined;
                    // Provide explicit return types for contextually-typed functions
                    // to avoid problems when there are literal types present
                    if (ts.isExpression(node) && !isJS) {
                        var contextualType = checker.getContextualType(node);
                        returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217
                    }
                    var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty;
                    ts.suppressLeadingAndTrailingTrivia(body);
                    var newFunction;
                    if (ts.isClassLike(scope)) {
                        // always create private method in TypeScript files
                        var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)];
                        if (range.facts & RangeFacts.InStaticRegion) {
                            modifiers.push(ts.createToken(115 /* StaticKeyword */));
                        }
                        if (range.facts & RangeFacts.IsAsyncFunction) {
                            modifiers.push(ts.createToken(120 /* AsyncKeyword */));
                        }
                        newFunction = ts.createMethod(
                        /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, 
                        /*questionToken*/ undefined, typeParameters, parameters, returnType, body);
                    }
                    else {
                        newFunction = ts.createFunctionDeclaration(
                        /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body);
                    }
                    var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
                    var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end;
                    var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope);
                    if (nodeToInsertBefore) {
                        changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true);
                    }
                    else {
                        changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction);
                    }
                    var newNodes = [];
                    // replace range with function call
                    var called = getCalledExpression(scope, range, functionNameText);
                    var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference
                    callArguments);
                    if (range.facts & RangeFacts.IsGenerator) {
                        call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call);
                    }
                    if (range.facts & RangeFacts.IsAsyncFunction) {
                        call = ts.createAwait(call);
                    }
                    if (exposedVariableDeclarations.length && !writes) {
                        // No need to mix declarations and writes.
                        // How could any variables be exposed if there's a return statement?
                        ts.Debug.assert(!returnValueProperty);
                        ts.Debug.assert(!(range.facts & RangeFacts.HasReturn));
                        if (exposedVariableDeclarations.length === 1) {
                            // Declaring exactly one variable: let x = newFunction();
                            var variableDeclaration = exposedVariableDeclarations[0];
                            newNodes.push(ts.createVariableStatement(
                            /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns
                            variableDeclaration.parent.flags)));
                        }
                        else {
                            // Declaring multiple variables / return properties:
                            //   let {x, y} = newFunction();
                            var bindingElements = [];
                            var typeElements = [];
                            var commonNodeFlags = exposedVariableDeclarations[0].parent.flags;
                            var sawExplicitType = false;
                            for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) {
                                var variableDeclaration = exposedVariableDeclarations_1[_i];
                                bindingElements.push(ts.createBindingElement(
                                /*dotDotDotToken*/ undefined, 
                                /*propertyName*/ undefined, 
                                /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name)));
                                // Being returned through an object literal will have widened the type.
                                var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */);
                                typeElements.push(ts.createPropertySignature(
                                /*modifiers*/ undefined, 
                                /*name*/ variableDeclaration.symbol.name, 
                                /*questionToken*/ undefined, 
                                /*type*/ variableType, 
                                /*initializer*/ undefined));
                                sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined;
                                commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags;
                            }
                            var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined;
                            if (typeLiteral) {
                                ts.setEmitFlags(typeLiteral, 1 /* SingleLine */);
                            }
                            newNodes.push(ts.createVariableStatement(
                            /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), 
                                /*type*/ typeLiteral, 
                                /*initializer*/ call)], commonNodeFlags)));
                        }
                    }
                    else if (exposedVariableDeclarations.length || writes) {
                        if (exposedVariableDeclarations.length) {
                            // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping.
                            for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) {
                                var variableDeclaration = exposedVariableDeclarations_2[_c];
                                var flags = variableDeclaration.parent.flags;
                                if (flags & 2 /* Const */) {
                                    flags = (flags & ~2 /* Const */) | 1 /* Let */;
                                }
                                newNodes.push(ts.createVariableStatement(
                                /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags)));
                            }
                        }
                        if (returnValueProperty) {
                            // has both writes and return, need to create variable declaration to hold return value;
                            newNodes.push(ts.createVariableStatement(
                            /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */)));
                        }
                        var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
                        if (returnValueProperty) {
                            assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty));
                        }
                        // propagate writes back
                        if (assignments.length === 1) {
                            // We would only have introduced a return value property if there had been
                            // other assignments to make.
                            ts.Debug.assert(!returnValueProperty);
                            newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call)));
                            if (range.facts & RangeFacts.HasReturn) {
                                newNodes.push(ts.createReturn());
                            }
                        }
                        else {
                            // emit e.g.
                            //   { a, b, __return } = newFunction(a, b);
                            //   return __return;
                            newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call)));
                            if (returnValueProperty) {
                                newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty)));
                            }
                        }
                    }
                    else {
                        if (range.facts & RangeFacts.HasReturn) {
                            newNodes.push(ts.createReturn(call));
                        }
                        else if (isReadonlyArray(range.range)) {
                            newNodes.push(ts.createStatement(call));
                        }
                        else {
                            newNodes.push(call);
                        }
                    }
                    if (isReadonlyArray(range.range)) {
                        changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes);
                    }
                    else {
                        changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes);
                    }
                    var edits = changeTracker.getChanges();
                    var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
                    var renameFilename = renameRange.getSourceFile().fileName;
                    var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false);
                    return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
                    function getTypeDeepCloneUnionUndefined(typeNode) {
                        if (typeNode === undefined) {
                            return undefined;
                        }
                        var clone = ts.getSynthesizedDeepClone(typeNode);
                        var withoutParens = clone;
                        while (ts.isParenthesizedTypeNode(withoutParens)) {
                            withoutParens = withoutParens.type;
                        }
                        return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 140 /* UndefinedKeyword */; })
                            ? clone
                            : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(140 /* UndefinedKeyword */)]);
                    }
                }
                /**
                 * Result of 'extractRange' operation for a specific scope.
                 * Stores either a list of changes that should be applied to extract a range or a list of errors
                 */
                function extractConstantInScope(node, scope, _a, rangeFacts, context) {
                    var substitutions = _a.substitutions;
                    var checker = context.program.getTypeChecker();
                    // Make a unique name for the extracted variable
                    var file = scope.getSourceFile();
                    var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file);
                    var isJS = ts.isInJSFile(scope);
                    var variableType = isJS || !checker.isContextSensitive(node)
                        ? undefined
                        : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217
                    var initializer = transformConstantInitializer(node, substitutions);
                    ts.suppressLeadingAndTrailingTrivia(initializer);
                    var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
                    if (ts.isClassLike(scope)) {
                        ts.Debug.assert(!isJS); // See CannotExtractToJSClass
                        var modifiers = [];
                        modifiers.push(ts.createToken(112 /* PrivateKeyword */));
                        if (rangeFacts & RangeFacts.InStaticRegion) {
                            modifiers.push(ts.createToken(115 /* StaticKeyword */));
                        }
                        modifiers.push(ts.createToken(132 /* ReadonlyKeyword */));
                        var newVariable = ts.createProperty(
                        /*decorators*/ undefined, modifiers, localNameText, 
                        /*questionToken*/ undefined, variableType, initializer);
                        var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion
                            ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217
                            : ts.createThis(), ts.createIdentifier(localNameText));
                        // Declare
                        var maxInsertionPos = node.pos;
                        var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope);
                        changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true);
                        // Consume
                        changeTracker.replaceNode(context.file, node, localReference);
                    }
                    else {
                        var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer);
                        // If the node is part of an initializer in a list of variable declarations, insert a new
                        // variable declaration into the list (in case it depends on earlier ones).
                        // CONSIDER: If the declaration list isn't const, we might want to split it into multiple
                        // lists so that the newly extracted one can be const.
                        var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope);
                        if (oldVariableDeclaration) {
                            // Declare
                            // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`)
                            changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration);
                            // Consume
                            var localReference = ts.createIdentifier(localNameText);
                            changeTracker.replaceNode(context.file, node, localReference);
                        }
                        else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) {
                            // If the parent is an expression statement and the target scope is the immediately enclosing one,
                            // replace the statement with the declaration.
                            var newVariableStatement = ts.createVariableStatement(
                            /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
                            changeTracker.replaceNode(context.file, node.parent, newVariableStatement);
                        }
                        else {
                            var newVariableStatement = ts.createVariableStatement(
                            /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
                            // Declare
                            var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope);
                            if (nodeToInsertBefore.pos === 0) {
                                changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false);
                            }
                            else {
                                changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false);
                            }
                            // Consume
                            if (node.parent.kind === 219 /* ExpressionStatement */) {
                                // If the parent is an expression statement, delete it.
                                changeTracker.delete(context.file, node.parent);
                            }
                            else {
                                var localReference = ts.createIdentifier(localNameText);
                                changeTracker.replaceNode(context.file, node, localReference);
                            }
                        }
                    }
                    var edits = changeTracker.getChanges();
                    var renameFilename = node.getSourceFile().fileName;
                    var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true);
                    return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
                }
                function getContainingVariableDeclarationIfInList(node, scope) {
                    var prevNode;
                    while (node !== undefined && node !== scope) {
                        if (ts.isVariableDeclaration(node) &&
                            node.initializer === prevNode &&
                            ts.isVariableDeclarationList(node.parent) &&
                            node.parent.declarations.length > 1) {
                            return node;
                        }
                        prevNode = node;
                        node = node.parent;
                    }
                }
                function getFirstDeclaration(type) {
                    var firstDeclaration;
                    var symbol = type.symbol;
                    if (symbol && symbol.declarations) {
                        for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                            var declaration = _a[_i];
                            if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) {
                                firstDeclaration = declaration;
                            }
                        }
                    }
                    return firstDeclaration;
                }
                function compareTypesByDeclarationOrder(_a, _b) {
                    var type1 = _a.type, declaration1 = _a.declaration;
                    var type2 = _b.type, declaration2 = _b.declaration;
                    return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues)
                        || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "")
                        || ts.compareValues(type1.id, type2.id);
                }
                function getCalledExpression(scope, range, functionNameText) {
                    var functionReference = ts.createIdentifier(functionNameText);
                    if (ts.isClassLike(scope)) {
                        var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217
                        return ts.createPropertyAccess(lhs, functionReference);
                    }
                    else {
                        return functionReference;
                    }
                }
                function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) {
                    var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0;
                    if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
                        // already block, no declarations or writes to propagate back, no substitutions - can use node as is
                        return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined };
                    }
                    var returnValueProperty;
                    var ignoreReturns = false;
                    var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]);
                    // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions
                    if (hasWritesOrVariableDeclarations || substitutions.size) {
                        var rewrittenStatements = ts.visitNodes(statements, visitor).slice();
                        if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) {
                            // add return at the end to propagate writes back in case if control flow falls out of the function body
                            // it is ok to know that range has at least one return since it we only allow unconditional returns
                            var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
                            if (assignments.length === 1) {
                                rewrittenStatements.push(ts.createReturn(assignments[0].name));
                            }
                            else {
                                rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments)));
                            }
                        }
                        return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty };
                    }
                    else {
                        return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined };
                    }
                    function visitor(node) {
                        if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) {
                            var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
                            if (node.expression) {
                                if (!returnValueProperty) {
                                    returnValueProperty = "__return";
                                }
                                assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor)));
                            }
                            if (assignments.length === 1) {
                                return ts.createReturn(assignments[0].name);
                            }
                            else {
                                return ts.createReturn(ts.createObjectLiteral(assignments));
                            }
                        }
                        else {
                            var oldIgnoreReturns = ignoreReturns;
                            ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node);
                            var substitution = substitutions.get(ts.getNodeId(node).toString());
                            var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
                            ignoreReturns = oldIgnoreReturns;
                            return result;
                        }
                    }
                }
                function transformConstantInitializer(initializer, substitutions) {
                    return substitutions.size
                        ? visitor(initializer)
                        : initializer;
                    function visitor(node) {
                        var substitution = substitutions.get(ts.getNodeId(node).toString());
                        return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
                    }
                }
                function getStatementsOrClassElements(scope) {
                    if (ts.isFunctionLikeDeclaration(scope)) {
                        var body = scope.body; // TODO: GH#18217
                        if (ts.isBlock(body)) {
                            return body.statements;
                        }
                    }
                    else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) {
                        return scope.statements;
                    }
                    else if (ts.isClassLike(scope)) {
                        return scope.members;
                    }
                    else {
                        ts.assertType(scope);
                    }
                    return ts.emptyArray;
                }
                /**
                 * If `scope` contains a function after `minPos`, then return the first such function.
                 * Otherwise, return `undefined`.
                 */
                function getNodeToInsertFunctionBefore(minPos, scope) {
                    return ts.find(getStatementsOrClassElements(scope), function (child) {
                        return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child);
                    });
                }
                function getNodeToInsertPropertyBefore(maxPos, scope) {
                    var members = scope.members;
                    ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one.
                    var prevMember;
                    var allProperties = true;
                    for (var _i = 0, members_7 = members; _i < members_7.length; _i++) {
                        var member = members_7[_i];
                        if (member.pos > maxPos) {
                            return prevMember || members[0];
                        }
                        if (allProperties && !ts.isPropertyDeclaration(member)) {
                            // If it is non-vacuously true that all preceding members are properties,
                            // insert before the current member (i.e. at the end of the list of properties).
                            if (prevMember !== undefined) {
                                return member;
                            }
                            allProperties = false;
                        }
                        prevMember = member;
                    }
                    if (prevMember === undefined)
                        return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember.
                    return prevMember;
                }
                function getNodeToInsertConstantBefore(node, scope) {
                    ts.Debug.assert(!ts.isClassLike(scope));
                    var prevScope;
                    for (var curr = node; curr !== scope; curr = curr.parent) {
                        if (isScope(curr)) {
                            prevScope = curr;
                        }
                    }
                    for (var curr = (prevScope || node).parent;; curr = curr.parent) {
                        if (isBlockLike(curr)) {
                            var prevStatement = void 0;
                            for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
                                var statement = _a[_i];
                                if (statement.pos > node.pos) {
                                    break;
                                }
                                prevStatement = statement;
                            }
                            if (!prevStatement && ts.isCaseClause(curr)) {
                                // We must have been in the expression of the case clause.
                                ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent));
                                return curr.parent.parent;
                            }
                            // There must be at least one statement since we started in one.
                            return ts.Debug.assertDefined(prevStatement);
                        }
                        ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
                    }
                }
                function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) {
                    var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); });
                    var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); });
                    // TODO: GH#18217 `variableAssignments` not possibly undefined!
                    return variableAssignments === undefined
                        ? writeAssignments
                        : writeAssignments === undefined
                            ? variableAssignments
                            : variableAssignments.concat(writeAssignments);
                }
                function isReadonlyArray(v) {
                    return ts.isArray(v);
                }
                /**
                 * Produces a range that spans the entirety of nodes, given a selection
                 * that might start/end in the middle of nodes.
                 *
                 * For example, when the user makes a selection like this
                 *                     v---v
                 *   var someThing = foo + bar;
                 *  this returns     ^-------^
                 */
                function getEnclosingTextRange(targetRange, sourceFile) {
                    return isReadonlyArray(targetRange.range)
                        ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() }
                        : targetRange.range;
                }
                var Usage;
                (function (Usage) {
                    // value should be passed to extracted method
                    Usage[Usage["Read"] = 1] = "Read";
                    // value should be passed to extracted method and propagated back
                    Usage[Usage["Write"] = 2] = "Write";
                })(Usage || (Usage = {}));
                function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) {
                    var allTypeParameterUsages = ts.createMap(); // Key is type ID
                    var usagesPerScope = [];
                    var substitutionsPerScope = [];
                    var functionErrorsPerScope = [];
                    var constantErrorsPerScope = [];
                    var visibleDeclarationsInExtractedRange = [];
                    var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID
                    var exposedVariableDeclarations = [];
                    var firstExposedNonVariableDeclaration;
                    var expression = !isReadonlyArray(targetRange.range)
                        ? targetRange.range
                        : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
                            ? targetRange.range[0].expression
                            : undefined;
                    var expressionDiagnostic;
                    if (expression === undefined) {
                        var statements = targetRange.range;
                        var start = ts.first(statements).getStart();
                        var end = ts.last(statements).end;
                        expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected);
                    }
                    else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) {
                        expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType);
                    }
                    // initialize results
                    for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) {
                        var scope = scopes_1[_i];
                        usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() });
                        substitutionsPerScope.push(ts.createMap());
                        functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */
                            ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)]
                            : []);
                        var constantErrors = [];
                        if (expressionDiagnostic) {
                            constantErrors.push(expressionDiagnostic);
                        }
                        if (ts.isClassLike(scope) && ts.isInJSFile(scope)) {
                            constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
                        }
                        if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) {
                            // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this
                            constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction));
                        }
                        constantErrorsPerScope.push(constantErrors);
                    }
                    var seenUsages = ts.createMap();
                    var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range;
                    var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range;
                    var inGenericContext = isInGenericContext(unmodifiedNode);
                    collectUsages(target);
                    // Unfortunately, this code takes advantage of the knowledge that the generated method
                    // will use the contextual type of an expression as the return type of the extracted
                    // method (and will therefore "use" all the types involved).
                    if (inGenericContext && !isReadonlyArray(targetRange.range)) {
                        var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217
                        recordTypeParameterUsages(contextualType);
                    }
                    if (allTypeParameterUsages.size > 0) {
                        var seenTypeParameterUsages = ts.createMap(); // Key is type ID
                        var i_1 = 0;
                        for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) {
                            if (curr === scopes[i_1]) {
                                // Copy current contents of seenTypeParameterUsages into scope.
                                seenTypeParameterUsages.forEach(function (typeParameter, id) {
                                    usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter);
                                });
                                i_1++;
                            }
                            // Note that we add the current node's type parameters *after* updating the corresponding scope.
                            if (ts.isDeclarationWithTypeParameters(curr)) {
                                for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) {
                                    var typeParameterDecl = _b[_a];
                                    var typeParameter = checker.getTypeAtLocation(typeParameterDecl);
                                    if (allTypeParameterUsages.has(typeParameter.id.toString())) {
                                        seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter);
                                    }
                                }
                            }
                        }
                        // If we didn't get through all the scopes, then there were some that weren't in our
                        // parent chain (impossible at time of writing).  A conservative solution would be to
                        // copy allTypeParameterUsages into all remaining scopes.
                        ts.Debug.assert(i_1 === scopes.length);
                    }
                    // If there are any declarations in the extracted block that are used in the same enclosing
                    // lexical scope, we can't move the extraction "up" as those declarations will become unreachable
                    if (visibleDeclarationsInExtractedRange.length) {
                        var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent)
                            ? scopes[0]
                            : ts.getEnclosingBlockScopeContainer(scopes[0]);
                        ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
                    }
                    var _loop_21 = function (i) {
                        var scopeUsages = usagesPerScope[i];
                        // Special case: in the innermost scope, all usages are available.
                        // (The computed value reflects the value at the top-level of the scope, but the
                        // local will actually be declared at the same level as the extracted expression).
                        if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
                            var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
                            constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
                        }
                        var hasWrite = false;
                        var readonlyClassPropertyWrite;
                        usagesPerScope[i].usages.forEach(function (value) {
                            if (value.usage === 2 /* Write */) {
                                hasWrite = true;
                                if (value.symbol.flags & 106500 /* ClassMember */ &&
                                    value.symbol.valueDeclaration &&
                                    ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) {
                                    readonlyClassPropertyWrite = value.symbol.valueDeclaration;
                                }
                            }
                        });
                        // If an expression was extracted, then there shouldn't have been any variable declarations.
                        ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0);
                        if (hasWrite && !isReadonlyArray(targetRange.range)) {
                            var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression);
                            functionErrorsPerScope[i].push(diag);
                            constantErrorsPerScope[i].push(diag);
                        }
                        else if (readonlyClassPropertyWrite && i > 0) {
                            var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor);
                            functionErrorsPerScope[i].push(diag);
                            constantErrorsPerScope[i].push(diag);
                        }
                        else if (firstExposedNonVariableDeclaration) {
                            var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity);
                            functionErrorsPerScope[i].push(diag);
                            constantErrorsPerScope[i].push(diag);
                        }
                    };
                    for (var i = 0; i < scopes.length; i++) {
                        _loop_21(i);
                    }
                    return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
                    function isInGenericContext(node) {
                        return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; });
                    }
                    function recordTypeParameterUsages(type) {
                        // PERF: This is potentially very expensive.  `type` could be a library type with
                        // a lot of properties, each of which the walker will visit.  Unfortunately, the
                        // solution isn't as trivial as filtering to user types because of (e.g.) Array.
                        var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); });
                        var visitedTypes = symbolWalker.walkType(type).visitedTypes;
                        for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) {
                            var visitedType = visitedTypes_1[_i];
                            if (visitedType.isTypeParameter()) {
                                allTypeParameterUsages.set(visitedType.id.toString(), visitedType);
                            }
                        }
                    }
                    function collectUsages(node, valueUsage) {
                        if (valueUsage === void 0) {
                            valueUsage = 1 /* Read */;
                        }
                        if (inGenericContext) {
                            var type = checker.getTypeAtLocation(node);
                            recordTypeParameterUsages(type);
                        }
                        if (ts.isDeclaration(node) && node.symbol) {
                            visibleDeclarationsInExtractedRange.push(node);
                        }
                        if (ts.isAssignmentExpression(node)) {
                            // use 'write' as default usage for values
                            collectUsages(node.left, 2 /* Write */);
                            collectUsages(node.right);
                        }
                        else if (ts.isUnaryExpressionWithWrite(node)) {
                            collectUsages(node.operand, 2 /* Write */);
                        }
                        else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
                            // use 'write' as default usage for values
                            ts.forEachChild(node, collectUsages);
                        }
                        else if (ts.isIdentifier(node)) {
                            if (!node.parent) {
                                return;
                            }
                            if (ts.isQualifiedName(node.parent) && node !== node.parent.left) {
                                return;
                            }
                            if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) {
                                return;
                            }
                            recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node));
                        }
                        else {
                            ts.forEachChild(node, collectUsages);
                        }
                    }
                    function recordUsage(n, usage, isTypeNode) {
                        var symbolId = recordUsagebySymbol(n, usage, isTypeNode);
                        if (symbolId) {
                            for (var i = 0; i < scopes.length; i++) {
                                // push substitution from map<symbolId, subst> to map<nodeId, subst> to simplify rewriting
                                var substitution = substitutionsPerScope[i].get(symbolId);
                                if (substitution) {
                                    usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution);
                                }
                            }
                        }
                    }
                    function recordUsagebySymbol(identifier, usage, isTypeName) {
                        var symbol = getSymbolReferencedByIdentifier(identifier);
                        if (!symbol) {
                            // cannot find symbol - do nothing
                            return undefined;
                        }
                        var symbolId = ts.getSymbolId(symbol).toString();
                        var lastUsage = seenUsages.get(symbolId);
                        // there are two kinds of value usages
                        // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter
                        // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and
                        //   returned as a return value
                        // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read'
                        // since all information is already recorded
                        if (lastUsage && lastUsage >= usage) {
                            return symbolId;
                        }
                        seenUsages.set(symbolId, usage);
                        if (lastUsage) {
                            // if we get here this means that we are trying to handle 'write' and 'read' was already processed
                            // walk scopes and update existing records.
                            for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) {
                                var perScope = usagesPerScope_1[_i];
                                var prevEntry = perScope.usages.get(identifier.text);
                                if (prevEntry) {
                                    perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
                                }
                            }
                            return symbolId;
                        }
                        // find first declaration in this file
                        var decls = symbol.getDeclarations();
                        var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; });
                        if (!declInFile) {
                            return undefined;
                        }
                        if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) {
                            // declaration is located in range to be extracted - do nothing
                            return undefined;
                        }
                        if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) {
                            // this is write to a reference located outside of the target scope and range is extracted into generator
                            // currently this is unsupported scenario
                            var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
                            for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) {
                                var errors = functionErrorsPerScope_1[_a];
                                errors.push(diag);
                            }
                            for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) {
                                var errors = constantErrorsPerScope_1[_b];
                                errors.push(diag);
                            }
                        }
                        for (var i = 0; i < scopes.length; i++) {
                            var scope = scopes[i];
                            var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false);
                            if (resolvedSymbol === symbol) {
                                continue;
                            }
                            if (!substitutionsPerScope[i].has(symbolId)) {
                                var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName);
                                if (substitution) {
                                    substitutionsPerScope[i].set(symbolId, substitution);
                                }
                                else if (isTypeName) {
                                    // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument
                                    // so there's no problem.
                                    if (!(symbol.flags & 262144 /* TypeParameter */)) {
                                        var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope);
                                        functionErrorsPerScope[i].push(diag);
                                        constantErrorsPerScope[i].push(diag);
                                    }
                                }
                                else {
                                    usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
                                }
                            }
                        }
                        return symbolId;
                    }
                    function checkForUsedDeclarations(node) {
                        // If this node is entirely within the original extraction range, we don't need to do anything.
                        if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) {
                            return;
                        }
                        // Otherwise check and recurse.
                        var sym = ts.isIdentifier(node)
                            ? getSymbolReferencedByIdentifier(node)
                            : checker.getSymbolAtLocation(node);
                        if (sym) {
                            var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; });
                            if (decl) {
                                if (ts.isVariableDeclaration(decl)) {
                                    var idString = decl.symbol.id.toString();
                                    if (!exposedVariableSymbolSet.has(idString)) {
                                        exposedVariableDeclarations.push(decl);
                                        exposedVariableSymbolSet.set(idString, true);
                                    }
                                }
                                else {
                                    // CONSIDER: this includes binding elements, which we could
                                    // expose in the same way as variables.
                                    firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl;
                                }
                            }
                        }
                        ts.forEachChild(node, checkForUsedDeclarations);
                    }
                    /**
                     * Return the symbol referenced by an identifier (even if it declares a different symbol).
                     */
                    function getSymbolReferencedByIdentifier(identifier) {
                        // If the identifier is both a property name and its value, we're only interested in its value
                        // (since the name is a declaration and will be included in the extracted range).
                        return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier
                            ? checker.getShorthandAssignmentValueSymbol(identifier.parent)
                            : checker.getSymbolAtLocation(identifier);
                    }
                    function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) {
                        if (!symbol) {
                            return undefined;
                        }
                        var decls = symbol.getDeclarations();
                        if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) {
                            return ts.createIdentifier(symbol.name);
                        }
                        var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode);
                        if (prefix === undefined) {
                            return undefined;
                        }
                        return isTypeNode
                            ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name))
                            : ts.createPropertyAccess(prefix, symbol.name);
                    }
                }
                /**
                 * Computes whether or not a node represents an expression in a position where it could
                 * be extracted.
                 * The isExpression() in utilities.ts returns some false positives we need to handle,
                 * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression
                 * in the sense of something that you could extract on
                 */
                function isExtractableExpression(node) {
                    var parent = node.parent;
                    switch (parent.kind) {
                        case 276 /* EnumMember */:
                            return false;
                    }
                    switch (node.kind) {
                        case 9 /* StringLiteral */:
                            return parent.kind !== 247 /* ImportDeclaration */ &&
                                parent.kind !== 251 /* ImportSpecifier */;
                        case 206 /* SpreadElement */:
                        case 182 /* ObjectBindingPattern */:
                        case 184 /* BindingElement */:
                            return false;
                        case 71 /* Identifier */:
                            return parent.kind !== 184 /* BindingElement */ &&
                                parent.kind !== 251 /* ImportSpecifier */ &&
                                parent.kind !== 255 /* ExportSpecifier */;
                    }
                    return true;
                }
                function isBlockLike(node) {
                    switch (node.kind) {
                        case 216 /* Block */:
                        case 277 /* SourceFile */:
                        case 243 /* ModuleBlock */:
                        case 269 /* CaseClause */:
                            return true;
                        default:
                            return false;
                    }
                }
            })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {}));
        })(refactor = ts.refactor || (ts.refactor = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var refactor;
        (function (refactor) {
            var generateGetAccessorAndSetAccessor;
            (function (generateGetAccessorAndSetAccessor) {
                var actionName = "Generate 'get' and 'set' accessors";
                var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message;
                refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
                function getAvailableActions(context) {
                    if (!getConvertibleFieldAtPosition(context))
                        return undefined;
                    return [{
                            name: actionName,
                            description: actionDescription,
                            actions: [
                                {
                                    name: actionName,
                                    description: actionDescription
                                }
                            ]
                        }];
                }
                function getEditsForAction(context, _actionName) {
                    var file = context.file;
                    var fieldInfo = getConvertibleFieldAtPosition(context);
                    if (!fieldInfo)
                        return undefined;
                    var isJS = ts.isSourceFileJS(file);
                    var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
                    var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor;
                    ts.suppressLeadingAndTrailingTrivia(fieldName);
                    ts.suppressLeadingAndTrailingTrivia(declaration);
                    ts.suppressLeadingAndTrailingTrivia(container);
                    var isInClassLike = ts.isClassLike(container);
                    // avoid Readonly modifier because it will convert to get accessor
                    var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
                    var accessorModifiers = isInClassLike
                        ? !modifierFlags || modifierFlags & 8 /* Private */
                            ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */)
                            : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
                        : undefined;
                    var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined;
                    updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
                    var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
                    ts.suppressLeadingAndTrailingTrivia(getAccessor);
                    insertAccessor(changeTracker, file, getAccessor, declaration, container);
                    if (isReadonly) {
                        // readonly modifier only existed in classLikeDeclaration
                        var constructor = ts.getFirstConstructorWithBody(container);
                        if (constructor) {
                            updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
                        }
                    }
                    else {
                        var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
                        ts.suppressLeadingAndTrailingTrivia(setAccessor);
                        insertAccessor(changeTracker, file, setAccessor, declaration, container);
                    }
                    var edits = changeTracker.getChanges();
                    var renameFilename = file.fileName;
                    var nameNeedRename = renameAccessor ? accessorName : fieldName;
                    var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
                    var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration));
                    return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
                }
                function isConvertibleName(name) {
                    return ts.isIdentifier(name) || ts.isStringLiteral(name);
                }
                function isAcceptedDeclaration(node) {
                    return ts.isParameterPropertyDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node);
                }
                function createPropertyName(name, originalName) {
                    return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name);
                }
                function createAccessorAccessExpression(fieldName, isStatic, container) {
                    var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217
                    return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName));
                }
                function getModifiers(isJS, isStatic, accessModifier) {
                    var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined);
                    return modifiers && ts.createNodeArray(modifiers);
                }
                function startsWithUnderscore(name) {
                    return name.charCodeAt(0) === 95 /* _ */;
                }
                function getConvertibleFieldAtPosition(context) {
                    var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition;
                    var node = ts.getTokenAtPosition(file, startPosition);
                    var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
                    // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
                    var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
                    if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217
                        || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
                        return undefined;
                    var name = declaration.name.text;
                    var startWithUnderscore = startsWithUnderscore(name);
                    var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name);
                    var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name);
                    return {
                        isStatic: ts.hasStaticModifier(declaration),
                        isReadonly: ts.hasReadonlyModifier(declaration),
                        type: ts.getTypeAnnotationNode(declaration),
                        container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent,
                        originalName: declaration.name,
                        declaration: declaration,
                        fieldName: fieldName,
                        accessorName: accessorName,
                        renameAccessor: startWithUnderscore
                    };
                }
                function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
                    return ts.createGetAccessor(
                    /*decorators*/ undefined, modifiers, accessorName, 
                    /*parameters*/ undefined, // TODO: GH#18217
                    type, ts.createBlock([
                        ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container))
                    ], /*multiLine*/ true));
                }
                function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
                    return ts.createSetAccessor(
                    /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter(
                        /*decorators*/ undefined, 
                        /*modifiers*/ undefined, 
                        /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), 
                        /*questionToken*/ undefined, type)], ts.createBlock([
                        ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value")))
                    ], /*multiLine*/ true));
                }
                function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
                    var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
                    changeTracker.replaceNode(file, declaration, property);
                }
                function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
                    var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
                    changeTracker.replacePropertyAssignment(file, declaration, assignment);
                }
                function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
                    if (ts.isPropertyDeclaration(declaration)) {
                        updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
                    }
                    else if (ts.isPropertyAssignment(declaration)) {
                        updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
                    }
                    else {
                        changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
                    }
                }
                function insertAccessor(changeTracker, file, accessor, declaration, container) {
                    ts.isParameterPropertyDeclaration(declaration)
                        ? changeTracker.insertNodeAtClassStart(file, container, accessor)
                        : ts.isPropertyAssignment(declaration)
                            ? changeTracker.insertNodeAfterComma(file, declaration, accessor)
                            : changeTracker.insertNodeAfter(file, declaration, accessor);
                }
                function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
                    if (!constructor.body)
                        return;
                    var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
                    var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) {
                        return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined;
                    });
                    ts.forEach(referenceEntries, function (entry) {
                        var parent = entry.parent;
                        var accessorName = ts.createIdentifier(fieldName.text);
                        var node = ts.isBinaryExpression(parent)
                            ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
                            : ts.isPropertyAccessExpression(parent)
                                ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
                                : ts.Debug.fail("Unexpected write access token");
                        changeTracker.replaceNode(file, parent, node);
                    });
                }
            })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
        })(refactor = ts.refactor || (ts.refactor = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var refactor;
        (function (refactor) {
            var refactorName = "Move to a new file";
            refactor.registerRefactor(refactorName, {
                getAvailableActions: function (context) {
                    if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
                        return undefined;
                    var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
                    return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
                },
                getEditsForAction: function (context, actionName) {
                    ts.Debug.assert(actionName === refactorName);
                    var statements = ts.Debug.assertDefined(getStatementsToMove(context));
                    var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); });
                    return { edits: edits, renameFilename: undefined, renameLocation: undefined };
                }
            });
            function getRangeToMove(context) {
                var file = context.file;
                var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
                var statements = file.statements;
                var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
                if (startNodeIndex === -1)
                    return undefined;
                var startStatement = statements[startNodeIndex];
                if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) {
                    return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] };
                }
                // Can't only partially include the start node or be partially into the next node
                if (range.pos > startStatement.getStart(file))
                    return undefined;
                var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
                // Can't be partially into the next node
                if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
                    return undefined;
                return {
                    toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex),
                    afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex],
                };
            }
            function doChange(oldFile, program, toMove, changes, host, preferences) {
                var checker = program.getTypeChecker();
                var usage = getUsageInfo(oldFile, toMove.all, checker);
                var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
                var extension = ts.extensionFromPath(oldFile.fileName);
                var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
                var newFileNameWithExtension = newModuleName + extension;
                // If previous file was global, this is easy.
                changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences));
                addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
            }
            // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file.
            function getStatementsToMove(context) {
                var rangeToMove = getRangeToMove(context);
                if (rangeToMove === undefined)
                    return undefined;
                var all = [];
                var ranges = [];
                var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast;
                ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) {
                    for (var i = start; i < afterEndIndex; i++)
                        all.push(toMove[i]);
                    ranges.push({ first: toMove[start], afterLast: afterLast });
                });
                return all.length === 0 ? undefined : { all: all, ranges: ranges };
            }
            function isPureImport(node) {
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                        return true;
                    case 246 /* ImportEqualsDeclaration */:
                        return !ts.hasModifier(node, 1 /* Export */);
                    case 217 /* VariableStatement */:
                        return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
                    default:
                        return false;
                }
            }
            function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
                var cfg = program.getCompilerOptions().configFile;
                if (!cfg)
                    return;
                var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
                var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
                var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
                var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
                    return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
                });
                if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
                    changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
                }
            }
            function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) {
                var checker = program.getTypeChecker();
                if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
                    deleteMovedStatements(oldFile, toMove.ranges, changes);
                    return toMove.all;
                }
                var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
                var quotePreference = ts.getQuotePreference(oldFile, preferences);
                var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference);
                if (importsFromNewFile) {
                    ts.insertImport(changes, oldFile, importsFromNewFile);
                }
                deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
                deleteMovedStatements(oldFile, toMove.ranges, changes);
                updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
                return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
            }
            function deleteMovedStatements(sourceFile, moved, changes) {
                for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
                    var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast;
                    changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast);
                }
            }
            function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
                for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
                    var statement = _a[_i];
                    if (ts.contains(toMove, statement))
                        continue;
                    forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
                }
            }
            function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
                var checker = program.getTypeChecker();
                var _loop_22 = function (sourceFile) {
                    if (sourceFile === oldFile)
                        return "continue";
                    var _loop_23 = function (statement) {
                        forEachImportInStatement(statement, function (importNode) {
                            if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
                                return;
                            var shouldMove = function (name) {
                                var symbol = ts.isBindingElement(name.parent)
                                    ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
                                    : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217
                                return !!symbol && movedSymbols.has(symbol);
                            };
                            deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
                            var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
                            var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
                            if (newImportDeclaration)
                                changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
                            var ns = getNamespaceLikeImport(importNode);
                            if (ns)
                                updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode);
                        });
                    };
                    for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
                        var statement = _a[_i];
                        _loop_23(statement);
                    }
                };
                for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
                    var sourceFile = _a[_i];
                    _loop_22(sourceFile);
                }
            }
            function getNamespaceLikeImport(node) {
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                        return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ?
                            node.importClause.namedBindings.name : undefined;
                    case 246 /* ImportEqualsDeclaration */:
                        return node.name;
                    case 235 /* VariableDeclaration */:
                        return ts.tryCast(node.name, ts.isIdentifier);
                    default:
                        return ts.Debug.assertNever(node);
                }
            }
            function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
                var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */);
                var needUniqueName = false;
                var toChange = [];
                ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
                    if (!ts.isPropertyAccessExpression(ref.parent))
                        return;
                    needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true);
                    if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) {
                        toChange.push(ref);
                    }
                });
                if (toChange.length) {
                    var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName;
                    for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) {
                        var ref = toChange_1[_i];
                        changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName));
                    }
                    changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier));
                }
            }
            function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) {
                var newNamespaceId = ts.createIdentifier(newNamespaceName);
                var newModuleString = ts.createLiteral(newModuleSpecifier);
                switch (node.kind) {
                    case 247 /* ImportDeclaration */:
                        return ts.createImportDeclaration(
                        /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString);
                    case 246 /* ImportEqualsDeclaration */:
                        return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString));
                    case 235 /* VariableDeclaration */:
                        return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString));
                    default:
                        return ts.Debug.assertNever(node);
                }
            }
            function moduleSpecifierFromImport(i) {
                return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier
                    : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
                        : i.initializer.arguments[0]);
            }
            function forEachImportInStatement(statement, cb) {
                if (ts.isImportDeclaration(statement)) {
                    if (ts.isStringLiteral(statement.moduleSpecifier))
                        cb(statement);
                }
                else if (ts.isImportEqualsDeclaration(statement)) {
                    if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
                        cb(statement);
                    }
                }
                else if (ts.isVariableStatement(statement)) {
                    for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
                            cb(decl);
                        }
                    }
                }
            }
            function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) {
                var defaultImport;
                var imports = [];
                newFileNeedExport.forEach(function (symbol) {
                    if (symbol.escapedName === "default" /* Default */) {
                        defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217
                    }
                    else {
                        imports.push(symbol.name);
                    }
                });
                return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference);
            }
            function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) {
                path = ts.ensurePathIsNonModuleName(path);
                if (useEs6Imports) {
                    var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
                    return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference);
                }
                else {
                    ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module.
                    var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
                    return bindingElements.length
                        ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
                        : undefined;
                }
            }
            function makeVariableStatement(name, type, initializer, flags) {
                if (flags === void 0) {
                    flags = 2 /* Const */;
                }
                return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
            }
            function createRequireCall(moduleSpecifier) {
                return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
            }
            function addExports(sourceFile, toMove, needExport, useEs6Exports) {
                return ts.flatMap(toMove, function (statement) {
                    if (isTopLevelDeclarationStatement(statement) &&
                        !isExported(sourceFile, statement, useEs6Exports) &&
                        forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
                        var exports_2 = addExport(statement, useEs6Exports);
                        if (exports_2)
                            return exports_2;
                    }
                    return statement;
                });
            }
            function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
                switch (importDecl.kind) {
                    case 247 /* ImportDeclaration */:
                        deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
                        break;
                    case 246 /* ImportEqualsDeclaration */:
                        if (isUnused(importDecl.name)) {
                            changes.delete(sourceFile, importDecl);
                        }
                        break;
                    case 235 /* VariableDeclaration */:
                        deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
                        break;
                    default:
                        ts.Debug.assertNever(importDecl);
                }
            }
            function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
                if (!importDecl.importClause)
                    return;
                var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
                var defaultUnused = !name || isUnused(name);
                var namedBindingsUnused = !namedBindings ||
                    (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); }));
                if (defaultUnused && namedBindingsUnused) {
                    changes.delete(sourceFile, importDecl);
                }
                else {
                    if (name && defaultUnused) {
                        changes.delete(sourceFile, name);
                    }
                    if (namedBindings) {
                        if (namedBindingsUnused) {
                            changes.delete(sourceFile, namedBindings);
                        }
                        else if (namedBindings.kind === 250 /* NamedImports */) {
                            for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
                                var element = _b[_i];
                                if (isUnused(element.name))
                                    changes.delete(sourceFile, element);
                            }
                        }
                    }
                }
            }
            function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
                var name = varDecl.name;
                switch (name.kind) {
                    case 71 /* Identifier */:
                        if (isUnused(name)) {
                            changes.delete(sourceFile, name);
                        }
                        break;
                    case 183 /* ArrayBindingPattern */:
                        break;
                    case 182 /* ObjectBindingPattern */:
                        if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
                            changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
                        }
                        else {
                            for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
                                var element = _a[_i];
                                if (ts.isIdentifier(element.name) && isUnused(element.name)) {
                                    changes.delete(sourceFile, element.name);
                                }
                            }
                        }
                        break;
                }
            }
            function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) {
                var copiedOldImports = [];
                for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
                    var oldStatement = _a[_i];
                    forEachImportInStatement(oldStatement, function (i) {
                        ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
                    });
                }
                // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
                var oldFileDefault;
                var oldFileNamedImports = [];
                var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
                newFileImportsFromOldFile.forEach(function (symbol) {
                    for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                        var decl = _a[_i];
                        if (!isTopLevelDeclaration(decl))
                            continue;
                        var name = nameOfTopLevelDeclaration(decl);
                        if (!name)
                            continue;
                        var top = getTopLevelDeclarationStatement(decl);
                        if (markSeenTop(top)) {
                            addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
                        }
                        if (ts.hasModifier(decl, 512 /* Default */)) {
                            oldFileDefault = name;
                        }
                        else {
                            oldFileNamedImports.push(name.text);
                        }
                    }
                });
                ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference));
                return copiedOldImports;
            }
            function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
                var newModuleName = moduleName;
                for (var i = 1;; i++) {
                    var name = ts.combinePaths(inDirectory, newModuleName + extension);
                    if (!host.fileExists(name))
                        return newModuleName; // TODO: GH#18217
                    newModuleName = moduleName + "." + i;
                }
            }
            function getNewModuleName(movedSymbols) {
                return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
            }
            function getUsageInfo(oldFile, toMove, checker) {
                var movedSymbols = new SymbolSet();
                var oldImportsNeededByNewFile = new SymbolSet();
                var newFileImportsFromOldFile = new SymbolSet();
                for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
                    var statement = toMove_1[_i];
                    forEachTopLevelDeclaration(statement, function (decl) {
                        movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
                    });
                }
                for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
                    var statement = toMove_2[_a];
                    forEachReference(statement, checker, function (symbol) {
                        if (!symbol.declarations)
                            return;
                        for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
                            var decl = _a[_i];
                            if (isInImport(decl)) {
                                oldImportsNeededByNewFile.add(symbol);
                            }
                            else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) {
                                newFileImportsFromOldFile.add(symbol);
                            }
                        }
                    });
                }
                var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
                var oldFileImportsFromNewFile = new SymbolSet();
                for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
                    var statement = _c[_b];
                    if (ts.contains(toMove, statement))
                        continue;
                    forEachReference(statement, checker, function (symbol) {
                        if (movedSymbols.has(symbol))
                            oldFileImportsFromNewFile.add(symbol);
                        unusedImportsFromOldFile.delete(symbol);
                    });
                }
                return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
            }
            // Below should all be utilities
            function isInImport(decl) {
                switch (decl.kind) {
                    case 246 /* ImportEqualsDeclaration */:
                    case 251 /* ImportSpecifier */:
                    case 248 /* ImportClause */:
                        return true;
                    case 235 /* VariableDeclaration */:
                        return isVariableDeclarationInImport(decl);
                    case 184 /* BindingElement */:
                        return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
                    default:
                        return false;
                }
            }
            function isVariableDeclarationInImport(decl) {
                return ts.isSourceFile(decl.parent.parent.parent) &&
                    decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
            }
            function filterImport(i, moduleSpecifier, keep) {
                switch (i.kind) {
                    case 247 /* ImportDeclaration */: {
                        var clause = i.importClause;
                        if (!clause)
                            return undefined;
                        var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
                        var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
                        return defaultImport || namedBindings
                            ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
                            : undefined;
                    }
                    case 246 /* ImportEqualsDeclaration */:
                        return keep(i.name) ? i : undefined;
                    case 235 /* VariableDeclaration */: {
                        var name = filterBindingName(i.name, keep);
                        return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
                    }
                    default:
                        return ts.Debug.assertNever(i);
                }
            }
            function filterNamedBindings(namedBindings, keep) {
                if (namedBindings.kind === 249 /* NamespaceImport */) {
                    return keep(namedBindings.name) ? namedBindings : undefined;
                }
                else {
                    var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
                    return newElements.length ? ts.createNamedImports(newElements) : undefined;
                }
            }
            function filterBindingName(name, keep) {
                switch (name.kind) {
                    case 71 /* Identifier */:
                        return keep(name) ? name : undefined;
                    case 183 /* ArrayBindingPattern */:
                        return name;
                    case 182 /* ObjectBindingPattern */: {
                        // We can't handle nested destructurings or property names well here, so just copy them all.
                        var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
                        return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
                    }
                }
            }
            function forEachReference(node, checker, onReference) {
                node.forEachChild(function cb(node) {
                    if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
                        var sym = checker.getSymbolAtLocation(node);
                        if (sym)
                            onReference(sym);
                    }
                    else {
                        node.forEachChild(cb);
                    }
                });
            }
            var SymbolSet = /** @class */ (function () {
                function SymbolSet() {
                    this.map = ts.createMap();
                }
                SymbolSet.prototype.add = function (symbol) {
                    this.map.set(String(ts.getSymbolId(symbol)), symbol);
                };
                SymbolSet.prototype.has = function (symbol) {
                    return this.map.has(String(ts.getSymbolId(symbol)));
                };
                SymbolSet.prototype.delete = function (symbol) {
                    this.map.delete(String(ts.getSymbolId(symbol)));
                };
                SymbolSet.prototype.forEach = function (cb) {
                    this.map.forEach(cb);
                };
                SymbolSet.prototype.forEachEntry = function (cb) {
                    return ts.forEachEntry(this.map, cb);
                };
                SymbolSet.prototype.clone = function () {
                    var clone = new SymbolSet();
                    ts.copyEntries(this.map, clone.map);
                    return clone;
                };
                return SymbolSet;
            }());
            function isTopLevelDeclaration(node) {
                return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
            }
            function sourceFileOfTopLevelDeclaration(node) {
                return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent;
            }
            function isTopLevelDeclarationStatement(node) {
                ts.Debug.assert(ts.isSourceFile(node.parent));
                return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
            }
            function isNonVariableTopLevelDeclaration(node) {
                switch (node.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 242 /* ModuleDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 246 /* ImportEqualsDeclaration */:
                        return true;
                    default:
                        return false;
                }
            }
            function forEachTopLevelDeclaration(statement, cb) {
                switch (statement.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 238 /* ClassDeclaration */:
                    case 242 /* ModuleDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 246 /* ImportEqualsDeclaration */:
                        return cb(statement);
                    case 217 /* VariableStatement */:
                        return ts.forEach(statement.declarationList.declarations, cb);
                    case 219 /* ExpressionStatement */: {
                        var expression = statement.expression;
                        return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */
                            ? cb(statement)
                            : undefined;
                    }
                }
            }
            function nameOfTopLevelDeclaration(d) {
                return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
            }
            function getTopLevelDeclarationStatement(d) {
                return ts.isVariableDeclaration(d) ? d.parent.parent : d;
            }
            function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
                if (isExported(sourceFile, decl, useEs6Exports))
                    return;
                if (useEs6Exports) {
                    if (!ts.isExpressionStatement(decl))
                        changes.insertExportModifier(sourceFile, decl);
                }
                else {
                    var names = getNamesToExportInCommonJS(decl);
                    if (names.length !== 0)
                        changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
                }
            }
            function isExported(sourceFile, decl, useEs6Exports) {
                if (useEs6Exports) {
                    return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
                }
                else {
                    return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
                }
            }
            function addExport(decl, useEs6Exports) {
                return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
            }
            function addEs6Export(d) {
                var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
                switch (d.kind) {
                    case 237 /* FunctionDeclaration */:
                        return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
                    case 238 /* ClassDeclaration */:
                        return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
                    case 217 /* VariableStatement */:
                        return ts.updateVariableStatement(d, modifiers, d.declarationList);
                    case 242 /* ModuleDeclaration */:
                        return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
                    case 241 /* EnumDeclaration */:
                        return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
                    case 240 /* TypeAliasDeclaration */:
                        return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
                    case 239 /* InterfaceDeclaration */:
                        return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
                    case 246 /* ImportEqualsDeclaration */:
                        return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
                    case 219 /* ExpressionStatement */:
                        return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
                    default:
                        return ts.Debug.assertNever(d);
                }
            }
            function addCommonjsExport(decl) {
                return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment));
            }
            function getNamesToExportInCommonJS(decl) {
                switch (decl.kind) {
                    case 237 /* FunctionDeclaration */:
                    case 238 /* ClassDeclaration */:
                        return [decl.name.text]; // TODO: GH#18217
                    case 217 /* VariableStatement */:
                        return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
                    case 242 /* ModuleDeclaration */:
                    case 241 /* EnumDeclaration */:
                    case 240 /* TypeAliasDeclaration */:
                    case 239 /* InterfaceDeclaration */:
                    case 246 /* ImportEqualsDeclaration */:
                        return ts.emptyArray;
                    case 219 /* ExpressionStatement */:
                        return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
                    default:
                        return ts.Debug.assertNever(decl);
                }
            }
            /** Creates `exports.x = x;` */
            function createExportAssignment(name) {
                return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name)));
            }
        })(refactor = ts.refactor || (ts.refactor = {}));
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var refactor;
        (function (refactor) {
            var addOrRemoveBracesToArrowFunction;
            (function (addOrRemoveBracesToArrowFunction) {
                var refactorName = "Add or remove braces in an arrow function";
                var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message;
                var addBracesActionName = "Add braces to arrow function";
                var removeBracesActionName = "Remove braces from arrow function";
                var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message;
                var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message;
                refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
                function getAvailableActions(context) {
                    var file = context.file, startPosition = context.startPosition;
                    var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
                    if (!info)
                        return undefined;
                    return [{
                            name: refactorName,
                            description: refactorDescription,
                            actions: [
                                info.addBraces ?
                                    {
                                        name: addBracesActionName,
                                        description: addBracesActionDescription
                                    } : {
                                    name: removeBracesActionName,
                                    description: removeBracesActionDescription
                                }
                            ]
                        }];
                }
                function getEditsForAction(context, actionName) {
                    var file = context.file, startPosition = context.startPosition;
                    var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
                    if (!info)
                        return undefined;
                    var expression = info.expression, returnStatement = info.returnStatement, func = info.func;
                    var body;
                    if (actionName === addBracesActionName) {
                        var returnStatement_1 = ts.createReturn(expression);
                        body = ts.createBlock([returnStatement_1], /* multiLine */ true);
                        ts.suppressLeadingAndTrailingTrivia(body);
                        ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
                    }
                    else if (actionName === removeBracesActionName && returnStatement) {
                        var actualExpression = expression || ts.createVoidZero();
                        body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
                        ts.suppressLeadingAndTrailingTrivia(body);
                        ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
                    }
                    else {
                        ts.Debug.fail("invalid action");
                    }
                    var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); });
                    return { renameFilename: undefined, renameLocation: undefined, edits: edits };
                }
                function needsParentheses(expression) {
                    return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression);
                }
                function getConvertibleArrowFunctionAtPosition(file, startPosition) {
                    var node = ts.getTokenAtPosition(file, startPosition);
                    var func = ts.getContainingFunction(node);
                    if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node)))
                        return undefined;
                    if (ts.isExpression(func.body)) {
                        return {
                            func: func,
                            addBraces: true,
                            expression: func.body
                        };
                    }
                    else if (func.body.statements.length === 1) {
                        var firstStatement = ts.first(func.body.statements);
                        if (ts.isReturnStatement(firstStatement)) {
                            return {
                                func: func,
                                addBraces: false,
                                expression: firstStatement.expression,
                                returnStatement: firstStatement
                            };
                        }
                    }
                    return undefined;
                }
            })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
        })(refactor = ts.refactor || (ts.refactor = {}));
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        /** The version of the language service API */
        ts.servicesVersion = "0.8";
        function createNode(kind, pos, end, parent) {
            var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) :
                kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) :
                    new TokenObject(kind, pos, end);
            node.parent = parent;
            node.flags = parent.flags & 12679168 /* ContextFlags */;
            return node;
        }
        var NodeObject = /** @class */ (function () {
            function NodeObject(kind, pos, end) {
                this.pos = pos;
                this.end = end;
                this.flags = 0 /* None */;
                this.transformFlags = undefined; // TODO: GH#18217
                this.parent = undefined;
                this.kind = kind;
            }
            NodeObject.prototype.assertHasRealPosition = function (message) {
                // tslint:disable-next-line:debug-assert
                ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation");
            };
            NodeObject.prototype.getSourceFile = function () {
                return ts.getSourceFileOfNode(this);
            };
            NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
                this.assertHasRealPosition();
                return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
            };
            NodeObject.prototype.getFullStart = function () {
                this.assertHasRealPosition();
                return this.pos;
            };
            NodeObject.prototype.getEnd = function () {
                this.assertHasRealPosition();
                return this.end;
            };
            NodeObject.prototype.getWidth = function (sourceFile) {
                this.assertHasRealPosition();
                return this.getEnd() - this.getStart(sourceFile);
            };
            NodeObject.prototype.getFullWidth = function () {
                this.assertHasRealPosition();
                return this.end - this.pos;
            };
            NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
                this.assertHasRealPosition();
                return this.getStart(sourceFile) - this.pos;
            };
            NodeObject.prototype.getFullText = function (sourceFile) {
                this.assertHasRealPosition();
                return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
            };
            NodeObject.prototype.getText = function (sourceFile) {
                this.assertHasRealPosition();
                if (!sourceFile) {
                    sourceFile = this.getSourceFile();
                }
                return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
            };
            NodeObject.prototype.getChildCount = function (sourceFile) {
                return this.getChildren(sourceFile).length;
            };
            NodeObject.prototype.getChildAt = function (index, sourceFile) {
                return this.getChildren(sourceFile)[index];
            };
            NodeObject.prototype.getChildren = function (sourceFile) {
                this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine");
                return this._children || (this._children = createChildren(this, sourceFile));
            };
            NodeObject.prototype.getFirstToken = function (sourceFile) {
                this.assertHasRealPosition();
                var children = this.getChildren(sourceFile);
                if (!children.length) {
                    return undefined;
                }
                var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; });
                return child.kind < 146 /* FirstNode */ ?
                    child :
                    child.getFirstToken(sourceFile);
            };
            NodeObject.prototype.getLastToken = function (sourceFile) {
                this.assertHasRealPosition();
                var children = this.getChildren(sourceFile);
                var child = ts.lastOrUndefined(children);
                if (!child) {
                    return undefined;
                }
                return child.kind < 146 /* FirstNode */ ? child : child.getLastToken(sourceFile);
            };
            NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) {
                return ts.forEachChild(this, cbNode, cbNodeArray);
            };
            return NodeObject;
        }());
        function createChildren(node, sourceFile) {
            if (!ts.isNodeKind(node.kind)) {
                return ts.emptyArray;
            }
            var children = [];
            if (ts.isJSDocCommentContainingNode(node)) {
                /** Don't add trivia for "tokens" since this is in a comment. */
                node.forEachChild(function (child) { children.push(child); });
                return children;
            }
            ts.scanner.setText((sourceFile || node.getSourceFile()).text);
            var pos = node.pos;
            var processNode = function (child) {
                addSyntheticNodes(children, pos, child.pos, node);
                children.push(child);
                pos = child.end;
            };
            var processNodes = function (nodes) {
                addSyntheticNodes(children, pos, nodes.pos, node);
                children.push(createSyntaxList(nodes, node));
                pos = nodes.end;
            };
            // jsDocComments need to be the first children
            ts.forEach(node.jsDoc, processNode);
            // For syntactic classifications, all trivia are classified together, including jsdoc comments.
            // For that to work, the jsdoc comments should still be the leading trivia of the first child.
            // Restoring the scanner position ensures that.
            pos = node.pos;
            node.forEachChild(processNode, processNodes);
            addSyntheticNodes(children, pos, node.end, node);
            ts.scanner.setText(undefined);
            return children;
        }
        function addSyntheticNodes(nodes, pos, end, parent) {
            ts.scanner.setTextPos(pos);
            while (pos < end) {
                var token = ts.scanner.scan();
                var textPos = ts.scanner.getTextPos();
                if (textPos <= end) {
                    if (token === 71 /* Identifier */) {
                        ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia");
                    }
                    nodes.push(createNode(token, pos, textPos, parent));
                }
                pos = textPos;
                if (token === 1 /* EndOfFileToken */) {
                    break;
                }
            }
        }
        function createSyntaxList(nodes, parent) {
            var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent);
            list._children = [];
            var pos = nodes.pos;
            for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
                var node = nodes_7[_i];
                addSyntheticNodes(list._children, pos, node.pos, parent);
                list._children.push(node);
                pos = node.end;
            }
            addSyntheticNodes(list._children, pos, nodes.end, parent);
            return list;
        }
        var TokenOrIdentifierObject = /** @class */ (function () {
            function TokenOrIdentifierObject(pos, end) {
                // Set properties in same order as NodeObject
                this.pos = pos;
                this.end = end;
                this.flags = 0 /* None */;
                this.parent = undefined;
            }
            TokenOrIdentifierObject.prototype.getSourceFile = function () {
                return ts.getSourceFileOfNode(this);
            };
            TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
                return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
            };
            TokenOrIdentifierObject.prototype.getFullStart = function () {
                return this.pos;
            };
            TokenOrIdentifierObject.prototype.getEnd = function () {
                return this.end;
            };
            TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
                return this.getEnd() - this.getStart(sourceFile);
            };
            TokenOrIdentifierObject.prototype.getFullWidth = function () {
                return this.end - this.pos;
            };
            TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
                return this.getStart(sourceFile) - this.pos;
            };
            TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
                return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
            };
            TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
                if (!sourceFile) {
                    sourceFile = this.getSourceFile();
                }
                return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
            };
            TokenOrIdentifierObject.prototype.getChildCount = function () {
                return 0;
            };
            TokenOrIdentifierObject.prototype.getChildAt = function () {
                return undefined; // TODO: GH#18217
            };
            TokenOrIdentifierObject.prototype.getChildren = function () {
                return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray;
            };
            TokenOrIdentifierObject.prototype.getFirstToken = function () {
                return undefined;
            };
            TokenOrIdentifierObject.prototype.getLastToken = function () {
                return undefined;
            };
            TokenOrIdentifierObject.prototype.forEachChild = function () {
                return undefined;
            };
            return TokenOrIdentifierObject;
        }());
        var SymbolObject = /** @class */ (function () {
            function SymbolObject(flags, name) {
                this.flags = flags;
                this.escapedName = name;
            }
            SymbolObject.prototype.getFlags = function () {
                return this.flags;
            };
            Object.defineProperty(SymbolObject.prototype, "name", {
                get: function () {
                    return ts.symbolName(this);
                },
                enumerable: true,
                configurable: true
            });
            SymbolObject.prototype.getEscapedName = function () {
                return this.escapedName;
            };
            SymbolObject.prototype.getName = function () {
                return this.name;
            };
            SymbolObject.prototype.getDeclarations = function () {
                return this.declarations;
            };
            SymbolObject.prototype.getDocumentationComment = function (checker) {
                if (!this.documentationComment) {
                    this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs
                    this.documentationComment = getDocumentationComment(this.declarations, checker);
                }
                return this.documentationComment;
            };
            SymbolObject.prototype.getJsDocTags = function () {
                if (this.tags === undefined) {
                    this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations);
                }
                return this.tags;
            };
            return SymbolObject;
        }());
        var TokenObject = /** @class */ (function (_super) {
            __extends(TokenObject, _super);
            function TokenObject(kind, pos, end) {
                var _this = _super.call(this, pos, end) || this;
                _this.kind = kind;
                return _this;
            }
            return TokenObject;
        }(TokenOrIdentifierObject));
        var IdentifierObject = /** @class */ (function (_super) {
            __extends(IdentifierObject, _super);
            function IdentifierObject(_kind, pos, end) {
                return _super.call(this, pos, end) || this;
            }
            Object.defineProperty(IdentifierObject.prototype, "text", {
                get: function () {
                    return ts.idText(this);
                },
                enumerable: true,
                configurable: true
            });
            return IdentifierObject;
        }(TokenOrIdentifierObject));
        IdentifierObject.prototype.kind = 71 /* Identifier */;
        var TypeObject = /** @class */ (function () {
            function TypeObject(checker, flags) {
                this.checker = checker;
                this.flags = flags;
            }
            TypeObject.prototype.getFlags = function () {
                return this.flags;
            };
            TypeObject.prototype.getSymbol = function () {
                return this.symbol;
            };
            TypeObject.prototype.getProperties = function () {
                return this.checker.getPropertiesOfType(this);
            };
            TypeObject.prototype.getProperty = function (propertyName) {
                return this.checker.getPropertyOfType(this, propertyName);
            };
            TypeObject.prototype.getApparentProperties = function () {
                return this.checker.getAugmentedPropertiesOfType(this);
            };
            TypeObject.prototype.getCallSignatures = function () {
                return this.checker.getSignaturesOfType(this, 0 /* Call */);
            };
            TypeObject.prototype.getConstructSignatures = function () {
                return this.checker.getSignaturesOfType(this, 1 /* Construct */);
            };
            TypeObject.prototype.getStringIndexType = function () {
                return this.checker.getIndexTypeOfType(this, 0 /* String */);
            };
            TypeObject.prototype.getNumberIndexType = function () {
                return this.checker.getIndexTypeOfType(this, 1 /* Number */);
            };
            TypeObject.prototype.getBaseTypes = function () {
                return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined;
            };
            TypeObject.prototype.getNonNullableType = function () {
                return this.checker.getNonNullableType(this);
            };
            TypeObject.prototype.getConstraint = function () {
                return this.checker.getBaseConstraintOfType(this);
            };
            TypeObject.prototype.getDefault = function () {
                return this.checker.getDefaultFromTypeParameter(this);
            };
            TypeObject.prototype.isUnion = function () {
                return !!(this.flags & 262144 /* Union */);
            };
            TypeObject.prototype.isIntersection = function () {
                return !!(this.flags & 524288 /* Intersection */);
            };
            TypeObject.prototype.isUnionOrIntersection = function () {
                return !!(this.flags & 786432 /* UnionOrIntersection */);
            };
            TypeObject.prototype.isLiteral = function () {
                return !!(this.flags & 192 /* StringOrNumberLiteral */);
            };
            TypeObject.prototype.isStringLiteral = function () {
                return !!(this.flags & 64 /* StringLiteral */);
            };
            TypeObject.prototype.isNumberLiteral = function () {
                return !!(this.flags & 128 /* NumberLiteral */);
            };
            TypeObject.prototype.isTypeParameter = function () {
                return !!(this.flags & 65536 /* TypeParameter */);
            };
            TypeObject.prototype.isClassOrInterface = function () {
                return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */);
            };
            TypeObject.prototype.isClass = function () {
                return !!(ts.getObjectFlags(this) & 1 /* Class */);
            };
            return TypeObject;
        }());
        var SignatureObject = /** @class */ (function () {
            function SignatureObject(checker) {
                this.checker = checker;
            }
            SignatureObject.prototype.getDeclaration = function () {
                return this.declaration;
            };
            SignatureObject.prototype.getTypeParameters = function () {
                return this.typeParameters;
            };
            SignatureObject.prototype.getParameters = function () {
                return this.parameters;
            };
            SignatureObject.prototype.getReturnType = function () {
                return this.checker.getReturnTypeOfSignature(this);
            };
            SignatureObject.prototype.getDocumentationComment = function () {
                return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker));
            };
            SignatureObject.prototype.getJsDocTags = function () {
                if (this.jsDocTags === undefined) {
                    this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : [];
                }
                return this.jsDocTags;
            };
            return SignatureObject;
        }());
        /**
         * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it.
         * @param node the Node in question.
         * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`.
         */
        function hasJSDocInheritDocTag(node) {
            return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; });
        }
        function getDocumentationComment(declarations, checker) {
            if (!declarations)
                return ts.emptyArray;
            var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
            if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
                for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) {
                    var declaration = declarations_14[_i];
                    var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
                    // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
                    if (inheritedDocs)
                        doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc);
                }
            }
            return doc;
        }
        /**
         * Attempts to find JSDoc comments for possibly-inherited properties.  Checks superclasses then traverses
         * implemented interfaces until a symbol is found with the same name and with documentation.
         * @param declaration The possibly-inherited declaration to find comments for.
         * @param propertyName The name of the possibly-inherited property.
         * @param typeChecker A TypeChecker, used to find inherited properties.
         * @returns A filled array of documentation comments if any were found, otherwise an empty array.
         */
        function findInheritedJSDocComments(declaration, propertyName, typeChecker) {
            return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) {
                var superType = typeChecker.getTypeAtLocation(superTypeNode);
                var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName);
                var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker);
                return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined;
            });
        }
        var SourceFileObject = /** @class */ (function (_super) {
            __extends(SourceFileObject, _super);
            function SourceFileObject(kind, pos, end) {
                return _super.call(this, kind, pos, end) || this;
            }
            SourceFileObject.prototype.update = function (newText, textChangeRange) {
                return ts.updateSourceFile(this, newText, textChangeRange);
            };
            SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) {
                return ts.getLineAndCharacterOfPosition(this, position);
            };
            SourceFileObject.prototype.getLineStarts = function () {
                return ts.getLineStarts(this);
            };
            SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) {
                return ts.getPositionOfLineAndCharacter(this, line, character);
            };
            SourceFileObject.prototype.getLineEndOfPosition = function (pos) {
                var line = this.getLineAndCharacterOfPosition(pos).line;
                var lineStarts = this.getLineStarts();
                var lastCharPos;
                if (line + 1 >= lineStarts.length) {
                    lastCharPos = this.getEnd();
                }
                if (!lastCharPos) {
                    lastCharPos = lineStarts[line + 1] - 1;
                }
                var fullText = this.getFullText();
                // if the new line is "\r\n", we should return the last non-new-line-character position
                return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos;
            };
            SourceFileObject.prototype.getNamedDeclarations = function () {
                if (!this.namedDeclarations) {
                    this.namedDeclarations = this.computeNamedDeclarations();
                }
                return this.namedDeclarations;
            };
            SourceFileObject.prototype.computeNamedDeclarations = function () {
                var result = ts.createMultiMap();
                this.forEachChild(visit);
                return result;
                function addDeclaration(declaration) {
                    var name = getDeclarationName(declaration);
                    if (name) {
                        result.add(name, declaration);
                    }
                }
                function getDeclarations(name) {
                    var declarations = result.get(name);
                    if (!declarations) {
                        result.set(name, declarations = []);
                    }
                    return declarations;
                }
                function getDeclarationName(declaration) {
                    var name = ts.getNonAssignedNameOfDeclaration(declaration);
                    return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text
                        : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined);
                }
                function visit(node) {
                    switch (node.kind) {
                        case 237 /* FunctionDeclaration */:
                        case 194 /* FunctionExpression */:
                        case 154 /* MethodDeclaration */:
                        case 153 /* MethodSignature */:
                            var functionDeclaration = node;
                            var declarationName = getDeclarationName(functionDeclaration);
                            if (declarationName) {
                                var declarations = getDeclarations(declarationName);
                                var lastDeclaration = ts.lastOrUndefined(declarations);
                                // Check whether this declaration belongs to an "overload group".
                                if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) {
                                    // Overwrite the last declaration if it was an overload
                                    // and this one is an implementation.
                                    if (functionDeclaration.body && !lastDeclaration.body) {
                                        declarations[declarations.length - 1] = functionDeclaration;
                                    }
                                }
                                else {
                                    declarations.push(functionDeclaration);
                                }
                            }
                            ts.forEachChild(node, visit);
                            break;
                        case 238 /* ClassDeclaration */:
                        case 207 /* ClassExpression */:
                        case 239 /* InterfaceDeclaration */:
                        case 240 /* TypeAliasDeclaration */:
                        case 241 /* EnumDeclaration */:
                        case 242 /* ModuleDeclaration */:
                        case 246 /* ImportEqualsDeclaration */:
                        case 255 /* ExportSpecifier */:
                        case 251 /* ImportSpecifier */:
                        case 248 /* ImportClause */:
                        case 249 /* NamespaceImport */:
                        case 156 /* GetAccessor */:
                        case 157 /* SetAccessor */:
                        case 166 /* TypeLiteral */:
                            addDeclaration(node);
                            ts.forEachChild(node, visit);
                            break;
                        case 149 /* Parameter */:
                            // Only consider parameter properties
                            if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
                                break;
                            }
                        // falls through
                        case 235 /* VariableDeclaration */:
                        case 184 /* BindingElement */: {
                            var decl = node;
                            if (ts.isBindingPattern(decl.name)) {
                                ts.forEachChild(decl.name, visit);
                                break;
                            }
                            if (decl.initializer) {
                                visit(decl.initializer);
                            }
                        }
                        // falls through
                        case 276 /* EnumMember */:
                        case 152 /* PropertyDeclaration */:
                        case 151 /* PropertySignature */:
                            addDeclaration(node);
                            break;
                        case 253 /* ExportDeclaration */:
                            // Handle named exports case e.g.:
                            //    export {a, b as B} from "mod";
                            if (node.exportClause) {
                                ts.forEach(node.exportClause.elements, visit);
                            }
                            break;
                        case 247 /* ImportDeclaration */:
                            var importClause = node.importClause;
                            if (importClause) {
                                // Handle default import case e.g.:
                                //    import d from "mod";
                                if (importClause.name) {
                                    addDeclaration(importClause.name);
                                }
                                // Handle named bindings in imports e.g.:
                                //    import * as NS from "mod";
                                //    import {a, b as B} from "mod";
                                if (importClause.namedBindings) {
                                    if (importClause.namedBindings.kind === 249 /* NamespaceImport */) {
                                        addDeclaration(importClause.namedBindings);
                                    }
                                    else {
                                        ts.forEach(importClause.namedBindings.elements, visit);
                                    }
                                }
                            }
                            break;
                        case 202 /* BinaryExpression */:
                            if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) {
                                addDeclaration(node);
                            }
                        // falls through
                        default:
                            ts.forEachChild(node, visit);
                    }
                }
            };
            return SourceFileObject;
        }(NodeObject));
        var SourceMapSourceObject = /** @class */ (function () {
            function SourceMapSourceObject(fileName, text, skipTrivia) {
                this.fileName = fileName;
                this.text = text;
                this.skipTrivia = skipTrivia;
            }
            SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) {
                return ts.getLineAndCharacterOfPosition(this, pos);
            };
            return SourceMapSourceObject;
        }());
        function getServicesObjectAllocator() {
            return {
                getNodeConstructor: function () { return NodeObject; },
                getTokenConstructor: function () { return TokenObject; },
                getIdentifierConstructor: function () { return IdentifierObject; },
                getSourceFileConstructor: function () { return SourceFileObject; },
                getSymbolConstructor: function () { return SymbolObject; },
                getTypeConstructor: function () { return TypeObject; },
                getSignatureConstructor: function () { return SignatureObject; },
                getSourceMapSourceConstructor: function () { return SourceMapSourceObject; },
            };
        }
        function toEditorSettings(optionsAsMap) {
            var allPropertiesAreCamelCased = true;
            for (var key in optionsAsMap) {
                if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) {
                    allPropertiesAreCamelCased = false;
                    break;
                }
            }
            if (allPropertiesAreCamelCased) {
                return optionsAsMap;
            }
            var settings = {};
            for (var key in optionsAsMap) {
                if (ts.hasProperty(optionsAsMap, key)) {
                    var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1);
                    settings[newKey] = optionsAsMap[key];
                }
            }
            return settings;
        }
        ts.toEditorSettings = toEditorSettings;
        function isCamelCase(s) {
            return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
        }
        function displayPartsToString(displayParts) {
            if (displayParts) {
                return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
            }
            return "";
        }
        ts.displayPartsToString = displayPartsToString;
        function getDefaultCompilerOptions() {
            // Always default to "ScriptTarget.ES5" for the language service
            return {
                target: 1 /* ES5 */,
                jsx: 1 /* Preserve */
            };
        }
        ts.getDefaultCompilerOptions = getDefaultCompilerOptions;
        function getSupportedCodeFixes() {
            return ts.codefix.getSupportedErrorCodes();
        }
        ts.getSupportedCodeFixes = getSupportedCodeFixes;
        // Cache host information about script Should be refreshed
        // at each language service public entry point, since we don't know when
        // the set of scripts handled by the host changes.
        var HostCache = /** @class */ (function () {
            function HostCache(host, getCanonicalFileName) {
                this.host = host;
                // script id => script index
                this.currentDirectory = host.getCurrentDirectory();
                this.fileNameToEntry = ts.createMap();
                // Initialize the list with the root file names
                var rootFileNames = host.getScriptFileNames();
                for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) {
                    var fileName = rootFileNames_1[_i];
                    this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName));
                }
                // store the compilation settings
                this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions();
            }
            HostCache.prototype.compilationSettings = function () {
                return this._compilationSettings;
            };
            HostCache.prototype.getProjectReferences = function () {
                return this.host.getProjectReferences && this.host.getProjectReferences();
            };
            HostCache.prototype.createEntry = function (fileName, path) {
                var entry;
                var scriptSnapshot = this.host.getScriptSnapshot(fileName);
                if (scriptSnapshot) {
                    entry = {
                        hostFileName: fileName,
                        version: this.host.getScriptVersion(fileName),
                        scriptSnapshot: scriptSnapshot,
                        scriptKind: ts.getScriptKind(fileName, this.host)
                    };
                }
                else {
                    entry = fileName;
                }
                this.fileNameToEntry.set(path, entry);
                return entry;
            };
            HostCache.prototype.getEntryByPath = function (path) {
                return this.fileNameToEntry.get(path);
            };
            HostCache.prototype.getHostFileInformation = function (path) {
                var entry = this.fileNameToEntry.get(path);
                return !ts.isString(entry) ? entry : undefined;
            };
            HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) {
                var info = this.getEntryByPath(path) || this.createEntry(fileName, path);
                return ts.isString(info) ? undefined : info; // TODO: GH#18217
            };
            HostCache.prototype.getRootFileNames = function () {
                var names = [];
                this.fileNameToEntry.forEach(function (entry) {
                    if (ts.isString(entry)) {
                        names.push(entry);
                    }
                    else {
                        if (entry.scriptKind !== 6 /* JSON */) {
                            names.push(entry.hostFileName);
                        }
                    }
                });
                return names;
            };
            HostCache.prototype.getVersion = function (path) {
                var file = this.getHostFileInformation(path);
                return (file && file.version); // TODO: GH#18217
            };
            HostCache.prototype.getScriptSnapshot = function (path) {
                var file = this.getHostFileInformation(path);
                return (file && file.scriptSnapshot); // TODO: GH#18217
            };
            return HostCache;
        }());
        var SyntaxTreeCache = /** @class */ (function () {
            function SyntaxTreeCache(host) {
                this.host = host;
            }
            SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) {
                var scriptSnapshot = this.host.getScriptSnapshot(fileName);
                if (!scriptSnapshot) {
                    // The host does not know about this file.
                    throw new Error("Could not find file: '" + fileName + "'.");
                }
                var scriptKind = ts.getScriptKind(fileName, this.host);
                var version = this.host.getScriptVersion(fileName);
                var sourceFile;
                if (this.currentFileName !== fileName) {
                    // This is a new file, just parse it
                    sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
                }
                else if (this.currentFileVersion !== version) {
                    // This is the same file, just a newer version. Incrementally parse the file.
                    var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot);
                    sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange);
                }
                if (sourceFile) {
                    // All done, ensure state is up to date
                    this.currentFileVersion = version;
                    this.currentFileName = fileName;
                    this.currentFileScriptSnapshot = scriptSnapshot;
                    this.currentSourceFile = sourceFile;
                }
                return this.currentSourceFile;
            };
            return SyntaxTreeCache;
        }());
        function setSourceFileFields(sourceFile, scriptSnapshot, version) {
            sourceFile.version = version;
            sourceFile.scriptSnapshot = scriptSnapshot;
        }
        function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) {
            var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind);
            setSourceFileFields(sourceFile, scriptSnapshot, version);
            return sourceFile;
        }
        ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile;
        ts.disableIncrementalParsing = false;
        function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) {
            // If we were given a text change range, and our version or open-ness changed, then
            // incrementally parse this file.
            if (textChangeRange) {
                if (version !== sourceFile.version) {
                    // Once incremental parsing is ready, then just call into this function.
                    if (!ts.disableIncrementalParsing) {
                        var newText = void 0;
                        // grab the fragment from the beginning of the original text to the beginning of the span
                        var prefix = textChangeRange.span.start !== 0
                            ? sourceFile.text.substr(0, textChangeRange.span.start)
                            : "";
                        // grab the fragment from the end of the span till the end of the original text
                        var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length
                            ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span))
                            : "";
                        if (textChangeRange.newLength === 0) {
                            // edit was a deletion - just combine prefix and suffix
                            newText = prefix && suffix ? prefix + suffix : prefix || suffix;
                        }
                        else {
                            // it was actual edit, fetch the fragment of new text that correspond to new span
                            var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength);
                            // combine prefix, changed text and suffix
                            newText = prefix && suffix
                                ? prefix + changedText + suffix
                                : prefix
                                    ? (prefix + changedText)
                                    : (changedText + suffix);
                        }
                        var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
                        setSourceFileFields(newSourceFile, scriptSnapshot, version);
                        // after incremental parsing nameTable might not be up-to-date
                        // drop it so it can be lazily recreated later
                        newSourceFile.nameTable = undefined;
                        // dispose all resources held by old script snapshot
                        if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) {
                            if (sourceFile.scriptSnapshot.dispose) {
                                sourceFile.scriptSnapshot.dispose();
                            }
                            sourceFile.scriptSnapshot = undefined;
                        }
                        return newSourceFile;
                    }
                }
            }
            // Otherwise, just create a new source file.
            return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind);
        }
        ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile;
        var CancellationTokenObject = /** @class */ (function () {
            function CancellationTokenObject(cancellationToken) {
                this.cancellationToken = cancellationToken;
            }
            CancellationTokenObject.prototype.isCancellationRequested = function () {
                return !!this.cancellationToken && this.cancellationToken.isCancellationRequested();
            };
            CancellationTokenObject.prototype.throwIfCancellationRequested = function () {
                if (this.isCancellationRequested()) {
                    throw new ts.OperationCanceledException();
                }
            };
            return CancellationTokenObject;
        }());
        /* @internal */
        /** A cancellation that throttles calls to the host */
        var ThrottledCancellationToken = /** @class */ (function () {
            function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) {
                if (throttleWaitMilliseconds === void 0) {
                    throttleWaitMilliseconds = 20;
                }
                this.hostCancellationToken = hostCancellationToken;
                this.throttleWaitMilliseconds = throttleWaitMilliseconds;
                // Store when we last tried to cancel.  Checking cancellation can be expensive (as we have
                // to marshall over to the host layer).  So we only bother actually checking once enough
                // time has passed.
                this.lastCancellationCheckTime = 0;
            }
            ThrottledCancellationToken.prototype.isCancellationRequested = function () {
                var time = ts.timestamp();
                var duration = Math.abs(time - this.lastCancellationCheckTime);
                if (duration >= this.throttleWaitMilliseconds) {
                    // Check no more than once every throttle wait milliseconds
                    this.lastCancellationCheckTime = time;
                    return this.hostCancellationToken.isCancellationRequested();
                }
                return false;
            };
            ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () {
                if (this.isCancellationRequested()) {
                    throw new ts.OperationCanceledException();
                }
            };
            return ThrottledCancellationToken;
        }());
        ts.ThrottledCancellationToken = ThrottledCancellationToken;
        function createLanguageService(host, documentRegistry, syntaxOnly) {
            if (documentRegistry === void 0) {
                documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
            }
            if (syntaxOnly === void 0) {
                syntaxOnly = false;
            }
            var _a;
            var syntaxTreeCache = new SyntaxTreeCache(host);
            var program;
            var lastProjectVersion;
            var lastTypesRootVersion = 0;
            var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken());
            var currentDirectory = host.getCurrentDirectory();
            // Check if the localized messages json is set, otherwise query the host for it
            if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) {
                ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages();
            }
            function log(message) {
                if (host.log) {
                    host.log(message);
                }
            }
            var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
            var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
            var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; });
            function getValidSourceFile(fileName) {
                var sourceFile = program.getSourceFile(fileName);
                if (!sourceFile) {
                    throw new Error("Could not find file: '" + fileName + "'.");
                }
                return sourceFile;
            }
            function synchronizeHostData() {
                ts.Debug.assert(!syntaxOnly);
                // perform fast check if host supports it
                if (host.getProjectVersion) {
                    var hostProjectVersion = host.getProjectVersion();
                    if (hostProjectVersion) {
                        if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) {
                            return;
                        }
                        lastProjectVersion = hostProjectVersion;
                    }
                }
                var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0;
                if (lastTypesRootVersion !== typeRootsVersion) {
                    log("TypeRoots version has changed; provide new program");
                    program = undefined; // TODO: GH#18217
                    lastTypesRootVersion = typeRootsVersion;
                }
                // Get a fresh cache of the host information
                var hostCache = new HostCache(host, getCanonicalFileName);
                var rootFileNames = hostCache.getRootFileNames();
                var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
                var projectReferences = hostCache.getProjectReferences();
                // If the program is already up-to-date, we can reuse it
                if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
                    return;
                }
                // IMPORTANT - It is critical from this moment onward that we do not check
                // cancellation tokens.  We are about to mutate source files from a previous program
                // instance.  If we cancel midway through, we may end up in an inconsistent state where
                // the program points to old source files that have been invalidated because of
                // incremental parsing.
                var newSettings = hostCache.compilationSettings();
                // Now create a new compiler
                var compilerHost = {
                    getSourceFile: getOrCreateSourceFile,
                    getSourceFileByPath: getOrCreateSourceFileByPath,
                    getCancellationToken: function () { return cancellationToken; },
                    getCanonicalFileName: getCanonicalFileName,
                    useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
                    getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); },
                    getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
                    writeFile: ts.noop,
                    getCurrentDirectory: function () { return currentDirectory; },
                    fileExists: fileExists,
                    readFile: function (fileName) {
                        // stub missing host functionality
                        var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
                        var entry = hostCache && hostCache.getEntryByPath(path);
                        if (entry) {
                            return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot);
                        }
                        return host.readFile && host.readFile(fileName);
                    },
                    realpath: host.realpath && (function (path) { return host.realpath(path); }),
                    directoryExists: function (directoryName) {
                        return ts.directoryProbablyExists(directoryName, host);
                    },
                    getDirectories: function (path) {
                        return host.getDirectories ? host.getDirectories(path) : [];
                    },
                    readDirectory: function (path, extensions, exclude, include, depth) {
                        ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
                        return host.readDirectory(path, extensions, exclude, include, depth);
                    },
                    onReleaseOldSourceFile: onReleaseOldSourceFile,
                    hasInvalidatedResolution: hasInvalidatedResolution,
                    hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames
                };
                if (host.trace) {
                    compilerHost.trace = function (message) { return host.trace(message); };
                }
                if (host.resolveModuleNames) {
                    compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); };
                }
                if (host.resolveTypeReferenceDirectives) {
                    compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) {
                        return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile);
                    };
                }
                var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
                var options = {
                    rootNames: rootFileNames,
                    options: newSettings,
                    host: compilerHost,
                    oldProgram: program,
                    projectReferences: projectReferences
                };
                program = ts.createProgram(options);
                // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
                // It needs to be cleared to allow all collected snapshots to be released
                hostCache = undefined;
                // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above,
                // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during
                // the course of whatever called `synchronizeHostData`
                sourceMapper.clearCache();
                // Make sure all the nodes in the program are both bound, and have their parent
                // pointers set property.
                program.getTypeChecker();
                return;
                function fileExists(fileName) {
                    var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
                    var entry = hostCache && hostCache.getEntryByPath(path);
                    return entry ?
                        !ts.isString(entry) :
                        (!!host.fileExists && host.fileExists(fileName));
                }
                // Release any files we have acquired in the old program but are
                // not part of the new program.
                function onReleaseOldSourceFile(oldSourceFile, oldOptions) {
                    var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions);
                    documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey);
                }
                function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
                    return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile);
                }
                function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) {
                    ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");
                    // The program is asking for this file, check first if the host can locate it.
                    // If the host can not locate the file, then it does not exist. return undefined
                    // to the program to allow reporting of errors for missing files.
                    var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path);
                    if (!hostFileInformation) {
                        return undefined;
                    }
                    // Check if the language version has changed since we last created a program; if they are the same,
                    // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile
                    // can not be reused. we have to dump all syntax trees and create new ones.
                    if (!shouldCreateNewSourceFile) {
                        // Check if the old program had this file already
                        var oldSourceFile = program && program.getSourceFileByPath(path);
                        if (oldSourceFile) {
                            // We already had a source file for this file name.  Go to the registry to
                            // ensure that we get the right up to date version of it.  We need this to
                            // address the following race-condition.  Specifically, say we have the following:
                            //
                            //      LS1
                            //          \
                            //           DocumentRegistry
                            //          /
                            //      LS2
                            //
                            // Each LS has a reference to file 'foo.ts' at version 1.  LS2 then updates
                            // it's version of 'foo.ts' to version 2.  This will cause LS2 and the
                            // DocumentRegistry to have version 2 of the document.  HOwever, LS1 will
                            // have version 1.  And *importantly* this source file will be *corrupt*.
                            // The act of creating version 2 of the file irrevocably damages the version
                            // 1 file.
                            //
                            // So, later when we call into LS1, we need to make sure that it doesn't use
                            // it's source file any more, and instead defers to DocumentRegistry to get
                            // either version 1, version 2 (or some other version) depending on what the
                            // host says should be used.
                            // We do not support the scenario where a host can modify a registered
                            // file's script kind, i.e. in one project some file is treated as ".ts"
                            // and in another as ".js"
                            ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path);
                            return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
                        }
                        // We didn't already have the file.  Fall through and acquire it from the registry.
                    }
                    // Could not find this file in the old program, create a new SourceFile for it.
                    return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
                }
            }
            // TODO: GH#18217 frequently asserted as defined
            function getProgram() {
                if (syntaxOnly) {
                    ts.Debug.assert(program === undefined);
                    return undefined;
                }
                synchronizeHostData();
                return program;
            }
            function cleanupSemanticCache() {
                program = undefined; // TODO: GH#18217
            }
            function dispose() {
                if (program) {
                    ts.forEach(program.getSourceFiles(), function (f) {
                        return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions());
                    });
                    program = undefined; // TODO: GH#18217
                }
                host = undefined;
            }
            /// Diagnostics
            function getSyntacticDiagnostics(fileName) {
                synchronizeHostData();
                return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice();
            }
            /**
             * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors
             * If '-d' enabled, report both semantic and emitter errors
             */
            function getSemanticDiagnostics(fileName) {
                synchronizeHostData();
                var targetSourceFile = getValidSourceFile(fileName);
                // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
                // Therefore only get diagnostics for given file.
                var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
                if (!ts.getEmitDeclarations(program.getCompilerOptions())) {
                    return semanticDiagnostics.slice();
                }
                // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface
                var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
                return semanticDiagnostics.concat(declarationDiagnostics);
            }
            function getSuggestionDiagnostics(fileName) {
                synchronizeHostData();
                return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken);
            }
            function getCompilerOptionsDiagnostics() {
                synchronizeHostData();
                return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken));
            }
            function getCompletionsAtPosition(fileName, position, options) {
                if (options === void 0) {
                    options = ts.emptyOptions;
                }
                // Convert from deprecated options names to new names
                var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions });
                synchronizeHostData();
                return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter);
            }
            function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) {
                if (preferences === void 0) {
                    preferences = ts.emptyOptions;
                }
                synchronizeHostData();
                return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217
                preferences, cancellationToken);
            }
            function getCompletionEntrySymbol(fileName, position, name, source) {
                synchronizeHostData();
                return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source });
            }
            function getQuickInfoAtPosition(fileName, position) {
                synchronizeHostData();
                var sourceFile = getValidSourceFile(fileName);
                var node = ts.getTouchingPropertyName(sourceFile, position);
                if (node === sourceFile) {
                    // Avoid giving quickInfo for the sourceFile as a whole.
                    return undefined;
                }
                var typeChecker = program.getTypeChecker();
                var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
                if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
                    var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
                    return type_7 && {
                        kind: "" /* unknown */,
                        kindModifiers: "" /* none */,
                        textSpan: ts.createTextSpanFromNode(node, sourceFile),
                        displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }),
                        documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined,
                        tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined
                    };
                }
                var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
                    return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node);
                }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
                return {
                    kind: symbolKind,
                    kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
                    textSpan: ts.createTextSpanFromNode(node, sourceFile),
                    displayParts: displayParts,
                    documentation: documentation,
                    tags: tags,
                };
            }
            function shouldGetType(sourceFile, node, position) {
                switch (node.kind) {
                    case 71 /* Identifier */:
                        return !ts.isLabelName(node);
                    case 187 /* PropertyAccessExpression */:
                    case 146 /* QualifiedName */:
                        // Don't return quickInfo if inside the comment in `a/**/.b`
                        return !ts.isInComment(sourceFile, position);
                    case 99 /* ThisKeyword */:
                    case 176 /* ThisType */:
                    case 97 /* SuperKeyword */:
                        return true;
                    default:
                        return false;
                }
            }
            /// Goto definition
            function getDefinitionAtPosition(fileName, position) {
                synchronizeHostData();
                return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position);
            }
            function getDefinitionAndBoundSpan(fileName, position) {
                synchronizeHostData();
                return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position);
            }
            function getTypeDefinitionAtPosition(fileName, position) {
                synchronizeHostData();
                return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position);
            }
            /// Goto implementation
            function getImplementationAtPosition(fileName, position) {
                synchronizeHostData();
                return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
            }
            /// References and Occurrences
            function getOccurrencesAtPosition(fileName, position) {
                return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) {
                    return entry.highlightSpans.map(function (highlightSpan) {
                        return ({
                            fileName: entry.fileName,
                            textSpan: highlightSpan.textSpan,
                            isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */,
                            isDefinition: false,
                            isInString: highlightSpan.isInString,
                        });
                    });
                });
            }
            function getDocumentHighlights(fileName, position, filesToSearch) {
                var normalizedFileName = ts.normalizePath(fileName);
                ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; }));
                synchronizeHostData();
                var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); });
                var sourceFile = getValidSourceFile(fileName);
                return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
            }
            function findRenameLocations(fileName, position, findInStrings, findInComments) {
                synchronizeHostData();
                var sourceFile = getValidSourceFile(fileName);
                var node = ts.getTouchingPropertyName(sourceFile, position);
                if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) {
                    var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
                    return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); });
                }
                else {
                    var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true });
                    return refs && refs.map(function (_a) {
                        var fileName = _a.fileName, textSpan = _a.textSpan;
                        return ({ fileName: fileName, textSpan: textSpan });
                    });
                }
            }
            function getReferencesAtPosition(fileName, position) {
                synchronizeHostData();
                return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position);
            }
            function getReferences(node, position, options) {
                synchronizeHostData();
                // Exclude default library when renaming as commonly user don't want to change that file.
                var sourceFiles = options && options.isForRename
                    ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); })
                    : program.getSourceFiles();
                return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options);
            }
            function findReferences(fileName, position) {
                synchronizeHostData();
                return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
            }
            function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
                if (excludeDtsFiles === void 0) {
                    excludeDtsFiles = false;
                }
                synchronizeHostData();
                var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
                return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
            }
            function getEmitOutput(fileName, emitOnlyDtsFiles) {
                if (emitOnlyDtsFiles === void 0) {
                    emitOnlyDtsFiles = false;
                }
                synchronizeHostData();
                var sourceFile = getValidSourceFile(fileName);
                var customTransformers = host.getCustomTransformers && host.getCustomTransformers();
                return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers);
            }
            // Signature help
            /**
             * This is a semantic operation.
             */
            function getSignatureHelpItems(fileName, position, _a) {
                var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason;
                synchronizeHostData();
                var sourceFile = getValidSourceFile(fileName);
                return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken);
            }
            /// Syntactic features
            function getNonBoundSourceFile(fileName) {
                return syntaxTreeCache.getCurrentSourceFile(fileName);
            }
            function getNameOrDottedNameSpan(fileName, startPos, _endPos) {
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                // Get node at the location
                var node = ts.getTouchingPropertyName(sourceFile, startPos);
                if (node === sourceFile) {
                    return undefined;
                }
                switch (node.kind) {
                    case 187 /* PropertyAccessExpression */:
                    case 146 /* QualifiedName */:
                    case 9 /* StringLiteral */:
                    case 86 /* FalseKeyword */:
                    case 101 /* TrueKeyword */:
                    case 95 /* NullKeyword */:
                    case 97 /* SuperKeyword */:
                    case 99 /* ThisKeyword */:
                    case 176 /* ThisType */:
                    case 71 /* Identifier */:
                        break;
                    // Cant create the text span
                    default:
                        return undefined;
                }
                var nodeForStartPos = node;
                while (true) {
                    if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) {
                        // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node
                        nodeForStartPos = nodeForStartPos.parent;
                    }
                    else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) {
                        // If this is name of a module declarations, check if this is right side of dotted module name
                        // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of
                        // Then this name is name from dotted module
                        if (nodeForStartPos.parent.parent.kind === 242 /* ModuleDeclaration */ &&
                            nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
                            // Use parent module declarations name for start pos
                            nodeForStartPos = nodeForStartPos.parent.parent.name;
                        }
                        else {
                            // We have to use this name for start pos
                            break;
                        }
                    }
                    else {
                        // Is not a member expression so we have found the node for start pos
                        break;
                    }
                }
                return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd());
            }
            function getBreakpointStatementAtPosition(fileName, position) {
                // doesn't use compiler - no need to synchronize with host
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position);
            }
            function getNavigationBarItems(fileName) {
                return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
            }
            function getNavigationTree(fileName) {
                return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
            }
            function isTsOrTsxFile(fileName) {
                var kind = ts.getScriptKind(fileName, host);
                return kind === 3 /* TS */ || kind === 4 /* TSX */;
            }
            function getSemanticClassifications(fileName, span) {
                if (!isTsOrTsxFile(fileName)) {
                    // do not run semantic classification on non-ts-or-tsx files
                    return [];
                }
                synchronizeHostData();
                return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
            }
            function getEncodedSemanticClassifications(fileName, span) {
                if (!isTsOrTsxFile(fileName)) {
                    // do not run semantic classification on non-ts-or-tsx files
                    return { spans: [], endOfLineState: 0 /* None */ };
                }
                synchronizeHostData();
                return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
            }
            function getSyntacticClassifications(fileName, span) {
                // doesn't use compiler - no need to synchronize with host
                return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
            }
            function getEncodedSyntacticClassifications(fileName, span) {
                // doesn't use compiler - no need to synchronize with host
                return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
            }
            function getOutliningSpans(fileName) {
                // doesn't use compiler - no need to synchronize with host
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken);
            }
            var braceMatching = ts.createMapFromTemplate((_a = {},
                _a[17 /* OpenBraceToken */] = 18 /* CloseBraceToken */,
                _a[19 /* OpenParenToken */] = 20 /* CloseParenToken */,
                _a[21 /* OpenBracketToken */] = 22 /* CloseBracketToken */,
                _a[29 /* GreaterThanToken */] = 27 /* LessThanToken */,
                _a));
            braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); });
            function getBraceMatchingAtPosition(fileName, position) {
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                var token = ts.getTouchingToken(sourceFile, position);
                var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined;
                var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile);
                // We want to order the braces when we return the result.
                return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray;
            }
            function getIndentationAtPosition(fileName, position, editorOptions) {
                var start = ts.timestamp();
                var settings = toEditorSettings(editorOptions);
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
                start = ts.timestamp();
                var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
                log("getIndentationAtPosition: computeIndentation  : " + (ts.timestamp() - start));
                return result;
            }
            function getFormattingEditsForRange(fileName, start, end, options) {
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options)));
            }
            function getFormattingEditsForDocument(fileName, options) {
                return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options)));
            }
            function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                var formatContext = ts.formatting.getFormatContext(toEditorSettings(options));
                if (!ts.isInComment(sourceFile, position)) {
                    switch (key) {
                        case "{":
                            return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext);
                        case "}":
                            return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext);
                        case ";":
                            return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext);
                        case "\n":
                            return ts.formatting.formatOnEnter(position, sourceFile, formatContext);
                    }
                }
                return [];
            }
            function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) {
                if (preferences === void 0) {
                    preferences = ts.emptyOptions;
                }
                synchronizeHostData();
                var sourceFile = getValidSourceFile(fileName);
                var span = ts.createTextSpanFromBounds(start, end);
                var formatContext = ts.formatting.getFormatContext(formatOptions);
                return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) {
                    cancellationToken.throwIfCancellationRequested();
                    return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
                });
            }
            function getCombinedCodeFix(scope, fixId, formatOptions, preferences) {
                if (preferences === void 0) {
                    preferences = ts.emptyOptions;
                }
                synchronizeHostData();
                ts.Debug.assert(scope.type === "file");
                var sourceFile = getValidSourceFile(scope.fileName);
                var formatContext = ts.formatting.getFormatContext(formatOptions);
                return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
            }
            function organizeImports(scope, formatOptions, preferences) {
                if (preferences === void 0) {
                    preferences = ts.emptyOptions;
                }
                synchronizeHostData();
                ts.Debug.assert(scope.type === "file");
                var sourceFile = getValidSourceFile(scope.fileName);
                var formatContext = ts.formatting.getFormatContext(formatOptions);
                return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences);
            }
            function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) {
                if (preferences === void 0) {
                    preferences = ts.emptyOptions;
                }
                return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper);
            }
            function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) {
                var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName;
                var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined;
                return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings);
            }
            function applySingleCodeActionCommand(action, formatSettings) {
                var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); };
                switch (action.type) {
                    case "install package":
                        return host.installPackage
                            ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName })
                            : Promise.reject("Host does not implement `installPackage`");
                    case "generate types": {
                        var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName;
                        if (!host.inspectValue)
                            return Promise.reject("Host does not implement `installPackage`");
                        var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor });
                        return valueInfoPromise.then(function (valueInfo) {
                            var fullOut = getPath(outputFileName_1);
                            host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217
                            return { successMessage: "Wrote types to '" + fullOut + "'" };
                        });
                    }
                    default:
                        return ts.Debug.assertNever(action);
                }
            }
            function getDocCommentTemplateAtPosition(fileName, position) {
                return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position);
            }
            function isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
                // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too
                // expensive to do during typing scenarios
                // i.e. whether we're dealing with:
                //      var x = new foo<| ( with class foo<T>{} )
                // or
                //      var y = 3 <|
                if (openingBrace === 60 /* lessThan */) {
                    return false;
                }
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                // Check if in a context where we don't want to perform any insertion
                if (ts.isInString(sourceFile, position)) {
                    return false;
                }
                if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) {
                    return openingBrace === 123 /* openBrace */;
                }
                if (ts.isInTemplateString(sourceFile, position)) {
                    return false;
                }
                switch (openingBrace) {
                    case 39 /* singleQuote */:
                    case 34 /* doubleQuote */:
                    case 96 /* backtick */:
                        return !ts.isInComment(sourceFile, position);
                }
                return true;
            }
            function getJsxClosingTagAtPosition(fileName, position) {
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                var token = ts.findPrecedingToken(position, sourceFile);
                if (!token)
                    return undefined;
                var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent
                    : ts.isJsxText(token) ? token.parent : undefined;
                if (element && isUnclosedTag(element)) {
                    return { newText: "</" + element.openingElement.tagName.getText(sourceFile) + ">" };
                }
            }
            function isUnclosedTag(_a) {
                var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent;
                return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) ||
                    ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent);
            }
            function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
                var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
                var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position);
                return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined;
            }
            function getTodoComments(fileName, descriptors) {
                // Note: while getting todo comments seems like a syntactic operation, we actually
                // treat it as a semantic operation here.  This is because we expect our host to call
                // this on every single file.  If we treat this syntactically, then that will cause
                // us to populate and throw away the tree in our syntax tree cache for each file.  By
                // treating this as a semantic operation, we can access any tree without throwing
                // anything away.
                synchronizeHostData();
                var sourceFile = getValidSourceFile(fileName);
                cancellationToken.throwIfCancellationRequested();
                var fileContents = sourceFile.text;
                var result = [];
                // Exclude node_modules files as we don't want to show the todos of external libraries.
                if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) {
                    var regExp = getTodoCommentsRegExp();
                    var matchArray = void 0;
                    while (matchArray = regExp.exec(fileContents)) {
                        cancellationToken.throwIfCancellationRequested();
                        // If we got a match, here is what the match array will look like.  Say the source text is:
                        //
                        //      "    // hack   1"
                        //
                        // The result array with the regexp:    will be:
                        //
                        //      ["// hack   1", "// ", "hack   1", undefined, "hack"]
                        //
                        // Here are the relevant capture groups:
                        //  0) The full match for the entire regexp.
                        //  1) The preamble to the message portion.
                        //  2) The message portion.
                        //  3...N) The descriptor that was matched - by index.  'undefined' for each
                        //         descriptor that didn't match.  an actual value if it did match.
                        //
                        //  i.e. 'undefined' in position 3 above means TODO(jason) didn't match.
                        //       "hack"      in position 4 means HACK did match.
                        var firstDescriptorCaptureIndex = 3;
                        ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex);
                        var preamble = matchArray[1];
                        var matchPosition = matchArray.index + preamble.length;
                        // OK, we have found a match in the file.  This is only an acceptable match if
                        // it is contained within a comment.
                        if (!ts.isInComment(sourceFile, matchPosition)) {
                            continue;
                        }
                        var descriptor = void 0;
                        for (var i = 0; i < descriptors.length; i++) {
                            if (matchArray[i + firstDescriptorCaptureIndex]) {
                                descriptor = descriptors[i];
                            }
                        }
                        if (descriptor === undefined)
                            return ts.Debug.fail();
                        // We don't want to match something like 'TODOBY', so we make sure a non
                        // letter/digit follows the match.
                        if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) {
                            continue;
                        }
                        var message = matchArray[2];
                        result.push({ descriptor: descriptor, message: message, position: matchPosition });
                    }
                }
                return result;
                function escapeRegExp(str) {
                    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
                }
                function getTodoCommentsRegExp() {
                    // NOTE: `?:` means 'non-capture group'.  It allows us to have groups without having to
                    // filter them out later in the final result array.
                    // TODO comments can appear in one of the following forms:
                    //
                    //  1)      // TODO     or  /////////// TODO
                    //
                    //  2)      /* TODO     or  /********** TODO
                    //
                    //  3)      /*
                    //           *   TODO
                    //           */
                    //
                    // The following three regexps are used to match the start of the text up to the TODO
                    // comment portion.
                    var singleLineCommentStart = /(?:\/\/+\s*)/.source;
                    var multiLineCommentStart = /(?:\/\*+\s*)/.source;
                    var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
                    // Match any of the above three TODO comment start regexps.
                    // Note that the outermost group *is* a capture group.  We want to capture the preamble
                    // so that we can determine the starting position of the TODO comment match.
                    var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
                    // Takes the descriptors and forms a regexp that matches them as if they were literals.
                    // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be:
                    //
                    //      (?:(TODO\(jason\))|(HACK))
                    //
                    // Note that the outermost group is *not* a capture group, but the innermost groups
                    // *are* capture groups.  By capturing the inner literals we can determine after
                    // matching which descriptor we are dealing with.
                    var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")";
                    // After matching a descriptor literal, the following regexp matches the rest of the
                    // text up to the end of the line (or */).
                    var endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
                    var messageRemainder = /(?:.*?)/.source;
                    // This is the portion of the match we'll return as part of the TODO comment result. We
                    // match the literal portion up to the end of the line or end of comment.
                    var messagePortion = "(" + literals + messageRemainder + ")";
                    var regExpString = preamble + messagePortion + endOfLineOrEndOfComment;
                    // The final regexp will look like this:
                    // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim
                    // The flags of the regexp are important here.
                    //  'g' is so that we are doing a global search and can find matches several times
                    //  in the input.
                    //
                    //  'i' is for case insensitivity (We do this to match C# TODO comment code).
                    //
                    //  'm' is so we can find matches in a multi-line input.
                    return new RegExp(regExpString, "gim");
                }
                function isLetterOrDigit(char) {
                    return (char >= 97 /* a */ && char <= 122 /* z */) ||
                        (char >= 65 /* A */ && char <= 90 /* Z */) ||
                        (char >= 48 /* _0 */ && char <= 57 /* _9 */);
                }
                function isNodeModulesFile(path) {
                    return ts.stringContains(path, "/node_modules/");
                }
            }
            function getRenameInfo(fileName, position) {
                synchronizeHostData();
                return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position);
            }
            function getRefactorContext(file, positionOrRange, preferences, formatOptions) {
                var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1];
                return {
                    file: file,
                    startPosition: startPosition,
                    endPosition: endPosition,
                    program: getProgram(),
                    host: host,
                    formatContext: ts.formatting.getFormatContext(formatOptions),
                    cancellationToken: cancellationToken,
                    preferences: preferences,
                };
            }
            function getApplicableRefactors(fileName, positionOrRange, preferences) {
                if (preferences === void 0) {
                    preferences = ts.emptyOptions;
                }
                synchronizeHostData();
                var file = getValidSourceFile(fileName);
                return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences));
            }
            function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) {
                if (preferences === void 0) {
                    preferences = ts.emptyOptions;
                }
                synchronizeHostData();
                var file = getValidSourceFile(fileName);
                return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName);
            }
            return {
                dispose: dispose,
                cleanupSemanticCache: cleanupSemanticCache,
                getSyntacticDiagnostics: getSyntacticDiagnostics,
                getSemanticDiagnostics: getSemanticDiagnostics,
                getSuggestionDiagnostics: getSuggestionDiagnostics,
                getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
                getSyntacticClassifications: getSyntacticClassifications,
                getSemanticClassifications: getSemanticClassifications,
                getEncodedSyntacticClassifications: getEncodedSyntacticClassifications,
                getEncodedSemanticClassifications: getEncodedSemanticClassifications,
                getCompletionsAtPosition: getCompletionsAtPosition,
                getCompletionEntryDetails: getCompletionEntryDetails,
                getCompletionEntrySymbol: getCompletionEntrySymbol,
                getSignatureHelpItems: getSignatureHelpItems,
                getQuickInfoAtPosition: getQuickInfoAtPosition,
                getDefinitionAtPosition: getDefinitionAtPosition,
                getDefinitionAndBoundSpan: getDefinitionAndBoundSpan,
                getImplementationAtPosition: getImplementationAtPosition,
                getTypeDefinitionAtPosition: getTypeDefinitionAtPosition,
                getReferencesAtPosition: getReferencesAtPosition,
                findReferences: findReferences,
                getOccurrencesAtPosition: getOccurrencesAtPosition,
                getDocumentHighlights: getDocumentHighlights,
                getNameOrDottedNameSpan: getNameOrDottedNameSpan,
                getBreakpointStatementAtPosition: getBreakpointStatementAtPosition,
                getNavigateToItems: getNavigateToItems,
                getRenameInfo: getRenameInfo,
                findRenameLocations: findRenameLocations,
                getNavigationBarItems: getNavigationBarItems,
                getNavigationTree: getNavigationTree,
                getOutliningSpans: getOutliningSpans,
                getTodoComments: getTodoComments,
                getBraceMatchingAtPosition: getBraceMatchingAtPosition,
                getIndentationAtPosition: getIndentationAtPosition,
                getFormattingEditsForRange: getFormattingEditsForRange,
                getFormattingEditsForDocument: getFormattingEditsForDocument,
                getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke,
                getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition,
                isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition,
                getJsxClosingTagAtPosition: getJsxClosingTagAtPosition,
                getSpanOfEnclosingComment: getSpanOfEnclosingComment,
                getCodeFixesAtPosition: getCodeFixesAtPosition,
                getCombinedCodeFix: getCombinedCodeFix,
                applyCodeActionCommand: applyCodeActionCommand,
                organizeImports: organizeImports,
                getEditsForFileRename: getEditsForFileRename,
                getEmitOutput: getEmitOutput,
                getNonBoundSourceFile: getNonBoundSourceFile,
                getProgram: getProgram,
                getApplicableRefactors: getApplicableRefactors,
                getEditsForRefactor: getEditsForRefactor,
                toLineColumnOffset: sourceMapper.toLineColumnOffset,
                getSourceMapper: function () { return sourceMapper; },
            };
        }
        ts.createLanguageService = createLanguageService;
        /* @internal */
        /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */
        function getNameTable(sourceFile) {
            if (!sourceFile.nameTable) {
                initializeNameTable(sourceFile);
            }
            return sourceFile.nameTable; // TODO: GH#18217
        }
        ts.getNameTable = getNameTable;
        function initializeNameTable(sourceFile) {
            var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
            sourceFile.forEachChild(function walk(node) {
                if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
                    var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
                    nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
                }
                ts.forEachChild(node, walk);
                if (ts.hasJSDocNodes(node)) {
                    for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
                        var jsDoc = _a[_i];
                        ts.forEachChild(jsDoc, walk);
                    }
                }
            });
        }
        /**
         * We want to store any numbers/strings if they were a name that could be
         * related to a declaration.  So, if we have 'import x = require("something")'
         * then we want 'something' to be in the name table.  Similarly, if we have
         * "a['propname']" then we want to store "propname" in the name table.
         */
        function literalIsName(node) {
            return ts.isDeclarationName(node) ||
                node.parent.kind === 257 /* ExternalModuleReference */ ||
                isArgumentOfElementAccessExpression(node) ||
                ts.isLiteralComputedPropertyDeclarationName(node);
        }
        /**
         * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }
         */
        /* @internal */
        function getContainingObjectLiteralElement(node) {
            var element = getContainingObjectLiteralElementWorker(node);
            return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined;
        }
        ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement;
        function getContainingObjectLiteralElementWorker(node) {
            switch (node.kind) {
                case 9 /* StringLiteral */:
                case 8 /* NumericLiteral */:
                    if (node.parent.kind === 147 /* ComputedPropertyName */) {
                        return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined;
                    }
                // falls through
                case 71 /* Identifier */:
                    return ts.isObjectLiteralElement(node.parent) &&
                        (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) &&
                        node.parent.name === node ? node.parent : undefined;
            }
            return undefined;
        }
        function getSymbolAtLocationForQuickInfo(node, checker) {
            var object = getContainingObjectLiteralElement(node);
            if (object) {
                var contextualType = checker.getContextualType(object.parent);
                var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false);
                if (properties && properties.length === 1) {
                    return ts.first(properties);
                }
            }
            return checker.getSymbolAtLocation(node);
        }
        /** Gets all symbols for one property. Does not get symbols for every property. */
        /* @internal */
        function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) {
            var name = ts.getNameFromPropertyName(node.name);
            if (!name)
                return ts.emptyArray;
            if (!contextualType.isUnion()) {
                var symbol = contextualType.getProperty(name);
                return symbol ? [symbol] : ts.emptyArray;
            }
            var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); });
            if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) {
                var symbol = contextualType.getProperty(name);
                if (symbol)
                    return [symbol];
            }
            if (discriminatedPropertySymbols.length === 0) {
                // Bad discriminant -- do again without discriminating
                return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); });
            }
            return discriminatedPropertySymbols;
        }
        ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType;
        function isArgumentOfElementAccessExpression(node) {
            return node &&
                node.parent &&
                node.parent.kind === 188 /* ElementAccessExpression */ &&
                node.parent.argumentExpression === node;
        }
        /**
         * Get the path of the default library files (lib.d.ts) as distributed with the typescript
         * node package.
         * The functionality is not supported if the ts module is consumed outside of a node module.
         */
        function getDefaultLibFilePath(options) {
            // Check __dirname is defined and that we are on a node.js system.
            if (typeof __dirname !== "undefined") {
                return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options);
            }
            throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
        }
        ts.getDefaultLibFilePath = getDefaultLibFilePath;
        ts.objectAllocator = getServicesObjectAllocator();
    })(ts || (ts = {}));
    /* @internal */
    var ts;
    (function (ts) {
        var BreakpointResolver;
        (function (BreakpointResolver) {
            /**
             * Get the breakpoint span in given sourceFile
             */
            function spanInSourceFileAtLocation(sourceFile, position) {
                // Cannot set breakpoint in dts file
                if (sourceFile.isDeclarationFile) {
                    return undefined;
                }
                var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position);
                var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
                if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
                    // Get previous token if the token is returned starts on new line
                    // eg: let x =10; |--- cursor is here
                    //     let y = 10;
                    // token at position will return let keyword on second line as the token but we would like to use
                    // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
                    var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile);
                    // It's a blank line
                    if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) {
                        return undefined;
                    }
                    tokenAtLocation = preceding;
                }
                // Cannot set breakpoint in ambient declarations
                if (tokenAtLocation.flags & 4194304 /* Ambient */) {
                    return undefined;
                }
                // Get the span in the node based on its syntax
                return spanInNode(tokenAtLocation);
                function textSpan(startNode, endNode) {
                    var start = startNode.decorators ?
                        ts.skipTrivia(sourceFile.text, startNode.decorators.end) :
                        startNode.getStart(sourceFile);
                    return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
                }
                function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
                    return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
                }
                function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
                    if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
                        return spanInNode(node);
                    }
                    return spanInNode(otherwiseOnNode);
                }
                function spanInNodeArray(nodeArray) {
                    return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
                }
                function spanInPreviousNode(node) {
                    return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
                }
                function spanInNextNode(node) {
                    return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
                }
                function spanInNode(node) {
                    if (node) {
                        var parent = node.parent;
                        switch (node.kind) {
                            case 217 /* VariableStatement */:
                                // Span on first variable declaration
                                return spanInVariableDeclaration(node.declarationList.declarations[0]);
                            case 235 /* VariableDeclaration */:
                            case 152 /* PropertyDeclaration */:
                            case 151 /* PropertySignature */:
                                return spanInVariableDeclaration(node);
                            case 149 /* Parameter */:
                                return spanInParameterDeclaration(node);
                            case 237 /* FunctionDeclaration */:
                            case 154 /* MethodDeclaration */:
                            case 153 /* MethodSignature */:
                            case 156 /* GetAccessor */:
                            case 157 /* SetAccessor */:
                            case 155 /* Constructor */:
                            case 194 /* FunctionExpression */:
                            case 195 /* ArrowFunction */:
                                return spanInFunctionDeclaration(node);
                            case 216 /* Block */:
                                if (ts.isFunctionBlock(node)) {
                                    return spanInFunctionBlock(node);
                                }
                            // falls through
                            case 243 /* ModuleBlock */:
                                return spanInBlock(node);
                            case 272 /* CatchClause */:
                                return spanInBlock(node.block);
                            case 219 /* ExpressionStatement */:
                                // span on the expression
                                return textSpan(node.expression);
                            case 228 /* ReturnStatement */:
                                // span on return keyword and expression if present
                                return textSpan(node.getChildAt(0), node.expression);
                            case 222 /* WhileStatement */:
                                // Span on while(...)
                                return textSpanEndingAtNextToken(node, node.expression);
                            case 221 /* DoStatement */:
                                // span in statement of the do statement
                                return spanInNode(node.statement);
                            case 234 /* DebuggerStatement */:
                                // span on debugger keyword
                                return textSpan(node.getChildAt(0));
                            case 220 /* IfStatement */:
                                // set on if(..) span
                                return textSpanEndingAtNextToken(node, node.expression);
                            case 231 /* LabeledStatement */:
                                // span in statement
                                return spanInNode(node.statement);
                            case 227 /* BreakStatement */:
                            case 226 /* ContinueStatement */:
                                // On break or continue keyword and label if present
                                return textSpan(node.getChildAt(0), node.label);
                            case 223 /* ForStatement */:
                                return spanInForStatement(node);
                            case 224 /* ForInStatement */:
                                // span of for (a in ...)
                                return textSpanEndingAtNextToken(node, node.expression);
                            case 225 /* ForOfStatement */:
                                // span in initializer
                                return spanInInitializerOfForLike(node);
                            case 230 /* SwitchStatement */:
                                // span on switch(...)
                                return textSpanEndingAtNextToken(node, node.expression);
                            case 269 /* CaseClause */:
                            case 270 /* DefaultClause */:
                                // span in first statement of the clause
                                return spanInNode(node.statements[0]);
                            case 233 /* TryStatement */:
                                // span in try block
                                return spanInBlock(node.tryBlock);
                            case 232 /* ThrowStatement */:
                                // span in throw ...
                                return textSpan(node, node.expression);
                            case 252 /* ExportAssignment */:
                                // span on export = id
                                return textSpan(node, node.expression);
                            case 246 /* ImportEqualsDeclaration */:
                                // import statement without including semicolon
                                return textSpan(node, node.moduleReference);
                            case 247 /* ImportDeclaration */:
                                // import statement without including semicolon
                                return textSpan(node, node.moduleSpecifier);
                            case 253 /* ExportDeclaration */:
                                // import statement without including semicolon
                                return textSpan(node, node.moduleSpecifier);
                            case 242 /* ModuleDeclaration */:
                                // span on complete module if it is instantiated
                                if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
                                    return undefined;
                                }
                            // falls through
                            case 238 /* ClassDeclaration */:
                            case 241 /* EnumDeclaration */:
                            case 276 /* EnumMember */:
                            case 184 /* BindingElement */:
                                // span on complete node
                                return textSpan(node);
                            case 229 /* WithStatement */:
                                // span in statement
                                return spanInNode(node.statement);
                            case 150 /* Decorator */:
                                return spanInNodeArray(parent.decorators);
                            case 182 /* ObjectBindingPattern */:
                            case 183 /* ArrayBindingPattern */:
                                return spanInBindingPattern(node);
                            // No breakpoint in interface, type alias
                            case 239 /* InterfaceDeclaration */:
                            case 240 /* TypeAliasDeclaration */:
                                return undefined;
                            // Tokens:
                            case 25 /* SemicolonToken */:
                            case 1 /* EndOfFileToken */:
                                return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile));
                            case 26 /* CommaToken */:
                                return spanInPreviousNode(node);
                            case 17 /* OpenBraceToken */:
                                return spanInOpenBraceToken(node);
                            case 18 /* CloseBraceToken */:
                                return spanInCloseBraceToken(node);
                            case 22 /* CloseBracketToken */:
                                return spanInCloseBracketToken(node);
                            case 19 /* OpenParenToken */:
                                return spanInOpenParenToken(node);
                            case 20 /* CloseParenToken */:
                                return spanInCloseParenToken(node);
                            case 56 /* ColonToken */:
                                return spanInColonToken(node);
                            case 29 /* GreaterThanToken */:
                            case 27 /* LessThanToken */:
                                return spanInGreaterThanOrLessThanToken(node);
                            // Keywords:
                            case 106 /* WhileKeyword */:
                                return spanInWhileKeyword(node);
                            case 82 /* ElseKeyword */:
                            case 74 /* CatchKeyword */:
                            case 87 /* FinallyKeyword */:
                                return spanInNextNode(node);
                            case 145 /* OfKeyword */:
                                return spanInOfKeyword(node);
                            default:
                                // Destructuring pattern in destructuring assignment
                                // [a, b, c] of
                                // [a, b, c] = expression
                                if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
                                    return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node);
                                }
                                // Set breakpoint on identifier element of destructuring pattern
                                // `a` or `...c` or `d: x` from
                                // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern
                                if ((node.kind === 71 /* Identifier */ ||
                                    node.kind === 206 /* SpreadElement */ ||
                                    node.kind === 273 /* PropertyAssignment */ ||
                                    node.kind === 274 /* ShorthandPropertyAssignment */) &&
                                    ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) {
                                    return textSpan(node);
                                }
                                if (node.kind === 202 /* BinaryExpression */) {
                                    var _a = node, left = _a.left, operatorToken = _a.operatorToken;
                                    // Set breakpoint in destructuring pattern if its destructuring assignment
                                    // [a, b, c] or {a, b, c} of
                                    // [a, b, c] = expression or
                                    // {a, b, c} = expression
                                    if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
                                        return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
                                    }
                                    if (operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
                                        // Set breakpoint on assignment expression element of destructuring pattern
                                        // a = expression of
                                        // [a = expression, b, c] = someExpression or
                                        // { a = expression, b, c } = someExpression
                                        return textSpan(node);
                                    }
                                    if (operatorToken.kind === 26 /* CommaToken */) {
                                        return spanInNode(left);
                                    }
                                }
                                if (ts.isExpressionNode(node)) {
                                    switch (parent.kind) {
                                        case 221 /* DoStatement */:
                                            // Set span as if on while keyword
                                            return spanInPreviousNode(node);
                                        case 150 /* Decorator */:
                                            // Set breakpoint on the decorator emit
                                            return spanInNode(node.parent);
                                        case 223 /* ForStatement */:
                                        case 225 /* ForOfStatement */:
                                            return textSpan(node);
                                        case 202 /* BinaryExpression */:
                                            if (node.parent.operatorToken.kind === 26 /* CommaToken */) {
                                                // If this is a comma expression, the breakpoint is possible in this expression
                                                return textSpan(node);
                                            }
                                            break;
                                        case 195 /* ArrowFunction */:
                                            if (node.parent.body === node) {
                                                // If this is body of arrow function, it is allowed to have the breakpoint
                                                return textSpan(node);
                                            }
                                            break;
                                    }
                                }
                                switch (node.parent.kind) {
                                    case 273 /* PropertyAssignment */:
                                        // If this is name of property assignment, set breakpoint in the initializer
                                        if (node.parent.name === node &&
                                            !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
                                            return spanInNode(node.parent.initializer);
                                        }
                                        break;
                                    case 192 /* TypeAssertionExpression */:
                                        // Breakpoint in type assertion goes to its operand
                                        if (node.parent.type === node) {
                                            return spanInNextNode(node.parent.type);
                                        }
                                        break;
                                    case 235 /* VariableDeclaration */:
                                    case 149 /* Parameter */: {
                                        // initializer of variable/parameter declaration go to previous node
                                        var _b = node.parent, initializer = _b.initializer, type = _b.type;
                                        if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) {
                                            return spanInPreviousNode(node);
                                        }
                                        break;
                                    }
                                    case 202 /* BinaryExpression */: {
                                        var left = node.parent.left;
                                        if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
                                            // If initializer of destructuring assignment move to previous token
                                            return spanInPreviousNode(node);
                                        }
                                        break;
                                    }
                                    default:
                                        // return type of function go to previous token
                                        if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
                                            return spanInPreviousNode(node);
                                        }
                                }
                                // Default go to parent to set the breakpoint
                                return spanInNode(node.parent);
                        }
                    }
                    function textSpanFromVariableDeclaration(variableDeclaration) {
                        if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
                            // First declaration - include let keyword
                            return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
                        }
                        else {
                            // Span only on this declaration
                            return textSpan(variableDeclaration);
                        }
                    }
                    function spanInVariableDeclaration(variableDeclaration) {
                        // If declaration of for in statement, just set the span in parent
                        if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) {
                            return spanInNode(variableDeclaration.parent.parent);
                        }
                        var parent = variableDeclaration.parent;
                        // If this is a destructuring pattern, set breakpoint in binding pattern
                        if (ts.isBindingPattern(variableDeclaration.name)) {
                            return spanInBindingPattern(variableDeclaration.name);
                        }
                        // Breakpoint is possible in variableDeclaration only if there is initialization
                        // or its declaration from 'for of'
                        if (variableDeclaration.initializer ||
                            ts.hasModifier(variableDeclaration, 1 /* Export */) ||
                            parent.parent.kind === 225 /* ForOfStatement */) {
                            return textSpanFromVariableDeclaration(variableDeclaration);
                        }
                        if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
                            variableDeclaration.parent.declarations[0] !== variableDeclaration) {
                            // If we cannot set breakpoint on this declaration, set it on previous one
                            // Because the variable declaration may be binding pattern and
                            // we would like to set breakpoint in last binding element if that's the case,
                            // use preceding token instead
                            return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
                        }
                    }
                    function canHaveSpanInParameterDeclaration(parameter) {
                        // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier
                        return !!parameter.initializer || parameter.dotDotDotToken !== undefined ||
                            ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */);
                    }
                    function spanInParameterDeclaration(parameter) {
                        if (ts.isBindingPattern(parameter.name)) {
                            // Set breakpoint in binding pattern
                            return spanInBindingPattern(parameter.name);
                        }
                        else if (canHaveSpanInParameterDeclaration(parameter)) {
                            return textSpan(parameter);
                        }
                        else {
                            var functionDeclaration = parameter.parent;
                            var indexOfParameter = functionDeclaration.parameters.indexOf(parameter);
                            ts.Debug.assert(indexOfParameter !== -1);
                            if (indexOfParameter !== 0) {
                                // Not a first parameter, go to previous parameter
                                return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
                            }
                            else {
                                // Set breakpoint in the function declaration body
                                return spanInNode(functionDeclaration.body);
                            }
                        }
                    }
                    function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
                        return ts.hasModifier(functionDeclaration, 1 /* Export */) ||
                            (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */);
                    }
                    function spanInFunctionDeclaration(functionDeclaration) {
                        // No breakpoints in the function signature
                        if (!functionDeclaration.body) {
                            return undefined;
                        }
                        if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
                            // Set the span on whole function declaration
                            return textSpan(functionDeclaration);
                        }
                        // Set span in function body
                        return spanInNode(functionDeclaration.body);
                    }
                    function spanInFunctionBlock(block) {
                        var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
                        if (canFunctionHaveSpanInWholeDeclaration(block.parent)) {
                            return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
                        }
                        return spanInNode(nodeForSpanInBlock);
                    }
                    function spanInBlock(block) {
                        switch (block.parent.kind) {
                            case 242 /* ModuleDeclaration */:
                                if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
                                    return undefined;
                                }
                            // falls through
                            // Set on parent if on same line otherwise on first statement
                            case 222 /* WhileStatement */:
                            case 220 /* IfStatement */:
                            case 224 /* ForInStatement */:
                                return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
                            // Set span on previous token if it starts on same line otherwise on the first statement of the block
                            case 223 /* ForStatement */:
                            case 225 /* ForOfStatement */:
                                return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
                        }
                        // Default action is to set on first statement
                        return spanInNode(block.statements[0]);
                    }
                    function spanInInitializerOfForLike(forLikeStatement) {
                        if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) {
                            // Declaration list - set breakpoint in first declaration
                            var variableDeclarationList = forLikeStatement.initializer;
                            if (variableDeclarationList.declarations.length > 0) {
                                return spanInNode(variableDeclarationList.declarations[0]);
                            }
                        }
                        else {
                            // Expression - set breakpoint in it
                            return spanInNode(forLikeStatement.initializer);
                        }
                    }
                    function spanInForStatement(forStatement) {
                        if (forStatement.initializer) {
                            return spanInInitializerOfForLike(forStatement);
                        }
                        if (forStatement.condition) {
                            return textSpan(forStatement.condition);
                        }
                        if (forStatement.incrementor) {
                            return textSpan(forStatement.incrementor);
                        }
                    }
                    function spanInBindingPattern(bindingPattern) {
                        // Set breakpoint in first binding element
                        var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; });
                        if (firstBindingElement) {
                            return spanInNode(firstBindingElement);
                        }
                        // Empty binding pattern of binding element, set breakpoint on binding element
                        if (bindingPattern.parent.kind === 184 /* BindingElement */) {
                            return textSpan(bindingPattern.parent);
                        }
                        // Variable declaration is used as the span
                        return textSpanFromVariableDeclaration(bindingPattern.parent);
                    }
                    function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) {
                        ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */);
                        var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties;
                        var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; });
                        if (firstBindingElement) {
                            return spanInNode(firstBindingElement);
                        }
                        // Could be ArrayLiteral from destructuring assignment or
                        // just nested element in another destructuring assignment
                        // set breakpoint on assignment when parent is destructuring assignment
                        // Otherwise set breakpoint for this element
                        return textSpan(node.parent.kind === 202 /* BinaryExpression */ ? node.parent : node);
                    }
                    // Tokens:
                    function spanInOpenBraceToken(node) {
                        switch (node.parent.kind) {
                            case 241 /* EnumDeclaration */:
                                var enumDeclaration = node.parent;
                                return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
                            case 238 /* ClassDeclaration */:
                                var classDeclaration = node.parent;
                                return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
                            case 244 /* CaseBlock */:
                                return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]);
                        }
                        // Default to parent node
                        return spanInNode(node.parent);
                    }
                    function spanInCloseBraceToken(node) {
                        switch (node.parent.kind) {
                            case 243 /* ModuleBlock */:
                                // If this is not an instantiated module block, no bp span
                                if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) {
                                    return undefined;
                                }
                            // falls through
                            case 241 /* EnumDeclaration */:
                            case 238 /* ClassDeclaration */:
                                // Span on close brace token
                                return textSpan(node);
                            case 216 /* Block */:
                                if (ts.isFunctionBlock(node.parent)) {
                                    // Span on close brace token
                                    return textSpan(node);
                                }
                            // falls through
                            case 272 /* CatchClause */:
                                return spanInNode(ts.lastOrUndefined(node.parent.statements));
                            case 244 /* CaseBlock */:
                                // breakpoint in last statement of the last clause
                                var caseBlock = node.parent;
                                var lastClause = ts.lastOrUndefined(caseBlock.clauses);
                                if (lastClause) {
                                    return spanInNode(ts.lastOrUndefined(lastClause.statements));
                                }
                                return undefined;
                            case 182 /* ObjectBindingPattern */:
                                // Breakpoint in last binding element or binding pattern if it contains no elements
                                var bindingPattern = node.parent;
                                return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
                            // Default to parent node
                            default:
                                if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
                                    // Breakpoint in last binding element or binding pattern if it contains no elements
                                    var objectLiteral = node.parent;
                                    return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral);
                                }
                                return spanInNode(node.parent);
                        }
                    }
                    function spanInCloseBracketToken(node) {
                        switch (node.parent.kind) {
                            case 183 /* ArrayBindingPattern */:
                                // Breakpoint in last binding element or binding pattern if it contains no elements
                                var bindingPattern = node.parent;
                                return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
                            default:
                                if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
                                    // Breakpoint in last binding element or binding pattern if it contains no elements
                                    var arrayLiteral = node.parent;
                                    return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
                                }
                                // Default to parent node
                                return spanInNode(node.parent);
                        }
                    }
                    function spanInOpenParenToken(node) {
                        if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead
                            node.parent.kind === 189 /* CallExpression */ ||
                            node.parent.kind === 190 /* NewExpression */) {
                            return spanInPreviousNode(node);
                        }
                        if (node.parent.kind === 193 /* ParenthesizedExpression */) {
                            return spanInNextNode(node);
                        }
                        // Default to parent node
                        return spanInNode(node.parent);
                    }
                    function spanInCloseParenToken(node) {
                        // Is this close paren token of parameter list, set span in previous token
                        switch (node.parent.kind) {
                            case 194 /* FunctionExpression */:
                            case 237 /* FunctionDeclaration */:
                            case 195 /* ArrowFunction */:
                            case 154 /* MethodDeclaration */:
                            case 153 /* MethodSignature */:
                            case 156 /* GetAccessor */:
                            case 157 /* SetAccessor */:
                            case 155 /* Constructor */:
                            case 222 /* WhileStatement */:
                            case 221 /* DoStatement */:
                            case 223 /* ForStatement */:
                            case 225 /* ForOfStatement */:
                            case 189 /* CallExpression */:
                            case 190 /* NewExpression */:
                            case 193 /* ParenthesizedExpression */:
                                return spanInPreviousNode(node);
                            // Default to parent node
                            default:
                                return spanInNode(node.parent);
                        }
                    }
                    function spanInColonToken(node) {
                        // Is this : specifying return annotation of the function declaration
                        if (ts.isFunctionLike(node.parent) ||
                            node.parent.kind === 273 /* PropertyAssignment */ ||
                            node.parent.kind === 149 /* Parameter */) {
                            return spanInPreviousNode(node);
                        }
                        return spanInNode(node.parent);
                    }
                    function spanInGreaterThanOrLessThanToken(node) {
                        if (node.parent.kind === 192 /* TypeAssertionExpression */) {
                            return spanInNextNode(node);
                        }
                        return spanInNode(node.parent);
                    }
                    function spanInWhileKeyword(node) {
                        if (node.parent.kind === 221 /* DoStatement */) {
                            // Set span on while expression
                            return textSpanEndingAtNextToken(node, node.parent.expression);
                        }
                        // Default to parent node
                        return spanInNode(node.parent);
                    }
                    function spanInOfKeyword(node) {
                        if (node.parent.kind === 225 /* ForOfStatement */) {
                            // Set using next token
                            return spanInNextNode(node);
                        }
                        // Default to parent node
                        return spanInNode(node.parent);
                    }
                }
            }
            BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation;
        })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {}));
    })(ts || (ts = {}));
    var ts;
    (function (ts) {
        /**
         * Transform one or more nodes using the supplied transformers.
         * @param source A single `Node` or an array of `Node` objects.
         * @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
         * @param compilerOptions Optional compiler options.
         */
        function transform(source, transformers, compilerOptions) {
            var diagnostics = [];
            compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217
            var nodes = ts.isArray(source) ? source : [source];
            var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
            result.diagnostics = ts.concatenate(result.diagnostics, diagnostics);
            return result;
        }
        ts.transform = transform;
    })(ts || (ts = {}));
    //
    // Copyright (c) Microsoft Corporation.  All rights reserved.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //   http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    //
    /* @internal */
    var debugObjectHost = (function () { return this; })();
    // We need to use 'null' to interface with the managed side.
    /* tslint:disable:no-null-keyword */
    /* tslint:disable:no-in-operator */
    /* @internal */
    var ts;
    (function (ts) {
        function logInternalError(logger, err) {
            if (logger) {
                logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
            }
        }
        var ScriptSnapshotShimAdapter = /** @class */ (function () {
            function ScriptSnapshotShimAdapter(scriptSnapshotShim) {
                this.scriptSnapshotShim = scriptSnapshotShim;
            }
            ScriptSnapshotShimAdapter.prototype.getText = function (start, end) {
                return this.scriptSnapshotShim.getText(start, end);
            };
            ScriptSnapshotShimAdapter.prototype.getLength = function () {
                return this.scriptSnapshotShim.getLength();
            };
            ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) {
                var oldSnapshotShim = oldSnapshot;
                var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
                if (encoded === null) {
                    return null; // TODO: GH#18217
                }
                var decoded = JSON.parse(encoded); // TODO: GH#18217
                return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
            };
            ScriptSnapshotShimAdapter.prototype.dispose = function () {
                // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments
                // 'in' does not have this effect
                if ("dispose" in this.scriptSnapshotShim) {
                    this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`?
                }
            };
            return ScriptSnapshotShimAdapter;
        }());
        var LanguageServiceShimHostAdapter = /** @class */ (function () {
            function LanguageServiceShimHostAdapter(shimHost) {
                var _this = this;
                this.shimHost = shimHost;
                this.loggingEnabled = false;
                this.tracingEnabled = false;
                // if shimHost is a COM object then property check will become method call with no arguments.
                // 'in' does not have this effect.
                if ("getModuleResolutionsForFile" in this.shimHost) {
                    this.resolveModuleNames = function (moduleNames, containingFile) {
                        var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217
                        return ts.map(moduleNames, function (name) {
                            var result = ts.getProperty(resolutionsInFile, name);
                            return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217
                        });
                    };
                }
                if ("directoryExists" in this.shimHost) {
                    this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
                }
                if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
                    this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
                        var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217
                        return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217
                    };
                }
            }
            LanguageServiceShimHostAdapter.prototype.log = function (s) {
                if (this.loggingEnabled) {
                    this.shimHost.log(s);
                }
            };
            LanguageServiceShimHostAdapter.prototype.trace = function (s) {
                if (this.tracingEnabled) {
                    this.shimHost.trace(s);
                }
            };
            LanguageServiceShimHostAdapter.prototype.error = function (s) {
                this.shimHost.error(s);
            };
            LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () {
                if (!this.shimHost.getProjectVersion) {
                    // shimmed host does not support getProjectVersion
                    return undefined; // TODO: GH#18217
                }
                return this.shimHost.getProjectVersion();
            };
            LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
                if (!this.shimHost.getTypeRootsVersion) {
                    return 0;
                }
                return this.shimHost.getTypeRootsVersion();
            };
            LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
                return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
            };
            LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () {
                var settingsJson = this.shimHost.getCompilationSettings();
                if (settingsJson === null || settingsJson === "") {
                    throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
                }
                var compilerOptions = JSON.parse(settingsJson);
                // permit language service to handle all files (filtering should be performed on the host side)
                compilerOptions.allowNonTsExtensions = true;
                return compilerOptions;
            };
            LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () {
                var encoded = this.shimHost.getScriptFileNames();
                return JSON.parse(encoded);
            };
            LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) {
                var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
                return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
            };
            LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) {
                if ("getScriptKind" in this.shimHost) {
                    return this.shimHost.getScriptKind(fileName); // TODO: GH#18217
                }
                else {
                    return 0 /* Unknown */;
                }
            };
            LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) {
                return this.shimHost.getScriptVersion(fileName);
            };
            LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () {
                var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
                if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
                    return null;
                }
                try {
                    return JSON.parse(diagnosticMessagesJson);
                }
                catch (e) {
                    this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
                    return null;
                }
            };
            LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () {
                var hostCancellationToken = this.shimHost.getCancellationToken();
                return new ts.ThrottledCancellationToken(hostCancellationToken);
            };
            LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () {
                return this.shimHost.getCurrentDirectory();
            };
            LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
                return JSON.parse(this.shimHost.getDirectories(path));
            };
            LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
                return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
            };
            LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) {
                var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
                return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
            };
            LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) {
                return this.shimHost.readFile(path, encoding);
            };
            LanguageServiceShimHostAdapter.prototype.fileExists = function (path) {
                return this.shimHost.fileExists(path);
            };
            return LanguageServiceShimHostAdapter;
        }());
        ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter;
        var CoreServicesShimHostAdapter = /** @class */ (function () {
            function CoreServicesShimHostAdapter(shimHost) {
                var _this = this;
                this.shimHost = shimHost;
                this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
                if ("directoryExists" in this.shimHost) {
                    this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
                }
                if ("realpath" in this.shimHost) {
                    this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
                }
            }
            CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
                var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
                return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
            };
            CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) {
                return this.shimHost.fileExists(fileName);
            };
            CoreServicesShimHostAdapter.prototype.readFile = function (fileName) {
                return this.shimHost.readFile(fileName);
            };
            CoreServicesShimHostAdapter.prototype.getDirectories = function (path) {
                return JSON.parse(this.shimHost.getDirectories(path));
            };
            return CoreServicesShimHostAdapter;
        }());
        ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter;
        function simpleForwardCall(logger, actionDescription, action, logPerformance) {
            var start;
            if (logPerformance) {
                logger.log(actionDescription);
                start = ts.timestamp();
            }
            var result = action();
            if (logPerformance) {
                var end = ts.timestamp();
                logger.log(actionDescription + " completed in " + (end - start) + " msec");
                if (ts.isString(result)) {
                    var str = result;
                    if (str.length > 128) {
                        str = str.substring(0, 128) + "...";
                    }
                    logger.log("  result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
                }
            }
            return result;
        }
        function forwardJSONCall(logger, actionDescription, action, logPerformance) {
            return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance);
        }
        function forwardCall(logger, actionDescription, returnJson, action, logPerformance) {
            try {
                var result = simpleForwardCall(logger, actionDescription, action, logPerformance);
                return returnJson ? JSON.stringify({ result: result }) : result;
            }
            catch (err) {
                if (err instanceof ts.OperationCanceledException) {
                    return JSON.stringify({ canceled: true });
                }
                logInternalError(logger, err);
                err.description = actionDescription;
                return JSON.stringify({ error: err });
            }
        }
        var ShimBase = /** @class */ (function () {
            function ShimBase(factory) {
                this.factory = factory;
                factory.registerShim(this);
            }
            ShimBase.prototype.dispose = function (_dummy) {
                this.factory.unregisterShim(this);
            };
            return ShimBase;
        }());
        function realizeDiagnostics(diagnostics, newLine) {
            return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); });
        }
        ts.realizeDiagnostics = realizeDiagnostics;
        function realizeDiagnostic(diagnostic, newLine) {
            return {
                message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
                start: diagnostic.start,
                length: diagnostic.length,
                category: ts.diagnosticCategoryName(diagnostic),
                code: diagnostic.code,
                reportsUnnecessary: diagnostic.reportsUnnecessary,
            };
        }
        var LanguageServiceShimObject = /** @class */ (function (_super) {
            __extends(LanguageServiceShimObject, _super);
            function LanguageServiceShimObject(factory, host, languageService) {
                var _this = _super.call(this, factory) || this;
                _this.host = host;
                _this.languageService = languageService;
                _this.logPerformance = false;
                _this.logger = _this.host;
                return _this;
            }
            LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
                return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
            };
            /// DISPOSE
            /**
             * Ensure (almost) deterministic release of internal Javascript resources when
             * some external native objects holds onto us (e.g. Com/Interop).
             */
            LanguageServiceShimObject.prototype.dispose = function (dummy) {
                this.logger.log("dispose()");
                this.languageService.dispose();
                this.languageService = null;
                // force a GC
                if (debugObjectHost && debugObjectHost.CollectGarbage) {
                    debugObjectHost.CollectGarbage();
                    this.logger.log("CollectGarbage()");
                }
                this.logger = null;
                _super.prototype.dispose.call(this, dummy);
            };
            /// REFRESH
            /**
             * Update the list of scripts known to the compiler
             */
            LanguageServiceShimObject.prototype.refresh = function (throwOnError) {
                this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; });
            };
            LanguageServiceShimObject.prototype.cleanupSemanticCache = function () {
                var _this = this;
                this.forwardJSONCall("cleanupSemanticCache()", function () {
                    _this.languageService.cleanupSemanticCache();
                    return null;
                });
            };
            LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
                var newLine = ts.getNewLineOrDefaultFromHost(this.host);
                return realizeDiagnostics(diagnostics, newLine);
            };
            LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
                var _this = this;
                return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); });
            };
            LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) {
                var _this = this;
                return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); });
            };
            LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) {
                var _this = this;
                return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", 
                // directly serialize the spans out to a string.  This is much faster to decode
                // on the managed side versus a full JSON array.
                function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); });
            };
            LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) {
                var _this = this;
                return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", 
                // directly serialize the spans out to a string.  This is much faster to decode
                // on the managed side versus a full JSON array.
                function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); });
            };
            LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) {
                var _this = this;
                return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () {
                    var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName);
                    return _this.realizeDiagnostics(diagnostics);
                });
            };
            LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) {
                var _this = this;
                return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () {
                    var diagnostics = _this.languageService.getSemanticDiagnostics(fileName);
                    return _this.realizeDiagnostics(diagnostics);
                });
            };
            LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
                var _this = this;
                return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
            };
            LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
                var _this = this;
                return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
                    var diagnostics = _this.languageService.getCompilerOptionsDiagnostics();
                    return _this.realizeDiagnostics(diagnostics);
                });
            };
            /// QUICKINFO
            /**
             * Computes a string representation of the type at the requested position
             * in the active file.
             */
            LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); });
            };
            /// NAMEORDOTTEDNAMESPAN
            /**
             * Computes span information of the name or dotted name at the requested position
             * in the active file.
             */
            LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) {
                var _this = this;
                return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); });
            };
            /**
             * STATEMENTSPAN
             * Computes span information of statement at the requested position in the active file.
             */
            LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); });
            };
            /// SIGNATUREHELP
            LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) {
                var _this = this;
                return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); });
            };
            /// GOTO DEFINITION
            /**
             * Computes the definition location and file for the symbol
             * at the requested position.
             */
            LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); });
            };
            /**
             * Computes the definition location and file for the symbol
             * at the requested position.
             */
            LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); });
            };
            /// GOTO Type
            /**
             * Computes the definition location of the type of the symbol
             * at the requested position.
             */
            LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); });
            };
            /// GOTO Implementation
            /**
             * Computes the implementation location of the symbol
             * at the requested position.
             */
            LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); });
            };
            LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); });
            };
            LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) {
                var _this = this;
                return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); });
            };
            /// GET BRACE MATCHING
            LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); });
            };
            LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) {
                var _this = this;
                return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); });
            };
            LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) {
                var _this = this;
                return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); });
            };
            /// GET SMART INDENT
            LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) {
                var _this = this;
                return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () {
                    var localOptions = JSON.parse(options);
                    return _this.languageService.getIndentationAtPosition(fileName, position, localOptions);
                });
            };
            /// GET REFERENCES
            LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); });
            };
            LanguageServiceShimObject.prototype.findReferences = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); });
            };
            LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); });
            };
            LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) {
                var _this = this;
                return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () {
                    var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
                    // workaround for VS document highlighting issue - keep only items from the initial file
                    var normalizedName = ts.normalizeSlashes(fileName).toLowerCase();
                    return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; });
                });
            };
            /// COMPLETION LISTS
            /**
             * Get a string based representation of the completions
             * to provide at the given source position and providing a member completion
             * list if requested.
             */
            LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) {
                var _this = this;
                return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); });
            };
            /** Get a string based representation of a completion list entry details */
            LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) {
                var _this = this;
                return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () {
                    var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions);
                    return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences);
                });
            };
            LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) {
                var _this = this;
                return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () {
                    var localOptions = JSON.parse(options);
                    return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
                });
            };
            LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) {
                var _this = this;
                return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () {
                    var localOptions = JSON.parse(options);
                    return _this.languageService.getFormattingEditsForDocument(fileName, localOptions);
                });
            };
            LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) {
                var _this = this;
                return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () {
                    var localOptions = JSON.parse(options);
                    return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
                });
            };
            LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) {
                var _this = this;
                return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); });
            };
            /// NAVIGATE TO
            /** Return a list of symbols that are interesting to navigate to */
            LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) {
                var _this = this;
                return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); });
            };
            LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) {
                var _this = this;
                return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); });
            };
            LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) {
                var _this = this;
                return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); });
            };
            LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) {
                var _this = this;
                return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); });
            };
            LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) {
                var _this = this;
                return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); });
            };
            /// Emit
            LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) {
                var _this = this;
                return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); });
            };
            LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) {
                var _this = this;
                return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", 
                /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance);
            };
            return LanguageServiceShimObject;
        }(ShimBase));
        function convertClassifications(classifications) {
            return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
        }
        var ClassifierShimObject = /** @class */ (function (_super) {
            __extends(ClassifierShimObject, _super);
            function ClassifierShimObject(factory, logger) {
                var _this = _super.call(this, factory) || this;
                _this.logger = logger;
                _this.logPerformance = false;
                _this.classifier = ts.createClassifier();
                return _this;
            }
            ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) {
                var _this = this;
                if (syntacticClassifierAbsent === void 0) {
                    syntacticClassifierAbsent = false;
                }
                return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance);
            };
            /// COLORIZATION
            ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) {
                if (classifyKeywordsInGenerics === void 0) {
                    classifyKeywordsInGenerics = false;
                }
                var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
                var result = "";
                for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) {
                    var item = _a[_i];
                    result += item.length + "\n";
                    result += item.classification + "\n";
                }
                result += classification.finalLexState;
                return result;
            };
            return ClassifierShimObject;
        }(ShimBase));
        var CoreServicesShimObject = /** @class */ (function (_super) {
            __extends(CoreServicesShimObject, _super);
            function CoreServicesShimObject(factory, logger, host) {
                var _this = _super.call(this, factory) || this;
                _this.logger = logger;
                _this.host = host;
                _this.logPerformance = false;
                return _this;
            }
            CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
                return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
            };
            CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) {
                var _this = this;
                return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () {
                    var compilerOptions = JSON.parse(compilerOptionsJson);
                    var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
                    var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined;
                    if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) {
                        resolvedFileName = undefined;
                    }
                    return {
                        resolvedFileName: resolvedFileName,
                        failedLookupLocations: result.failedLookupLocations
                    };
                });
            };
            CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) {
                var _this = this;
                return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () {
                    var compilerOptions = JSON.parse(compilerOptionsJson);
                    var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
                    return {
                        resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
                        primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
                        failedLookupLocations: result.failedLookupLocations
                    };
                });
            };
            CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) {
                var _this = this;
                return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () {
                    // for now treat files as JavaScript
                    var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
                    return {
                        referencedFiles: _this.convertFileReferences(result.referencedFiles),
                        importedFiles: _this.convertFileReferences(result.importedFiles),
                        ambientExternalModules: result.ambientExternalModules,
                        isLibFile: result.isLibFile,
                        typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives),
                        libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives)
                    };
                });
            };
            CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) {
                var _this = this;
                return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () {
                    var compilerOptions = JSON.parse(compilerOptionsJson);
                    return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host);
                });
            };
            CoreServicesShimObject.prototype.convertFileReferences = function (refs) {
                if (!refs) {
                    return undefined;
                }
                var result = [];
                for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
                    var ref = refs_1[_i];
                    result.push({
                        path: ts.normalizeSlashes(ref.fileName),
                        position: ref.pos,
                        length: ref.end - ref.pos
                    });
                }
                return result;
            };
            CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) {
                var _this = this;
                return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () {
                    var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot));
                    var normalizedFileName = ts.normalizeSlashes(fileName);
                    var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName);
                    return {
                        options: configFile.options,
                        typeAcquisition: configFile.typeAcquisition,
                        files: configFile.fileNames,
                        raw: configFile.raw,
                        errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n")
                    };
                });
            };
            CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () {
                return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); });
            };
            CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) {
                var _this = this;
                var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
                return this.forwardJSONCall("discoverTypings()", function () {
                    var info = JSON.parse(discoverTypingsJson);
                    if (_this.safeList === undefined) {
                        _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName));
                    }
                    return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry);
                });
            };
            return CoreServicesShimObject;
        }(ShimBase));
        var TypeScriptServicesFactory = /** @class */ (function () {
            function TypeScriptServicesFactory() {
                this._shims = [];
            }
            /*
             * Returns script API version.
             */
            TypeScriptServicesFactory.prototype.getServicesVersion = function () {
                return ts.servicesVersion;
            };
            TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) {
                try {
                    if (this.documentRegistry === undefined) {
                        this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
                    }
                    var hostAdapter = new LanguageServiceShimHostAdapter(host);
                    var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false);
                    return new LanguageServiceShimObject(this, host, languageService);
                }
                catch (err) {
                    logInternalError(host, err);
                    throw err;
                }
            };
            TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) {
                try {
                    return new ClassifierShimObject(this, logger);
                }
                catch (err) {
                    logInternalError(logger, err);
                    throw err;
                }
            };
            TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) {
                try {
                    var adapter = new CoreServicesShimHostAdapter(host);
                    return new CoreServicesShimObject(this, host, adapter);
                }
                catch (err) {
                    logInternalError(host, err);
                    throw err;
                }
            };
            TypeScriptServicesFactory.prototype.close = function () {
                // Forget all the registered shims
                ts.clear(this._shims);
                this.documentRegistry = undefined;
            };
            TypeScriptServicesFactory.prototype.registerShim = function (shim) {
                this._shims.push(shim);
            };
            TypeScriptServicesFactory.prototype.unregisterShim = function (shim) {
                for (var i = 0; i < this._shims.length; i++) {
                    if (this._shims[i] === shim) {
                        delete this._shims[i];
                        return;
                    }
                }
                throw new Error("Invalid operation");
            };
            return TypeScriptServicesFactory;
        }());
        ts.TypeScriptServicesFactory = TypeScriptServicesFactory;
        if (typeof module !== "undefined" && module.exports) {
            module.exports = ts;
        }
    })(ts || (ts = {}));
    /* tslint:enable:no-in-operator */
    /* tslint:enable:no-null */
    /// TODO: this is used by VS, clean this up on both sides of the interface
    /* @internal */
    var TypeScript;
    (function (TypeScript) {
        var Services;
        (function (Services) {
            Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
        })(Services = TypeScript.Services || (TypeScript.Services = {}));
    })(TypeScript || (TypeScript = {}));
    // 'toolsVersion' gets consumed by the managed side, so it's not unused.
    // TODO: it should be moved into a namespace though.
    /* @internal */
    var toolsVersion = ts.versionMajorMinor;
}
,
/* uuid/lib/bytesToUuid */ function _(require, module, exports) {
    /**
     * Convert array of 16 byte values to UUID string format of the form:
     * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
     */
    var byteToHex = [];
    for (var i = 0; i < 256; ++i) {
        byteToHex[i] = (i + 0x100).toString(16).substr(1);
    }
    function bytesToUuid(buf, offset) {
        var i = offset || 0;
        var bth = byteToHex;
        // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
        return ([bth[buf[i++]], bth[buf[i++]],
            bth[buf[i++]], bth[buf[i++]], '-',
            bth[buf[i++]], bth[buf[i++]], '-',
            bth[buf[i++]], bth[buf[i++]], '-',
            bth[buf[i++]], bth[buf[i++]], '-',
            bth[buf[i++]], bth[buf[i++]],
            bth[buf[i++]], bth[buf[i++]],
            bth[buf[i++]], bth[buf[i++]]]).join('');
    }
    module.exports = bytesToUuid;
}
,
/* uuid/lib/rng */ function _(require, module, exports) {
    // Unique ID creation requires a high quality random # generator.  In node.js
    // this is pretty straight-forward - we use the crypto API.
    var crypto = require('crypto');
    module.exports = function nodeRNG() {
        return crypto.randomBytes(16);
    };
}
,
/* uuid/v4 */ function _(require, module, exports) {
    var rng = require(369) /* ./lib/rng */;
    var bytesToUuid = require(368) /* ./lib/bytesToUuid */;
    function v4(options, buf, offset) {
        var i = buf && offset || 0;
        if (typeof (options) == 'string') {
            buf = options === 'binary' ? new Array(16) : null;
            options = null;
        }
        options = options || {};
        var rnds = options.random || (options.rng || rng)();
        // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
        rnds[6] = (rnds[6] & 0x0f) | 0x40;
        rnds[8] = (rnds[8] & 0x3f) | 0x80;
        // Copy bytes to buffer, if provided
        if (buf) {
            for (var ii = 0; ii < 16; ++ii) {
                buf[i + ii] = rnds[ii];
            }
        }
        return buf || bytesToUuid(rnds);
    }
    module.exports = v4;
}
,
/* verror/lib/verror */ function _(require, module, exports) {
    /*
     * verror.js: richer JavaScript errors
     */
    var mod_assertplus = require(53) /* assert-plus */;
    var mod_util = require('util');
    var mod_extsprintf = require(107) /* extsprintf */;
    var mod_isError = require(88) /* core-util-is */.isError;
    var sprintf = mod_extsprintf.sprintf;
    /*
     * Public interface
     */
    /* So you can 'var VError = require('verror')' */
    module.exports = VError;
    /* For compatibility */
    VError.VError = VError;
    /* Other exported classes */
    VError.SError = SError;
    VError.WError = WError;
    VError.MultiError = MultiError;
    /*
     * Common function used to parse constructor arguments for VError, WError, and
     * SError.  Named arguments to this function:
     *
     *     strict		force strict interpretation of sprintf arguments, even
     *     			if the options in "argv" don't say so
     *
     *     argv		error's constructor arguments, which are to be
     *     			interpreted as described in README.md.  For quick
     *     			reference, "argv" has one of the following forms:
     *
     *          [ sprintf_args... ]           (argv[0] is a string)
     *          [ cause, sprintf_args... ]    (argv[0] is an Error)
     *          [ options, sprintf_args... ]  (argv[0] is an object)
     *
     * This function normalizes these forms, producing an object with the following
     * properties:
     *
     *    options           equivalent to "options" in third form.  This will never
     *    			be a direct reference to what the caller passed in
     *    			(i.e., it may be a shallow copy), so it can be freely
     *    			modified.
     *
     *    shortmessage      result of sprintf(sprintf_args), taking options.strict
     *    			into account as described in README.md.
     */
    function parseConstructorArguments(args) {
        var argv, options, sprintf_args, shortmessage, k;
        mod_assertplus.object(args, 'args');
        mod_assertplus.bool(args.strict, 'args.strict');
        mod_assertplus.array(args.argv, 'args.argv');
        argv = args.argv;
        /*
         * First, figure out which form of invocation we've been given.
         */
        if (argv.length === 0) {
            options = {};
            sprintf_args = [];
        }
        else if (mod_isError(argv[0])) {
            options = { 'cause': argv[0] };
            sprintf_args = argv.slice(1);
        }
        else if (typeof (argv[0]) === 'object') {
            options = {};
            for (k in argv[0]) {
                options[k] = argv[0][k];
            }
            sprintf_args = argv.slice(1);
        }
        else {
            mod_assertplus.string(argv[0], 'first argument to VError, SError, or WError ' +
                'constructor must be a string, object, or Error');
            options = {};
            sprintf_args = argv;
        }
        /*
         * Now construct the error's message.
         *
         * extsprintf (which we invoke here with our caller's arguments in order
         * to construct this Error's message) is strict in its interpretation of
         * values to be processed by the "%s" specifier.  The value passed to
         * extsprintf must actually be a string or something convertible to a
         * String using .toString().  Passing other values (notably "null" and
         * "undefined") is considered a programmer error.  The assumption is
         * that if you actually want to print the string "null" or "undefined",
         * then that's easy to do that when you're calling extsprintf; on the
         * other hand, if you did NOT want that (i.e., there's actually a bug
         * where the program assumes some variable is non-null and tries to
         * print it, which might happen when constructing a packet or file in
         * some specific format), then it's better to stop immediately than
         * produce bogus output.
         *
         * However, sometimes the bug is only in the code calling VError, and a
         * programmer might prefer to have the error message contain "null" or
         * "undefined" rather than have the bug in the error path crash the
         * program (making the first bug harder to identify).  For that reason,
         * by default VError converts "null" or "undefined" arguments to their
         * string representations and passes those to extsprintf.  Programmers
         * desiring the strict behavior can use the SError class or pass the
         * "strict" option to the VError constructor.
         */
        mod_assertplus.object(options);
        if (!options.strict && !args.strict) {
            sprintf_args = sprintf_args.map(function (a) {
                return (a === null ? 'null' :
                    a === undefined ? 'undefined' : a);
            });
        }
        if (sprintf_args.length === 0) {
            shortmessage = '';
        }
        else {
            shortmessage = sprintf.apply(null, sprintf_args);
        }
        return ({
            'options': options,
            'shortmessage': shortmessage
        });
    }
    /*
     * See README.md for reference documentation.
     */
    function VError() {
        var args, obj, parsed, cause, ctor, message, k;
        args = Array.prototype.slice.call(arguments, 0);
        /*
         * This is a regrettable pattern, but JavaScript's built-in Error class
         * is defined to work this way, so we allow the constructor to be called
         * without "new".
         */
        if (!(this instanceof VError)) {
            obj = Object.create(VError.prototype);
            VError.apply(obj, arguments);
            return (obj);
        }
        /*
         * For convenience and backwards compatibility, we support several
         * different calling forms.  Normalize them here.
         */
        parsed = parseConstructorArguments({
            'argv': args,
            'strict': false
        });
        /*
         * If we've been given a name, apply it now.
         */
        if (parsed.options.name) {
            mod_assertplus.string(parsed.options.name, 'error\'s "name" must be a string');
            this.name = parsed.options.name;
        }
        /*
         * For debugging, we keep track of the original short message (attached
         * this Error particularly) separately from the complete message (which
         * includes the messages of our cause chain).
         */
        this.jse_shortmsg = parsed.shortmessage;
        message = parsed.shortmessage;
        /*
         * If we've been given a cause, record a reference to it and update our
         * message appropriately.
         */
        cause = parsed.options.cause;
        if (cause) {
            mod_assertplus.ok(mod_isError(cause), 'cause is not an Error');
            this.jse_cause = cause;
            if (!parsed.options.skipCauseMessage) {
                message += ': ' + cause.message;
            }
        }
        /*
         * If we've been given an object with properties, shallow-copy that
         * here.  We don't want to use a deep copy in case there are non-plain
         * objects here, but we don't want to use the original object in case
         * the caller modifies it later.
         */
        this.jse_info = {};
        if (parsed.options.info) {
            for (k in parsed.options.info) {
                this.jse_info[k] = parsed.options.info[k];
            }
        }
        this.message = message;
        Error.call(this, message);
        if (Error.captureStackTrace) {
            ctor = parsed.options.constructorOpt || this.constructor;
            Error.captureStackTrace(this, ctor);
        }
        return (this);
    }
    mod_util.inherits(VError, Error);
    VError.prototype.name = 'VError';
    VError.prototype.toString = function ve_toString() {
        var str = (this.hasOwnProperty('name') && this.name ||
            this.constructor.name || this.constructor.prototype.name);
        if (this.message)
            str += ': ' + this.message;
        return (str);
    };
    /*
     * This method is provided for compatibility.  New callers should use
     * VError.cause() instead.  That method also uses the saner `null` return value
     * when there is no cause.
     */
    VError.prototype.cause = function ve_cause() {
        var cause = VError.cause(this);
        return (cause === null ? undefined : cause);
    };
    /*
     * Static methods
     *
     * These class-level methods are provided so that callers can use them on
     * instances of Errors that are not VErrors.  New interfaces should be provided
     * only using static methods to eliminate the class of programming mistake where
     * people fail to check whether the Error object has the corresponding methods.
     */
    VError.cause = function (err) {
        mod_assertplus.ok(mod_isError(err), 'err must be an Error');
        return (mod_isError(err.jse_cause) ? err.jse_cause : null);
    };
    VError.info = function (err) {
        var rv, cause, k;
        mod_assertplus.ok(mod_isError(err), 'err must be an Error');
        cause = VError.cause(err);
        if (cause !== null) {
            rv = VError.info(cause);
        }
        else {
            rv = {};
        }
        if (typeof (err.jse_info) == 'object' && err.jse_info !== null) {
            for (k in err.jse_info) {
                rv[k] = err.jse_info[k];
            }
        }
        return (rv);
    };
    VError.findCauseByName = function (err, name) {
        var cause;
        mod_assertplus.ok(mod_isError(err), 'err must be an Error');
        mod_assertplus.string(name, 'name');
        mod_assertplus.ok(name.length > 0, 'name cannot be empty');
        for (cause = err; cause !== null; cause = VError.cause(cause)) {
            mod_assertplus.ok(mod_isError(cause));
            if (cause.name == name) {
                return (cause);
            }
        }
        return (null);
    };
    VError.hasCauseWithName = function (err, name) {
        return (VError.findCauseByName(err, name) !== null);
    };
    VError.fullStack = function (err) {
        mod_assertplus.ok(mod_isError(err), 'err must be an Error');
        var cause = VError.cause(err);
        if (cause) {
            return (err.stack + '\ncaused by: ' + VError.fullStack(cause));
        }
        return (err.stack);
    };
    VError.errorFromList = function (errors) {
        mod_assertplus.arrayOfObject(errors, 'errors');
        if (errors.length === 0) {
            return (null);
        }
        errors.forEach(function (e) {
            mod_assertplus.ok(mod_isError(e));
        });
        if (errors.length == 1) {
            return (errors[0]);
        }
        return (new MultiError(errors));
    };
    VError.errorForEach = function (err, func) {
        mod_assertplus.ok(mod_isError(err), 'err must be an Error');
        mod_assertplus.func(func, 'func');
        if (err instanceof MultiError) {
            err.errors().forEach(function iterError(e) { func(e); });
        }
        else {
            func(err);
        }
    };
    /*
     * SError is like VError, but stricter about types.  You cannot pass "null" or
     * "undefined" as string arguments to the formatter.
     */
    function SError() {
        var args, obj, parsed, options;
        args = Array.prototype.slice.call(arguments, 0);
        if (!(this instanceof SError)) {
            obj = Object.create(SError.prototype);
            SError.apply(obj, arguments);
            return (obj);
        }
        parsed = parseConstructorArguments({
            'argv': args,
            'strict': true
        });
        options = parsed.options;
        VError.call(this, options, '%s', parsed.shortmessage);
        return (this);
    }
    /*
     * We don't bother setting SError.prototype.name because once constructed,
     * SErrors are just like VErrors.
     */
    mod_util.inherits(SError, VError);
    /*
     * Represents a collection of errors for the purpose of consumers that generally
     * only deal with one error.  Callers can extract the individual errors
     * contained in this object, but may also just treat it as a normal single
     * error, in which case a summary message will be printed.
     */
    function MultiError(errors) {
        mod_assertplus.array(errors, 'list of errors');
        mod_assertplus.ok(errors.length > 0, 'must be at least one error');
        this.ase_errors = errors;
        VError.call(this, {
            'cause': errors[0]
        }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');
    }
    mod_util.inherits(MultiError, VError);
    MultiError.prototype.name = 'MultiError';
    MultiError.prototype.errors = function me_errors() {
        return (this.ase_errors.slice(0));
    };
    /*
     * See README.md for reference details.
     */
    function WError() {
        var args, obj, parsed, options;
        args = Array.prototype.slice.call(arguments, 0);
        if (!(this instanceof WError)) {
            obj = Object.create(WError.prototype);
            WError.apply(obj, args);
            return (obj);
        }
        parsed = parseConstructorArguments({
            'argv': args,
            'strict': false
        });
        options = parsed.options;
        options['skipCauseMessage'] = true;
        VError.call(this, options, '%s', parsed.shortmessage);
        return (this);
    }
    mod_util.inherits(WError, VError);
    WError.prototype.name = 'WError';
    WError.prototype.toString = function we_toString() {
        var str = (this.hasOwnProperty('name') && this.name ||
            this.constructor.name || this.constructor.prototype.name);
        if (this.message)
            str += ': ' + this.message;
        if (this.jse_cause && this.jse_cause.message)
            str += '; caused by ' + this.jse_cause.toString();
        return (str);
    };
    /*
     * For purely historical reasons, WError's cause() function allows you to set
     * the cause.
     */
    WError.prototype.cause = function we_cause(c) {
        if (mod_isError(c))
            this.jse_cause = c;
        return (this.jse_cause);
    };
}
,
/* which-module/index */ function _(require, module, exports) {
    module.exports = function whichModule(exported) {
        for (var i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
            mod = require.cache[files[i]];
            if (mod.exports === exported)
                return mod;
        }
        return null;
    };
}
,
/* which/which */ function _(require, module, exports) {
    module.exports = which;
    which.sync = whichSync;
    var isWindows = process.platform === 'win32' ||
        process.env.OSTYPE === 'cygwin' ||
        process.env.OSTYPE === 'msys';
    var path = require('path');
    var COLON = isWindows ? ';' : ':';
    var isexe = require(151) /* isexe */;
    function getNotFoundError(cmd) {
        var er = new Error('not found: ' + cmd);
        er.code = 'ENOENT';
        return er;
    }
    function getPathInfo(cmd, opt) {
        var colon = opt.colon || COLON;
        var pathEnv = opt.path || process.env.PATH || '';
        var pathExt = [''];
        pathEnv = pathEnv.split(colon);
        var pathExtExe = '';
        if (isWindows) {
            pathEnv.unshift(process.cwd());
            pathExtExe = (opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM');
            pathExt = pathExtExe.split(colon);
            // Always test the cmd itself first.  isexe will check to make sure
            // it's found in the pathExt set.
            if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
                pathExt.unshift('');
        }
        // If it has a slash, then we don't bother searching the pathenv.
        // just check the file itself, and that's it.
        if (cmd.match(/\//) || isWindows && cmd.match(/\\/))
            pathEnv = [''];
        return {
            env: pathEnv,
            ext: pathExt,
            extExe: pathExtExe
        };
    }
    function which(cmd, opt, cb) {
        if (typeof opt === 'function') {
            cb = opt;
            opt = {};
        }
        var info = getPathInfo(cmd, opt);
        var pathEnv = info.env;
        var pathExt = info.ext;
        var pathExtExe = info.extExe;
        var found = [];
        (function F(i, l) {
            if (i === l) {
                if (opt.all && found.length)
                    return cb(null, found);
                else
                    return cb(getNotFoundError(cmd));
            }
            var pathPart = pathEnv[i];
            if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"')
                pathPart = pathPart.slice(1, -1);
            var p = path.join(pathPart, cmd);
            if (!pathPart && (/^\.[\\\/]/).test(cmd)) {
                p = cmd.slice(0, 2) + p;
            }
            ;
            (function E(ii, ll) {
                if (ii === ll)
                    return F(i + 1, l);
                var ext = pathExt[ii];
                isexe(p + ext, { pathExt: pathExtExe }, function (er, is) {
                    if (!er && is) {
                        if (opt.all)
                            found.push(p + ext);
                        else
                            return cb(null, p + ext);
                    }
                    return E(ii + 1, ll);
                });
            })(0, pathExt.length);
        })(0, pathEnv.length);
    }
    function whichSync(cmd, opt) {
        opt = opt || {};
        var info = getPathInfo(cmd, opt);
        var pathEnv = info.env;
        var pathExt = info.ext;
        var pathExtExe = info.extExe;
        var found = [];
        for (var i = 0, l = pathEnv.length; i < l; i++) {
            var pathPart = pathEnv[i];
            if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"')
                pathPart = pathPart.slice(1, -1);
            var p = path.join(pathPart, cmd);
            if (!pathPart && /^\.[\\\/]/.test(cmd)) {
                p = cmd.slice(0, 2) + p;
            }
            for (var j = 0, ll = pathExt.length; j < ll; j++) {
                var cur = p + pathExt[j];
                var is;
                try {
                    is = isexe.sync(cur, { pathExt: pathExtExe });
                    if (is) {
                        if (opt.all)
                            found.push(cur);
                        else
                            return cur;
                    }
                }
                catch (ex) { }
            }
        }
        if (opt.all && found.length)
            return found;
        if (opt.nothrow)
            return null;
        throw getNotFoundError(cmd);
    }
}
,
/* wordwrap/index */ function _(require, module, exports) {
    var wordwrap = module.exports = function (start, stop, params) {
        if (typeof start === 'object') {
            params = start;
            start = params.start;
            stop = params.stop;
        }
        if (typeof stop === 'object') {
            params = stop;
            start = start || params.start;
            stop = undefined;
        }
        if (!stop) {
            stop = start;
            start = 0;
        }
        if (!params)
            params = {};
        var mode = params.mode || 'soft';
        var re = mode === 'hard' ? /\b/ : /(\S+\s+)/;
        return function (text) {
            var chunks = text.toString()
                .split(re)
                .reduce(function (acc, x) {
                if (mode === 'hard') {
                    for (var i = 0; i < x.length; i += stop - start) {
                        acc.push(x.slice(i, i + stop - start));
                    }
                }
                else
                    acc.push(x);
                return acc;
            }, []);
            return chunks.reduce(function (lines, rawChunk) {
                if (rawChunk === '')
                    return lines;
                var chunk = rawChunk.replace(/\t/g, '    ');
                var i = lines.length - 1;
                if (lines[i].length + chunk.length > stop) {
                    lines[i] = lines[i].replace(/\s+$/, '');
                    chunk.split(/\n/).forEach(function (c) {
                        lines.push(new Array(start + 1).join(' ')
                            + c.replace(/^\s+/, ''));
                    });
                }
                else if (chunk.match(/\n/)) {
                    var xs = chunk.split(/\n/);
                    lines[i] += xs.shift();
                    xs.forEach(function (c) {
                        lines.push(new Array(start + 1).join(' ')
                            + c.replace(/^\s+/, ''));
                    });
                }
                else {
                    lines[i] += chunk;
                }
                return lines;
            }, [new Array(start + 1).join(' ')]).join('\n');
        };
    };
    wordwrap.soft = wordwrap;
    wordwrap.hard = function (start, stop) {
        return wordwrap(start, stop, { mode: 'hard' });
    };
}
,
/* y18n/index */ function _(require, module, exports) {
    var fs = require('fs');
    var path = require('path');
    var util = require('util');
    function Y18N(opts) {
        // configurable options.
        opts = opts || {};
        this.directory = opts.directory || './locales';
        this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
        this.locale = opts.locale || 'en';
        this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
        // internal stuff.
        this.cache = {};
        this.writeQueue = [];
    }
    Y18N.prototype.__ = function () {
        var args = Array.prototype.slice.call(arguments);
        var str = args.shift();
        var cb = function () { }; // start with noop.
        if (typeof args[args.length - 1] === 'function')
            cb = args.pop();
        cb = cb || function () { }; // noop.
        if (!this.cache[this.locale])
            this._readLocaleFile();
        // we've observed a new string, update the language file.
        if (!this.cache[this.locale][str] && this.updateFiles) {
            this.cache[this.locale][str] = str;
            // include the current directory and locale,
            // since these values could change before the
            // write is performed.
            this._enqueueWrite([this.directory, this.locale, cb]);
        }
        else {
            cb();
        }
        return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args));
    };
    Y18N.prototype._enqueueWrite = function (work) {
        this.writeQueue.push(work);
        if (this.writeQueue.length === 1)
            this._processWriteQueue();
    };
    Y18N.prototype._processWriteQueue = function () {
        var _this = this;
        var work = this.writeQueue[0];
        // destructure the enqueued work.
        var directory = work[0];
        var locale = work[1];
        var cb = work[2];
        var languageFile = this._resolveLocaleFile(directory, locale);
        var serializedLocale = JSON.stringify(this.cache[locale], null, 2);
        fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
            _this.writeQueue.shift();
            if (_this.writeQueue.length > 0)
                _this._processWriteQueue();
            cb(err);
        });
    };
    Y18N.prototype._readLocaleFile = function () {
        var localeLookup = {};
        var languageFile = this._resolveLocaleFile(this.directory, this.locale);
        try {
            localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8'));
        }
        catch (err) {
            if (err instanceof SyntaxError) {
                err.message = 'syntax error in ' + languageFile;
            }
            if (err.code === 'ENOENT')
                localeLookup = {};
            else
                throw err;
        }
        this.cache[this.locale] = localeLookup;
    };
    Y18N.prototype._resolveLocaleFile = function (directory, locale) {
        var file = path.resolve(directory, './', locale + '.json');
        if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
            // attempt fallback to language only
            var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json');
            if (this._fileExistsSync(languageFile))
                file = languageFile;
        }
        return file;
    };
    // this only exists because fs.existsSync() "will be deprecated"
    // see https://nodejs.org/api/fs.html#fs_fs_existssync_path
    Y18N.prototype._fileExistsSync = function (file) {
        try {
            return fs.statSync(file).isFile();
        }
        catch (err) {
            return false;
        }
    };
    Y18N.prototype.__n = function () {
        var args = Array.prototype.slice.call(arguments);
        var singular = args.shift();
        var plural = args.shift();
        var quantity = args.shift();
        var cb = function () { }; // start with noop.
        if (typeof args[args.length - 1] === 'function')
            cb = args.pop();
        if (!this.cache[this.locale])
            this._readLocaleFile();
        var str = quantity === 1 ? singular : plural;
        if (this.cache[this.locale][singular]) {
            str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other'];
        }
        // we've observed a new string, update the language file.
        if (!this.cache[this.locale][singular] && this.updateFiles) {
            this.cache[this.locale][singular] = {
                one: singular,
                other: plural
            };
            // include the current directory and locale,
            // since these values could change before the
            // write is performed.
            this._enqueueWrite([this.directory, this.locale, cb]);
        }
        else {
            cb();
        }
        // if a %d placeholder is provided, add quantity
        // to the arguments expanded by util.format.
        var values = [str];
        if (~str.indexOf('%d'))
            values.push(quantity);
        return util.format.apply(util, values.concat(args));
    };
    Y18N.prototype.setLocale = function (locale) {
        this.locale = locale;
    };
    Y18N.prototype.getLocale = function () {
        return this.locale;
    };
    Y18N.prototype.updateLocale = function (obj) {
        if (!this.cache[this.locale])
            this._readLocaleFile();
        for (var key in obj) {
            this.cache[this.locale][key] = obj[key];
        }
    };
    module.exports = function (opts) {
        var y18n = new Y18N(opts);
        // bind all functions to y18n, so that
        // they can be used in isolation.
        for (var key in y18n) {
            if (typeof y18n[key] === 'function') {
                y18n[key] = y18n[key].bind(y18n);
            }
        }
        return y18n;
    };
}
,
/* yallist/yallist */ function _(require, module, exports) {
    module.exports = Yallist;
    Yallist.Node = Node;
    Yallist.create = Yallist;
    function Yallist(list) {
        var self = this;
        if (!(self instanceof Yallist)) {
            self = new Yallist();
        }
        self.tail = null;
        self.head = null;
        self.length = 0;
        if (list && typeof list.forEach === 'function') {
            list.forEach(function (item) {
                self.push(item);
            });
        }
        else if (arguments.length > 0) {
            for (var i = 0, l = arguments.length; i < l; i++) {
                self.push(arguments[i]);
            }
        }
        return self;
    }
    Yallist.prototype.removeNode = function (node) {
        if (node.list !== this) {
            throw new Error('removing node which does not belong to this list');
        }
        var next = node.next;
        var prev = node.prev;
        if (next) {
            next.prev = prev;
        }
        if (prev) {
            prev.next = next;
        }
        if (node === this.head) {
            this.head = next;
        }
        if (node === this.tail) {
            this.tail = prev;
        }
        node.list.length--;
        node.next = null;
        node.prev = null;
        node.list = null;
    };
    Yallist.prototype.unshiftNode = function (node) {
        if (node === this.head) {
            return;
        }
        if (node.list) {
            node.list.removeNode(node);
        }
        var head = this.head;
        node.list = this;
        node.next = head;
        if (head) {
            head.prev = node;
        }
        this.head = node;
        if (!this.tail) {
            this.tail = node;
        }
        this.length++;
    };
    Yallist.prototype.pushNode = function (node) {
        if (node === this.tail) {
            return;
        }
        if (node.list) {
            node.list.removeNode(node);
        }
        var tail = this.tail;
        node.list = this;
        node.prev = tail;
        if (tail) {
            tail.next = node;
        }
        this.tail = node;
        if (!this.head) {
            this.head = node;
        }
        this.length++;
    };
    Yallist.prototype.push = function () {
        for (var i = 0, l = arguments.length; i < l; i++) {
            push(this, arguments[i]);
        }
        return this.length;
    };
    Yallist.prototype.unshift = function () {
        for (var i = 0, l = arguments.length; i < l; i++) {
            unshift(this, arguments[i]);
        }
        return this.length;
    };
    Yallist.prototype.pop = function () {
        if (!this.tail) {
            return undefined;
        }
        var res = this.tail.value;
        this.tail = this.tail.prev;
        if (this.tail) {
            this.tail.next = null;
        }
        else {
            this.head = null;
        }
        this.length--;
        return res;
    };
    Yallist.prototype.shift = function () {
        if (!this.head) {
            return undefined;
        }
        var res = this.head.value;
        this.head = this.head.next;
        if (this.head) {
            this.head.prev = null;
        }
        else {
            this.tail = null;
        }
        this.length--;
        return res;
    };
    Yallist.prototype.forEach = function (fn, thisp) {
        thisp = thisp || this;
        for (var walker = this.head, i = 0; walker !== null; i++) {
            fn.call(thisp, walker.value, i, this);
            walker = walker.next;
        }
    };
    Yallist.prototype.forEachReverse = function (fn, thisp) {
        thisp = thisp || this;
        for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
            fn.call(thisp, walker.value, i, this);
            walker = walker.prev;
        }
    };
    Yallist.prototype.get = function (n) {
        for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
            // abort out of the list early if we hit a cycle
            walker = walker.next;
        }
        if (i === n && walker !== null) {
            return walker.value;
        }
    };
    Yallist.prototype.getReverse = function (n) {
        for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
            // abort out of the list early if we hit a cycle
            walker = walker.prev;
        }
        if (i === n && walker !== null) {
            return walker.value;
        }
    };
    Yallist.prototype.map = function (fn, thisp) {
        thisp = thisp || this;
        var res = new Yallist();
        for (var walker = this.head; walker !== null;) {
            res.push(fn.call(thisp, walker.value, this));
            walker = walker.next;
        }
        return res;
    };
    Yallist.prototype.mapReverse = function (fn, thisp) {
        thisp = thisp || this;
        var res = new Yallist();
        for (var walker = this.tail; walker !== null;) {
            res.push(fn.call(thisp, walker.value, this));
            walker = walker.prev;
        }
        return res;
    };
    Yallist.prototype.reduce = function (fn, initial) {
        var acc;
        var walker = this.head;
        if (arguments.length > 1) {
            acc = initial;
        }
        else if (this.head) {
            walker = this.head.next;
            acc = this.head.value;
        }
        else {
            throw new TypeError('Reduce of empty list with no initial value');
        }
        for (var i = 0; walker !== null; i++) {
            acc = fn(acc, walker.value, i);
            walker = walker.next;
        }
        return acc;
    };
    Yallist.prototype.reduceReverse = function (fn, initial) {
        var acc;
        var walker = this.tail;
        if (arguments.length > 1) {
            acc = initial;
        }
        else if (this.tail) {
            walker = this.tail.prev;
            acc = this.tail.value;
        }
        else {
            throw new TypeError('Reduce of empty list with no initial value');
        }
        for (var i = this.length - 1; walker !== null; i--) {
            acc = fn(acc, walker.value, i);
            walker = walker.prev;
        }
        return acc;
    };
    Yallist.prototype.toArray = function () {
        var arr = new Array(this.length);
        for (var i = 0, walker = this.head; walker !== null; i++) {
            arr[i] = walker.value;
            walker = walker.next;
        }
        return arr;
    };
    Yallist.prototype.toArrayReverse = function () {
        var arr = new Array(this.length);
        for (var i = 0, walker = this.tail; walker !== null; i++) {
            arr[i] = walker.value;
            walker = walker.prev;
        }
        return arr;
    };
    Yallist.prototype.slice = function (from, to) {
        to = to || this.length;
        if (to < 0) {
            to += this.length;
        }
        from = from || 0;
        if (from < 0) {
            from += this.length;
        }
        var ret = new Yallist();
        if (to < from || to < 0) {
            return ret;
        }
        if (from < 0) {
            from = 0;
        }
        if (to > this.length) {
            to = this.length;
        }
        for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
            walker = walker.next;
        }
        for (; walker !== null && i < to; i++, walker = walker.next) {
            ret.push(walker.value);
        }
        return ret;
    };
    Yallist.prototype.sliceReverse = function (from, to) {
        to = to || this.length;
        if (to < 0) {
            to += this.length;
        }
        from = from || 0;
        if (from < 0) {
            from += this.length;
        }
        var ret = new Yallist();
        if (to < from || to < 0) {
            return ret;
        }
        if (from < 0) {
            from = 0;
        }
        if (to > this.length) {
            to = this.length;
        }
        for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
            walker = walker.prev;
        }
        for (; walker !== null && i > from; i--, walker = walker.prev) {
            ret.push(walker.value);
        }
        return ret;
    };
    Yallist.prototype.reverse = function () {
        var head = this.head;
        var tail = this.tail;
        for (var walker = head; walker !== null; walker = walker.prev) {
            var p = walker.prev;
            walker.prev = walker.next;
            walker.next = p;
        }
        this.head = tail;
        this.tail = head;
        return this;
    };
    function push(self, item) {
        self.tail = new Node(item, self.tail, null, self);
        if (!self.head) {
            self.head = self.tail;
        }
        self.length++;
    }
    function unshift(self, item) {
        self.head = new Node(item, null, self.head, self);
        if (!self.tail) {
            self.tail = self.head;
        }
        self.length++;
    }
    function Node(value, prev, next, list) {
        if (!(this instanceof Node)) {
            return new Node(value, prev, next, list);
        }
        this.list = list;
        this.value = value;
        if (prev) {
            prev.next = this;
            this.prev = prev;
        }
        else {
            this.prev = null;
        }
        if (next) {
            next.prev = this;
            this.next = next;
        }
        else {
            this.next = null;
        }
    }
}
,
/* yargs-parser/index */ function _(require, module, exports) {
    var camelCase = require(69) /* camelcase */;
    var path = require('path');
    var tokenizeArgString = require(378) /* ./lib/tokenize-arg-string */;
    var util = require('util');
    function parse(args, opts) {
        if (!opts)
            opts = {};
        // allow a string argument to be passed in rather
        // than an argv array.
        args = tokenizeArgString(args);
        // aliases might have transitive relationships, normalize this.
        var aliases = combineAliases(opts.alias || {});
        var configuration = assign({
            'short-option-groups': true,
            'camel-case-expansion': true,
            'dot-notation': true,
            'parse-numbers': true,
            'boolean-negation': true,
            'negation-prefix': 'no-',
            'duplicate-arguments-array': true,
            'flatten-duplicate-arrays': true,
            'populate--': false,
            'combine-arrays': false
        }, opts.configuration);
        var defaults = opts.default || {};
        var configObjects = opts.configObjects || [];
        var envPrefix = opts.envPrefix;
        var notFlagsOption = configuration['populate--'];
        var notFlagsArgv = notFlagsOption ? '--' : '_';
        var newAliases = {};
        // allow a i18n handler to be passed in, default to a fake one (util.format).
        var __ = opts.__ || function (str) {
            return util.format.apply(util, Array.prototype.slice.call(arguments));
        };
        var error = null;
        var flags = {
            aliases: {},
            arrays: {},
            bools: {},
            strings: {},
            numbers: {},
            counts: {},
            normalize: {},
            configs: {},
            defaulted: {},
            nargs: {},
            coercions: {}
        };
        var negative = /^-[0-9]+(\.[0-9]+)?/;
        var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
        [].concat(opts.array).filter(Boolean).forEach(function (key) {
            flags.arrays[key] = true;
        });
        [].concat(opts.boolean).filter(Boolean).forEach(function (key) {
            flags.bools[key] = true;
        });
        [].concat(opts.string).filter(Boolean).forEach(function (key) {
            flags.strings[key] = true;
        });
        [].concat(opts.number).filter(Boolean).forEach(function (key) {
            flags.numbers[key] = true;
        });
        [].concat(opts.count).filter(Boolean).forEach(function (key) {
            flags.counts[key] = true;
        });
        [].concat(opts.normalize).filter(Boolean).forEach(function (key) {
            flags.normalize[key] = true;
        });
        Object.keys(opts.narg || {}).forEach(function (k) {
            flags.nargs[k] = opts.narg[k];
        });
        Object.keys(opts.coerce || {}).forEach(function (k) {
            flags.coercions[k] = opts.coerce[k];
        });
        if (Array.isArray(opts.config) || typeof opts.config === 'string') {
            ;
            [].concat(opts.config).filter(Boolean).forEach(function (key) {
                flags.configs[key] = true;
            });
        }
        else {
            Object.keys(opts.config || {}).forEach(function (k) {
                flags.configs[k] = opts.config[k];
            });
        }
        // create a lookup table that takes into account all
        // combinations of aliases: {f: ['foo'], foo: ['f']}
        extendAliases(opts.key, aliases, opts.default, flags.arrays);
        // apply default values to all aliases.
        Object.keys(defaults).forEach(function (key) {
            (flags.aliases[key] || []).forEach(function (alias) {
                defaults[alias] = defaults[key];
            });
        });
        var argv = { _: [] };
        Object.keys(flags.bools).forEach(function (key) {
            setArg(key, !(key in defaults) ? false : defaults[key]);
            setDefaulted(key);
        });
        var notFlags = [];
        if (args.indexOf('--') !== -1) {
            notFlags = args.slice(args.indexOf('--') + 1);
            args = args.slice(0, args.indexOf('--'));
        }
        for (var i = 0; i < args.length; i++) {
            var arg = args[i];
            var broken;
            var key;
            var letters;
            var m;
            var next;
            var value;
            // -- seperated by =
            if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
                // Using [\s\S] instead of . because js doesn't support the
                // 'dotall' regex modifier. See:
                // http://stackoverflow.com/a/1068308/13216
                m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
                // nargs format = '--f=monkey washing cat'
                if (checkAllAliases(m[1], flags.nargs)) {
                    args.splice(i + 1, 0, m[2]);
                    i = eatNargs(i, m[1], args);
                    // arrays format = '--f=a b c'
                }
                else if (checkAllAliases(m[1], flags.arrays) && args.length > i + 1) {
                    args.splice(i + 1, 0, m[2]);
                    i = eatArray(i, m[1], args);
                }
                else {
                    setArg(m[1], m[2]);
                }
            }
            else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
                key = arg.match(negatedBoolean)[1];
                setArg(key, false);
                // -- seperated by space.
            }
            else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-.+/))) {
                key = arg.match(/^--?(.+)/)[1];
                // nargs format = '--foo a b c'
                if (checkAllAliases(key, flags.nargs)) {
                    i = eatNargs(i, key, args);
                    // array format = '--foo a b c'
                }
                else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
                    i = eatArray(i, key, args);
                }
                else {
                    next = args[i + 1];
                    if (next !== undefined && (!next.match(/^-/) ||
                        next.match(negative)) &&
                        !checkAllAliases(key, flags.bools) &&
                        !checkAllAliases(key, flags.counts)) {
                        setArg(key, next);
                        i++;
                    }
                    else if (/^(true|false)$/.test(next)) {
                        setArg(key, next);
                        i++;
                    }
                    else {
                        setArg(key, defaultForType(guessType(key, flags)));
                    }
                }
                // dot-notation flag seperated by '='.
            }
            else if (arg.match(/^-.\..+=/)) {
                m = arg.match(/^-([^=]+)=([\s\S]*)$/);
                setArg(m[1], m[2]);
                // dot-notation flag seperated by space.
            }
            else if (arg.match(/^-.\..+/)) {
                next = args[i + 1];
                key = arg.match(/^-(.\..+)/)[1];
                if (next !== undefined && !next.match(/^-/) &&
                    !checkAllAliases(key, flags.bools) &&
                    !checkAllAliases(key, flags.counts)) {
                    setArg(key, next);
                    i++;
                }
                else {
                    setArg(key, defaultForType(guessType(key, flags)));
                }
            }
            else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
                letters = arg.slice(1, -1).split('');
                broken = false;
                for (var j = 0; j < letters.length; j++) {
                    next = arg.slice(j + 2);
                    if (letters[j + 1] && letters[j + 1] === '=') {
                        value = arg.slice(j + 3);
                        key = letters[j];
                        // nargs format = '-f=monkey washing cat'
                        if (checkAllAliases(key, flags.nargs)) {
                            args.splice(i + 1, 0, value);
                            i = eatNargs(i, key, args);
                            // array format = '-f=a b c'
                        }
                        else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
                            args.splice(i + 1, 0, value);
                            i = eatArray(i, key, args);
                        }
                        else {
                            setArg(key, value);
                        }
                        broken = true;
                        break;
                    }
                    if (next === '-') {
                        setArg(letters[j], next);
                        continue;
                    }
                    // current letter is an alphabetic character and next value is a number
                    if (/[A-Za-z]/.test(letters[j]) &&
                        /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                        setArg(letters[j], next);
                        broken = true;
                        break;
                    }
                    if (letters[j + 1] && letters[j + 1].match(/\W/)) {
                        setArg(letters[j], next);
                        broken = true;
                        break;
                    }
                    else {
                        setArg(letters[j], defaultForType(guessType(letters[j], flags)));
                    }
                }
                key = arg.slice(-1)[0];
                if (!broken && key !== '-') {
                    // nargs format = '-f a b c'
                    if (checkAllAliases(key, flags.nargs)) {
                        i = eatNargs(i, key, args);
                        // array format = '-f a b c'
                    }
                    else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
                        i = eatArray(i, key, args);
                    }
                    else {
                        next = args[i + 1];
                        if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
                            next.match(negative)) &&
                            !checkAllAliases(key, flags.bools) &&
                            !checkAllAliases(key, flags.counts)) {
                            setArg(key, next);
                            i++;
                        }
                        else if (/^(true|false)$/.test(next)) {
                            setArg(key, next);
                            i++;
                        }
                        else {
                            setArg(key, defaultForType(guessType(key, flags)));
                        }
                    }
                }
            }
            else {
                argv._.push(maybeCoerceNumber('_', arg));
            }
        }
        // order of precedence:
        // 1. command line arg
        // 2. value from env var
        // 3. value from config file
        // 4. value from config objects
        // 5. configured default value
        applyEnvVars(argv, true); // special case: check env vars that point to config file
        applyEnvVars(argv, false);
        setConfig(argv);
        setConfigObjects();
        applyDefaultsAndAliases(argv, flags.aliases, defaults);
        applyCoercions(argv);
        // for any counts either not in args or without an explicit default, set to 0
        Object.keys(flags.counts).forEach(function (key) {
            if (!hasKey(argv, key.split('.')))
                setArg(key, 0);
        });
        // '--' defaults to undefined.
        if (notFlagsOption && notFlags.length)
            argv[notFlagsArgv] = [];
        notFlags.forEach(function (key) {
            argv[notFlagsArgv].push(key);
        });
        // how many arguments should we consume, based
        // on the nargs option?
        function eatNargs(i, key, args) {
            var ii;
            const toEat = checkAllAliases(key, flags.nargs);
            // nargs will not consume flag arguments, e.g., -abc, --foo,
            // and terminates when one is observed.
            var available = 0;
            for (ii = i + 1; ii < args.length; ii++) {
                if (!args[ii].match(/^-[^0-9]/))
                    available++;
                else
                    break;
            }
            if (available < toEat)
                error = Error(__('Not enough arguments following: %s', key));
            const consumed = Math.min(available, toEat);
            for (ii = i + 1; ii < (consumed + i + 1); ii++) {
                setArg(key, args[ii]);
            }
            return (i + consumed);
        }
        // if an option is an array, eat all non-hyphenated arguments
        // following it... YUM!
        // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
        function eatArray(i, key, args) {
            var start = i + 1;
            var argsToSet = [];
            var multipleArrayFlag = i > 0;
            for (var ii = i + 1; ii < args.length; ii++) {
                if (/^-/.test(args[ii]) && !negative.test(args[ii])) {
                    if (ii === start) {
                        setArg(key, defaultForType('array'));
                    }
                    multipleArrayFlag = true;
                    break;
                }
                i = ii;
                argsToSet.push(args[ii]);
            }
            if (multipleArrayFlag) {
                setArg(key, argsToSet.map(function (arg) {
                    return processValue(key, arg);
                }));
            }
            else {
                argsToSet.forEach(function (arg) {
                    setArg(key, arg);
                });
            }
            return i;
        }
        function setArg(key, val) {
            unsetDefaulted(key);
            if (/-/.test(key) && configuration['camel-case-expansion']) {
                addNewAlias(key, camelCase(key));
            }
            var value = processValue(key, val);
            var splitKey = key.split('.');
            setKey(argv, splitKey, value);
            // handle populating aliases of the full key
            if (flags.aliases[key]) {
                flags.aliases[key].forEach(function (x) {
                    x = x.split('.');
                    setKey(argv, x, value);
                });
            }
            // handle populating aliases of the first element of the dot-notation key
            if (splitKey.length > 1 && configuration['dot-notation']) {
                ;
                (flags.aliases[splitKey[0]] || []).forEach(function (x) {
                    x = x.split('.');
                    // expand alias with nested objects in key
                    var a = [].concat(splitKey);
                    a.shift(); // nuke the old key.
                    x = x.concat(a);
                    setKey(argv, x, value);
                });
            }
            // Set normalize getter and setter when key is in 'normalize' but isn't an array
            if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
                var keys = [key].concat(flags.aliases[key] || []);
                keys.forEach(function (key) {
                    argv.__defineSetter__(key, function (v) {
                        val = path.normalize(v);
                    });
                    argv.__defineGetter__(key, function () {
                        return typeof val === 'string' ? path.normalize(val) : val;
                    });
                });
            }
        }
        function addNewAlias(key, alias) {
            if (!(flags.aliases[key] && flags.aliases[key].length)) {
                flags.aliases[key] = [alias];
                newAliases[alias] = true;
            }
            if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
                addNewAlias(alias, key);
            }
        }
        function processValue(key, val) {
            // handle parsing boolean arguments --foo=true --bar false.
            if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
                if (typeof val === 'string')
                    val = val === 'true';
            }
            var value = maybeCoerceNumber(key, val);
            // increment a count given as arg (either no value or value parsed as boolean)
            if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
                value = increment;
            }
            // Set normalized value when key is in 'normalize' and in 'arrays'
            if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
                if (Array.isArray(val))
                    value = val.map(path.normalize);
                else
                    value = path.normalize(val);
            }
            return value;
        }
        function maybeCoerceNumber(key, value) {
            if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) {
                const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(value)));
                if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers)))
                    value = Number(value);
            }
            return value;
        }
        // set args from config.json file, this should be
        // applied last so that defaults can be applied.
        function setConfig(argv) {
            var configLookup = {};
            // expand defaults/aliases, in-case any happen to reference
            // the config.json file.
            applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
            Object.keys(flags.configs).forEach(function (configKey) {
                var configPath = argv[configKey] || configLookup[configKey];
                if (configPath) {
                    try {
                        var config = null;
                        var resolvedConfigPath = path.resolve(process.cwd(), configPath);
                        if (typeof flags.configs[configKey] === 'function') {
                            try {
                                config = flags.configs[configKey](resolvedConfigPath);
                            }
                            catch (e) {
                                config = e;
                            }
                            if (config instanceof Error) {
                                error = config;
                                return;
                            }
                        }
                        else {
                            config = require(resolvedConfigPath);
                        }
                        setConfigObject(config);
                    }
                    catch (ex) {
                        if (argv[configKey])
                            error = Error(__('Invalid JSON config file: %s', configPath));
                    }
                }
            });
        }
        // set args from config object.
        // it recursively checks nested objects.
        function setConfigObject(config, prev) {
            Object.keys(config).forEach(function (key) {
                var value = config[key];
                var fullKey = prev ? prev + '.' + key : key;
                // if the value is an inner object and we have dot-notation
                // enabled, treat inner objects in config the same as
                // heavily nested dot notations (foo.bar.apple).
                if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
                    // if the value is an object but not an array, check nested object
                    setConfigObject(value, fullKey);
                }
                else {
                    // setting arguments via CLI takes precedence over
                    // values within the config file.
                    if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
                        setArg(fullKey, value);
                    }
                }
            });
        }
        // set all config objects passed in opts
        function setConfigObjects() {
            if (typeof configObjects === 'undefined')
                return;
            configObjects.forEach(function (configObject) {
                setConfigObject(configObject);
            });
        }
        function applyEnvVars(argv, configOnly) {
            if (typeof envPrefix === 'undefined')
                return;
            var prefix = typeof envPrefix === 'string' ? envPrefix : '';
            Object.keys(process.env).forEach(function (envVar) {
                if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
                    // get array of nested keys and convert them to camel case
                    var keys = envVar.split('__').map(function (key, i) {
                        if (i === 0) {
                            key = key.substring(prefix.length);
                        }
                        return camelCase(key);
                    });
                    if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) {
                        setArg(keys.join('.'), process.env[envVar]);
                    }
                }
            });
        }
        function applyCoercions(argv) {
            var coerce;
            var applied = {};
            Object.keys(argv).forEach(function (key) {
                if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
                    coerce = checkAllAliases(key, flags.coercions);
                    if (typeof coerce === 'function') {
                        try {
                            var value = coerce(argv[key]);
                            ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
                                applied[ali] = argv[ali] = value;
                            });
                        }
                        catch (err) {
                            error = err;
                        }
                    }
                }
            });
        }
        function applyDefaultsAndAliases(obj, aliases, defaults) {
            Object.keys(defaults).forEach(function (key) {
                if (!hasKey(obj, key.split('.'))) {
                    setKey(obj, key.split('.'), defaults[key]);
                    (aliases[key] || []).forEach(function (x) {
                        if (hasKey(obj, x.split('.')))
                            return;
                        setKey(obj, x.split('.'), defaults[key]);
                    });
                }
            });
        }
        function hasKey(obj, keys) {
            var o = obj;
            if (!configuration['dot-notation'])
                keys = [keys.join('.')];
            keys.slice(0, -1).forEach(function (key) {
                o = (o[key] || {});
            });
            var key = keys[keys.length - 1];
            if (typeof o !== 'object')
                return false;
            else
                return key in o;
        }
        function setKey(obj, keys, value) {
            var o = obj;
            if (!configuration['dot-notation'])
                keys = [keys.join('.')];
            keys.slice(0, -1).forEach(function (key, index) {
                if (typeof o === 'object' && o[key] === undefined) {
                    o[key] = {};
                }
                if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
                    // ensure that o[key] is an array, and that the last item is an empty object.
                    if (Array.isArray(o[key])) {
                        o[key].push({});
                    }
                    else {
                        o[key] = [o[key], {}];
                    }
                    // we want to update the empty object at the end of the o[key] array, so set o to that object
                    o = o[key][o[key].length - 1];
                }
                else {
                    o = o[key];
                }
            });
            var key = keys[keys.length - 1];
            var isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
            var isValueArray = Array.isArray(value);
            var duplicate = configuration['duplicate-arguments-array'];
            if (value === increment) {
                o[key] = increment(o[key]);
            }
            else if (Array.isArray(o[key])) {
                if (duplicate && isTypeArray && isValueArray) {
                    o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : [o[key]].concat([value]);
                }
                else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
                    o[key] = value;
                }
                else {
                    o[key] = o[key].concat([value]);
                }
            }
            else if (o[key] === undefined && isTypeArray) {
                o[key] = isValueArray ? value : [value];
            }
            else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) {
                o[key] = [o[key], value];
            }
            else {
                o[key] = value;
            }
        }
        // extend the aliases list with inferred aliases.
        function extendAliases() {
            Array.prototype.slice.call(arguments).forEach(function (obj) {
                Object.keys(obj || {}).forEach(function (key) {
                    // short-circuit if we've already added a key
                    // to the aliases array, for example it might
                    // exist in both 'opts.default' and 'opts.key'.
                    if (flags.aliases[key])
                        return;
                    flags.aliases[key] = [].concat(aliases[key] || []);
                    // For "--option-name", also set argv.optionName
                    flags.aliases[key].concat(key).forEach(function (x) {
                        if (/-/.test(x) && configuration['camel-case-expansion']) {
                            var c = camelCase(x);
                            if (c !== key && flags.aliases[key].indexOf(c) === -1) {
                                flags.aliases[key].push(c);
                                newAliases[c] = true;
                            }
                        }
                    });
                    flags.aliases[key].forEach(function (x) {
                        flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
                            return x !== y;
                        }));
                    });
                });
            });
        }
        // check if a flag is set for any of a key's aliases.
        function checkAllAliases(key, flag) {
            var isSet = false;
            var toCheck = [].concat(flags.aliases[key] || [], key);
            toCheck.forEach(function (key) {
                if (flag[key])
                    isSet = flag[key];
            });
            return isSet;
        }
        function setDefaulted(key) {
            [].concat(flags.aliases[key] || [], key).forEach(function (k) {
                flags.defaulted[k] = true;
            });
        }
        function unsetDefaulted(key) {
            [].concat(flags.aliases[key] || [], key).forEach(function (k) {
                delete flags.defaulted[k];
            });
        }
        // return a default value, given the type of a flag.,
        // e.g., key of type 'string' will default to '', rather than 'true'.
        function defaultForType(type) {
            var def = {
                boolean: true,
                string: '',
                number: undefined,
                array: []
            };
            return def[type];
        }
        // given a flag, enforce a default type.
        function guessType(key, flags) {
            var type = 'boolean';
            if (checkAllAliases(key, flags.strings))
                type = 'string';
            else if (checkAllAliases(key, flags.numbers))
                type = 'number';
            else if (checkAllAliases(key, flags.arrays))
                type = 'array';
            return type;
        }
        function isNumber(x) {
            if (typeof x === 'number')
                return true;
            if (/^0x[0-9a-f]+$/i.test(x))
                return true;
            return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
        }
        function isUndefined(num) {
            return num === undefined;
        }
        return {
            argv: argv,
            error: error,
            aliases: flags.aliases,
            newAliases: newAliases,
            configuration: configuration
        };
    }
    // if any aliases reference each other, we should
    // merge them together.
    function combineAliases(aliases) {
        var aliasArrays = [];
        var change = true;
        var combined = {};
        // turn alias lookup hash {key: ['alias1', 'alias2']} into
        // a simple array ['key', 'alias1', 'alias2']
        Object.keys(aliases).forEach(function (key) {
            aliasArrays.push([].concat(aliases[key], key));
        });
        // combine arrays until zero changes are
        // made in an iteration.
        while (change) {
            change = false;
            for (var i = 0; i < aliasArrays.length; i++) {
                for (var ii = i + 1; ii < aliasArrays.length; ii++) {
                    var intersect = aliasArrays[i].filter(function (v) {
                        return aliasArrays[ii].indexOf(v) !== -1;
                    });
                    if (intersect.length) {
                        aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
                        aliasArrays.splice(ii, 1);
                        change = true;
                        break;
                    }
                }
            }
        }
        // map arrays back to the hash-lookup (de-dupe while
        // we're at it).
        aliasArrays.forEach(function (aliasArray) {
            aliasArray = aliasArray.filter(function (v, i, self) {
                return self.indexOf(v) === i;
            });
            combined[aliasArray.pop()] = aliasArray;
        });
        return combined;
    }
    function assign(defaults, configuration) {
        var o = {};
        configuration = configuration || {};
        Object.keys(defaults).forEach(function (k) {
            o[k] = defaults[k];
        });
        Object.keys(configuration).forEach(function (k) {
            o[k] = configuration[k];
        });
        return o;
    }
    // this function should only be called when a count is given as an arg
    // it is NOT called to set a default value
    // thus we can start the count at 1 instead of 0
    function increment(orig) {
        return orig !== undefined ? orig + 1 : 1;
    }
    function Parser(args, opts) {
        var result = parse(args.slice(), opts);
        return result.argv;
    }
    // parse arguments and return detailed
    // meta information, aliases, etc.
    Parser.detailed = function (args, opts) {
        return parse(args.slice(), opts);
    };
    module.exports = Parser;
}
,
/* yargs-parser/lib/tokenize-arg-string */ function _(require, module, exports) {
    // take an un-split argv string and tokenize it.
    module.exports = function (argString) {
        if (Array.isArray(argString))
            return argString;
        argString = argString.trim();
        var i = 0;
        var prevC = null;
        var c = null;
        var opening = null;
        var args = [];
        for (var ii = 0; ii < argString.length; ii++) {
            prevC = c;
            c = argString.charAt(ii);
            // split on spaces unless we're in quotes.
            if (c === ' ' && !opening) {
                if (!(prevC === ' ')) {
                    i++;
                }
                continue;
            }
            // don't split the string if we're in matching
            // opening or closing single and double quotes.
            if (c === opening) {
                opening = null;
                continue;
            }
            else if ((c === "'" || c === '"') && !opening) {
                opening = c;
                continue;
            }
            if (!args[i])
                args[i] = '';
            args[i] += c;
        }
        return args;
    };
}
,
/* yargs/index */ function _(require, module, exports) {
    // classic singleton yargs API, to use yargs
    // without running as a singleton do:
    // require('yargs/yargs')(process.argv.slice(2))
    const yargs = require(389) /* ./yargs */;
    Argv(process.argv.slice(2));
    module.exports = Argv;
    function Argv(processArgs, cwd) {
        const argv = yargs(processArgs, cwd, require);
        singletonify(argv);
        return argv;
    }
    /*  Hack an instance of Argv with process.argv into Argv
        so people can do
        require('yargs')(['--beeble=1','-z','zizzle']).argv
        to parse a list of args and
        require('yargs').argv
        to get a parsed version of process.argv.
    */
    function singletonify(inst) {
        Object.keys(inst).forEach((key) => {
            if (key === 'argv') {
                Argv.__defineGetter__(key, inst.__lookupGetter__(key));
            }
            else {
                Argv[key] = typeof inst[key] === 'function' ? inst[key].bind(inst) : inst[key];
            }
        });
    }
}
,
/* yargs/lib/apply-extends */ function _(require, module, exports) {
    const fs = require('fs');
    const path = require('path');
    const YError = require(388) /* ./yerror */;
    let previouslyVisitedConfigs = [];
    function checkForCircularExtends(path) {
        if (previouslyVisitedConfigs.indexOf(path) > -1) {
            throw new YError(`Circular extended configurations: '${path}'.`);
        }
    }
    function getPathToDefaultConfig(cwd, pathToExtend) {
        return path.resolve(cwd, pathToExtend);
    }
    function applyExtends(config, cwd) {
        let defaultConfig = {};
        if (config.hasOwnProperty('extends')) {
            if (typeof config.extends !== 'string')
                return defaultConfig;
            const isPath = /\.json$/.test(config.extends);
            let pathToDefault = null;
            if (!isPath) {
                try {
                    pathToDefault = require.resolve(config.extends);
                }
                catch (err) {
                    // most likely this simply isn't a module.
                }
            }
            else {
                pathToDefault = getPathToDefaultConfig(cwd, config.extends);
            }
            // maybe the module uses key for some other reason,
            // err on side of caution.
            if (!pathToDefault && !isPath)
                return config;
            checkForCircularExtends(pathToDefault);
            previouslyVisitedConfigs.push(pathToDefault);
            defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends);
            delete config.extends;
            defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault));
        }
        previouslyVisitedConfigs = [];
        return Object.assign({}, defaultConfig, config);
    }
    module.exports = applyExtends;
}
,
/* yargs/lib/argsert */ function _(require, module, exports) {
    const command = require(382) /* ./command */();
    const YError = require(388) /* ./yerror */;
    const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
    module.exports = function argsert(expected, callerArguments, length) {
        // TODO: should this eventually raise an exception.
        try {
            // preface the argument description with "cmd", so
            // that we can run it through yargs' command parser.
            let position = 0;
            let parsed = { demanded: [], optional: [] };
            if (typeof expected === 'object') {
                length = callerArguments;
                callerArguments = expected;
            }
            else {
                parsed = command.parseCommand(`cmd ${expected}`);
            }
            const args = [].slice.call(callerArguments);
            while (args.length && args[args.length - 1] === undefined)
                args.pop();
            length = length || args.length;
            if (length < parsed.demanded.length) {
                throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
            }
            const totalCommands = parsed.demanded.length + parsed.optional.length;
            if (length > totalCommands) {
                throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
            }
            parsed.demanded.forEach((demanded) => {
                const arg = args.shift();
                const observedType = guessType(arg);
                const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
                if (matchingTypes.length === 0)
                    argumentTypeError(observedType, demanded.cmd, position, false);
                position += 1;
            });
            parsed.optional.forEach((optional) => {
                if (args.length === 0)
                    return;
                const arg = args.shift();
                const observedType = guessType(arg);
                const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
                if (matchingTypes.length === 0)
                    argumentTypeError(observedType, optional.cmd, position, true);
                position += 1;
            });
        }
        catch (err) {
            console.warn(err.stack);
        }
    };
    function guessType(arg) {
        if (Array.isArray(arg)) {
            return 'array';
        }
        else if (arg === null) {
            return 'null';
        }
        return typeof arg;
    }
    function argumentTypeError(observedType, allowedTypes, position, optional) {
        throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
    }
}
,
/* yargs/lib/command */ function _(require, module, exports) {
    const inspect = require('util').inspect;
    const path = require('path');
    const Parser = require(377) /* yargs-parser */;
    const DEFAULT_MARKER = /(^\*)|(^\$0)/;
    // handles parsing positional arguments,
    // and populating argv with said positional
    // arguments.
    module.exports = function command(yargs, usage, validation) {
        const self = {};
        let handlers = {};
        let aliasMap = {};
        let defaultCommand;
        self.addHandler = function addHandler(cmd, description, builder, handler, middlewares) {
            let aliases = [];
            handler = handler || (() => { });
            middlewares = middlewares || [];
            if (Array.isArray(cmd)) {
                aliases = cmd.slice(1);
                cmd = cmd[0];
            }
            else if (typeof cmd === 'object') {
                let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd);
                if (cmd.aliases)
                    command = [].concat(command).concat(cmd.aliases);
                self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares);
                return;
            }
            // allow a module to be provided instead of separate builder and handler
            if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') {
                self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares);
                return;
            }
            // parse positionals out of cmd string
            const parsedCommand = self.parseCommand(cmd);
            // remove positional args from aliases only
            aliases = aliases.map(alias => self.parseCommand(alias).cmd);
            // check for default and filter out '*''
            let isDefault = false;
            const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
                if (DEFAULT_MARKER.test(c)) {
                    isDefault = true;
                    return false;
                }
                return true;
            });
            // standardize on $0 for default command.
            if (parsedAliases.length === 0 && isDefault)
                parsedAliases.push('$0');
            // shift cmd and aliases after filtering out '*'
            if (isDefault) {
                parsedCommand.cmd = parsedAliases[0];
                aliases = parsedAliases.slice(1);
                cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
            }
            // populate aliasMap
            aliases.forEach((alias) => {
                aliasMap[alias] = parsedCommand.cmd;
            });
            if (description !== false) {
                usage.command(cmd, description, isDefault, aliases);
            }
            handlers[parsedCommand.cmd] = {
                original: cmd,
                description: description,
                handler,
                builder: builder || {},
                middlewares: middlewares || [],
                demanded: parsedCommand.demanded,
                optional: parsedCommand.optional
            };
            if (isDefault)
                defaultCommand = handlers[parsedCommand.cmd];
        };
        self.addDirectory = function addDirectory(dir, context, req, callerFile, opts) {
            opts = opts || {};
            // disable recursion to support nested directories of subcommands
            if (typeof opts.recurse !== 'boolean')
                opts.recurse = false;
            // exclude 'json', 'coffee' from require-directory defaults
            if (!Array.isArray(opts.extensions))
                opts.extensions = ['js'];
            // allow consumer to define their own visitor function
            const parentVisit = typeof opts.visit === 'function' ? opts.visit : o => o;
            // call addHandler via visitor function
            opts.visit = function visit(obj, joined, filename) {
                const visited = parentVisit(obj, joined, filename);
                // allow consumer to skip modules with their own visitor
                if (visited) {
                    // check for cyclic reference
                    // each command file path should only be seen once per execution
                    if (~context.files.indexOf(joined))
                        return visited;
                    // keep track of visited files in context.files
                    context.files.push(joined);
                    self.addHandler(visited);
                }
                return visited;
            };
            require(308) /* require-directory */({ require: req, filename: callerFile }, dir, opts);
        };
        // lookup module object from require()d command and derive name
        // if module was not require()d and no name given, throw error
        function moduleName(obj) {
            const mod = require(372) /* which-module */(obj);
            if (!mod)
                throw new Error(`No command name given for module: ${inspect(obj)}`);
            return commandFromFilename(mod.filename);
        }
        // derive command name from filename
        function commandFromFilename(filename) {
            return path.basename(filename, path.extname(filename));
        }
        function extractDesc(obj) {
            for (let keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {
                test = obj[keys[i]];
                if (typeof test === 'string' || typeof test === 'boolean')
                    return test;
            }
            return false;
        }
        self.parseCommand = function parseCommand(cmd) {
            const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
            const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
            const bregex = /\.*[\][<>]/g;
            const parsedCommand = {
                cmd: (splitCommand.shift()).replace(bregex, ''),
                demanded: [],
                optional: []
            };
            splitCommand.forEach((cmd, i) => {
                let variadic = false;
                cmd = cmd.replace(/\s/g, '');
                if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
                    variadic = true;
                if (/^\[/.test(cmd)) {
                    parsedCommand.optional.push({
                        cmd: cmd.replace(bregex, '').split('|'),
                        variadic
                    });
                }
                else {
                    parsedCommand.demanded.push({
                        cmd: cmd.replace(bregex, '').split('|'),
                        variadic
                    });
                }
            });
            return parsedCommand;
        };
        self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap));
        self.getCommandHandlers = () => handlers;
        self.hasDefaultCommand = () => !!defaultCommand;
        self.runCommand = function runCommand(command, yargs, parsed, commandIndex) {
            let aliases = parsed.aliases;
            const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand;
            const currentContext = yargs.getContext();
            let numFiles = currentContext.files.length;
            const parentCommands = currentContext.commands.slice();
            // what does yargs look like after the buidler is run?
            let innerArgv = parsed.argv;
            let innerYargs = null;
            let positionalMap = {};
            if (command) {
                currentContext.commands.push(command);
                currentContext.fullCommands.push(commandHandler.original);
            }
            if (typeof commandHandler.builder === 'function') {
                // a function can be provided, which builds
                // up a yargs chain and possibly returns it.
                innerYargs = commandHandler.builder(yargs.reset(parsed.aliases));
                // if the builder function did not yet parse argv with reset yargs
                // and did not explicitly set a usage() string, then apply the
                // original command string as usage() for consistent behavior with
                // options object below.
                if (yargs.parsed === false) {
                    if (shouldUpdateUsage(yargs)) {
                        yargs.getUsageInstance().usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
                    }
                    innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex);
                }
                else {
                    innerArgv = yargs.parsed.argv;
                }
                if (innerYargs && yargs.parsed === false)
                    aliases = innerYargs.parsed.aliases;
                else
                    aliases = yargs.parsed.aliases;
            }
            else if (typeof commandHandler.builder === 'object') {
                // as a short hand, an object can instead be provided, specifying
                // the options that a command takes.
                innerYargs = yargs.reset(parsed.aliases);
                if (shouldUpdateUsage(innerYargs)) {
                    innerYargs.getUsageInstance().usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
                }
                Object.keys(commandHandler.builder).forEach((key) => {
                    innerYargs.option(key, commandHandler.builder[key]);
                });
                innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
                aliases = innerYargs.parsed.aliases;
            }
            if (!yargs._hasOutput()) {
                positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs);
            }
            // we apply validation post-hoc, so that custom
            // checks get passed populated positional arguments.
            if (!yargs._hasOutput())
                yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error);
            if (commandHandler.handler && !yargs._hasOutput()) {
                yargs._setHasOutput();
                if (commandHandler.middlewares.length > 0) {
                    const middlewareArgs = commandHandler.middlewares.reduce(function (initialObj, middleware) {
                        return Object.assign(initialObj, middleware(innerArgv));
                    }, {});
                    Object.assign(innerArgv, middlewareArgs);
                }
                const handlerResult = commandHandler.handler(innerArgv);
                if (handlerResult && typeof handlerResult.then === 'function') {
                    handlerResult.then(null, (error) => yargs.getUsageInstance().fail(null, error));
                }
            }
            if (command) {
                currentContext.commands.pop();
                currentContext.fullCommands.pop();
            }
            numFiles = currentContext.files.length - numFiles;
            if (numFiles > 0)
                currentContext.files.splice(numFiles * -1, numFiles);
            return innerArgv;
        };
        function shouldUpdateUsage(yargs) {
            return !yargs.getUsageInstance().getUsageDisabled() &&
                yargs.getUsageInstance().getUsage().length === 0;
        }
        function usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
            const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original;
            const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c); });
            pc.push(c);
            return `$0 ${pc.join(' ')}`;
        }
        self.runDefaultBuilderOn = function (yargs) {
            if (shouldUpdateUsage(yargs)) {
                // build the root-level command string from the default string.
                const commandString = DEFAULT_MARKER.test(defaultCommand.original)
                    ? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
                yargs.getUsageInstance().usage(commandString, defaultCommand.description);
            }
            const builder = defaultCommand.builder;
            if (typeof builder === 'function') {
                builder(yargs);
            }
            else {
                Object.keys(builder).forEach((key) => {
                    yargs.option(key, builder[key]);
                });
            }
        };
        // transcribe all positional arguments "command <foo> <bar> [apple]"
        // onto argv.
        function populatePositionals(commandHandler, argv, context, yargs) {
            argv._ = argv._.slice(context.commands.length); // nuke the current commands
            const demanded = commandHandler.demanded.slice(0);
            const optional = commandHandler.optional.slice(0);
            const positionalMap = {};
            validation.positionalCount(demanded.length, argv._.length);
            while (demanded.length) {
                const demand = demanded.shift();
                populatePositional(demand, argv, positionalMap);
            }
            while (optional.length) {
                const maybe = optional.shift();
                populatePositional(maybe, argv, positionalMap);
            }
            argv._ = context.commands.concat(argv._);
            postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original));
            return positionalMap;
        }
        function populatePositional(positional, argv, positionalMap, parseOptions) {
            const cmd = positional.cmd[0];
            if (positional.variadic) {
                positionalMap[cmd] = argv._.splice(0).map(String);
            }
            else {
                if (argv._.length)
                    positionalMap[cmd] = [String(argv._.shift())];
            }
        }
        // we run yargs-parser against the positional arguments
        // applying the same parsing logic used for flags.
        function postProcessPositionals(argv, positionalMap, parseOptions) {
            // combine the parsing hints we've inferred from the command
            // string with explicitly configured parsing hints.
            const options = Object.assign({}, yargs.getOptions());
            options.default = Object.assign(parseOptions.default, options.default);
            options.alias = Object.assign(parseOptions.alias, options.alias);
            options.array = options.array.concat(parseOptions.array);
            const unparsed = [];
            Object.keys(positionalMap).forEach((key) => {
                positionalMap[key].map((value) => {
                    unparsed.push(`--${key}`);
                    unparsed.push(value);
                });
            });
            // short-circuit parse.
            if (!unparsed.length)
                return;
            const parsed = Parser.detailed(unparsed, options);
            if (parsed.error) {
                yargs.getUsageInstance().fail(parsed.error.message, parsed.error);
            }
            else {
                // only copy over positional keys (don't overwrite
                // flag arguments that were already parsed).
                const positionalKeys = Object.keys(positionalMap);
                Object.keys(positionalMap).forEach((key) => {
                    [].push.apply(positionalKeys, parsed.aliases[key]);
                });
                Object.keys(parsed.argv).forEach((key) => {
                    if (positionalKeys.indexOf(key) !== -1) {
                        argv[key] = parsed.argv[key];
                    }
                });
            }
        }
        self.cmdToParseOptions = function (cmdString) {
            const parseOptions = {
                array: [],
                default: {},
                alias: {},
                demand: {}
            };
            const parsed = self.parseCommand(cmdString);
            parsed.demanded.forEach((d) => {
                const cmds = d.cmd.slice(0);
                const cmd = cmds.shift();
                if (d.variadic) {
                    parseOptions.array.push(cmd);
                    parseOptions.default[cmd] = [];
                }
                cmds.forEach((c) => {
                    parseOptions.alias[cmd] = c;
                });
                parseOptions.demand[cmd] = true;
            });
            parsed.optional.forEach((o) => {
                const cmds = o.cmd.slice(0);
                const cmd = cmds.shift();
                if (o.variadic) {
                    parseOptions.array.push(cmd);
                    parseOptions.default[cmd] = [];
                }
                cmds.forEach((c) => {
                    parseOptions.alias[cmd] = c;
                });
            });
            return parseOptions;
        };
        self.reset = () => {
            handlers = {};
            aliasMap = {};
            defaultCommand = undefined;
            return self;
        };
        // used by yargs.parse() to freeze
        // the state of commands such that
        // we can apply .parse() multiple times
        // with the same yargs instance.
        let frozen;
        self.freeze = () => {
            frozen = {};
            frozen.handlers = handlers;
            frozen.aliasMap = aliasMap;
            frozen.defaultCommand = defaultCommand;
        };
        self.unfreeze = () => {
            handlers = frozen.handlers;
            aliasMap = frozen.aliasMap;
            defaultCommand = frozen.defaultCommand;
            frozen = undefined;
        };
        return self;
    };
}
,
/* yargs/lib/completion */ function _(require, module, exports) {
    const fs = require('fs');
    const path = require('path');
    // add bash completions to your
    //  yargs-powered applications.
    module.exports = function completion(yargs, usage, command) {
        const self = {
            completionKey: 'get-yargs-completions'
        };
        // get a list of completion commands.
        // 'args' is the array of strings from the line to be completed
        self.getCompletion = function getCompletion(args, done) {
            const completions = [];
            const current = args.length ? args[args.length - 1] : '';
            const argv = yargs.parse(args, true);
            const aliases = yargs.parsed.aliases;
            // a custom completion function can be provided
            // to completion().
            if (completionFunction) {
                if (completionFunction.length < 3) {
                    const result = completionFunction(current, argv);
                    // promise based completion function.
                    if (typeof result.then === 'function') {
                        return result.then((list) => {
                            process.nextTick(() => { done(list); });
                        }).catch((err) => {
                            process.nextTick(() => { throw err; });
                        });
                    }
                    // synchronous completion function.
                    return done(result);
                }
                else {
                    // asynchronous completion function
                    return completionFunction(current, argv, (completions) => {
                        done(completions);
                    });
                }
            }
            const handlers = command.getCommandHandlers();
            for (let i = 0, ii = args.length; i < ii; ++i) {
                if (handlers[args[i]] && handlers[args[i]].builder) {
                    const builder = handlers[args[i]].builder;
                    if (typeof builder === 'function') {
                        const y = yargs.reset();
                        builder(y);
                        return y.argv;
                    }
                }
            }
            if (!current.match(/^-/)) {
                usage.getCommands().forEach((usageCommand) => {
                    const commandName = command.parseCommand(usageCommand[0]).cmd;
                    if (args.indexOf(commandName) === -1) {
                        completions.push(commandName);
                    }
                });
            }
            if (current.match(/^-/)) {
                Object.keys(yargs.getOptions().key).forEach((key) => {
                    // If the key and its aliases aren't in 'args', add the key to 'completions'
                    const keyAndAliases = [key].concat(aliases[key] || []);
                    const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1);
                    if (notInArgs) {
                        completions.push(`--${key}`);
                    }
                });
            }
            done(completions);
        };
        // generate the completion script to add to your .bashrc.
        self.generateCompletionScript = function generateCompletionScript($0, cmd) {
            let script = fs.readFileSync(path.resolve(__dirname, '../completion.sh.hbs'), 'utf-8');
            const name = path.basename($0);
            // add ./to applications not yet installed as bin.
            if ($0.match(/\.js$/))
                $0 = `./${$0}`;
            script = script.replace(/{{app_name}}/g, name);
            script = script.replace(/{{completion_command}}/g, cmd);
            return script.replace(/{{app_path}}/g, $0);
        };
        // register a function to perform your own custom
        // completions., this function can be either
        // synchrnous or asynchronous.
        let completionFunction = null;
        self.registerFunction = (fn) => {
            completionFunction = fn;
        };
        return self;
    };
}
,
/* yargs/lib/levenshtein */ function _(require, module, exports) {
    // Compute the edit distance between the two given strings
    module.exports = function levenshtein(a, b) {
        if (a.length === 0)
            return b.length;
        if (b.length === 0)
            return a.length;
        const matrix = [];
        // increment along the first column of each row
        let i;
        for (i = 0; i <= b.length; i++) {
            matrix[i] = [i];
        }
        // increment each column in the first row
        let j;
        for (j = 0; j <= a.length; j++) {
            matrix[0][j] = j;
        }
        // Fill in the rest of the matrix
        for (i = 1; i <= b.length; i++) {
            for (j = 1; j <= a.length; j++) {
                if (b.charAt(i - 1) === a.charAt(j - 1)) {
                    matrix[i][j] = matrix[i - 1][j - 1];
                }
                else {
                    matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
                    Math.min(matrix[i][j - 1] + 1, // insertion
                    matrix[i - 1][j] + 1)); // deletion
                }
            }
        }
        return matrix[b.length][a.length];
    };
}
,
/* yargs/lib/obj-filter */ function _(require, module, exports) {
    module.exports = function objFilter(original, filter) {
        const obj = {};
        filter = filter || ((k, v) => true);
        Object.keys(original || {}).forEach((key) => {
            if (filter(key, original[key])) {
                obj[key] = original[key];
            }
        });
        return obj;
    };
}
,
/* yargs/lib/usage */ function _(require, module, exports) {
    // this file handles outputting usage instructions,
    // failures, etc. keeps logging in one place.
    const stringWidth = require(355) /* string-width */;
    const objFilter = require(385) /* ./obj-filter */;
    const path = require('path');
    const setBlocking = require(313) /* set-blocking */;
    const YError = require(388) /* ./yerror */;
    module.exports = function usage(yargs, y18n) {
        const __ = y18n.__;
        const self = {};
        // methods for ouputting/building failure message.
        const fails = [];
        self.failFn = function failFn(f) {
            fails.push(f);
        };
        let failMessage = null;
        let showHelpOnFail = true;
        self.showHelpOnFail = function showHelpOnFailFn(enabled, message) {
            if (typeof enabled === 'string') {
                message = enabled;
                enabled = true;
            }
            else if (typeof enabled === 'undefined') {
                enabled = true;
            }
            failMessage = message;
            showHelpOnFail = enabled;
            return self;
        };
        let failureOutput = false;
        self.fail = function fail(msg, err) {
            const logger = yargs._getLoggerInstance();
            if (fails.length) {
                for (let i = fails.length - 1; i >= 0; --i) {
                    fails[i](msg, err, self);
                }
            }
            else {
                if (yargs.getExitProcess())
                    setBlocking(true);
                // don't output failure message more than once
                if (!failureOutput) {
                    failureOutput = true;
                    if (showHelpOnFail)
                        yargs.showHelp('error');
                    if (msg || err)
                        logger.error(msg || err);
                    if (failMessage) {
                        if (msg || err)
                            logger.error('');
                        logger.error(failMessage);
                    }
                }
                err = err || new YError(msg);
                if (yargs.getExitProcess()) {
                    return yargs.exit(1);
                }
                else if (yargs._hasParseCallback()) {
                    return yargs.exit(1, err);
                }
                else {
                    throw err;
                }
            }
        };
        // methods for ouputting/building help (usage) message.
        let usages = [];
        let usageDisabled = false;
        self.usage = (msg, description) => {
            if (msg === null) {
                usageDisabled = true;
                usages = [];
                return;
            }
            usageDisabled = false;
            usages.push([msg, description || '']);
            return self;
        };
        self.getUsage = () => {
            return usages;
        };
        self.getUsageDisabled = () => {
            return usageDisabled;
        };
        self.getPositionalGroupName = () => {
            return __('Positionals:');
        };
        let examples = [];
        self.example = (cmd, description) => {
            examples.push([cmd, description || '']);
        };
        let commands = [];
        self.command = function command(cmd, description, isDefault, aliases) {
            // the last default wins, so cancel out any previously set default
            if (isDefault) {
                commands = commands.map((cmdArray) => {
                    cmdArray[2] = false;
                    return cmdArray;
                });
            }
            commands.push([cmd, description || '', isDefault, aliases]);
        };
        self.getCommands = () => commands;
        let descriptions = {};
        self.describe = function describe(key, desc) {
            if (typeof key === 'object') {
                Object.keys(key).forEach((k) => {
                    self.describe(k, key[k]);
                });
            }
            else {
                descriptions[key] = desc;
            }
        };
        self.getDescriptions = () => descriptions;
        let epilog;
        self.epilog = (msg) => {
            epilog = msg;
        };
        let wrapSet = false;
        let wrap;
        self.wrap = (cols) => {
            wrapSet = true;
            wrap = cols;
        };
        function getWrap() {
            if (!wrapSet) {
                wrap = windowWidth();
                wrapSet = true;
            }
            return wrap;
        }
        const deferY18nLookupPrefix = '__yargsString__:';
        self.deferY18nLookup = str => deferY18nLookupPrefix + str;
        const defaultGroup = 'Options:';
        self.help = function help() {
            normalizeAliases();
            // handle old demanded API
            const base$0 = path.basename(yargs.$0);
            const demandedOptions = yargs.getDemandedOptions();
            const demandedCommands = yargs.getDemandedCommands();
            const groups = yargs.getGroups();
            const options = yargs.getOptions();
            let keys = Object.keys(Object.keys(descriptions)
                .concat(Object.keys(demandedOptions))
                .concat(Object.keys(demandedCommands))
                .concat(Object.keys(options.default))
                .reduce((acc, key) => {
                if (key !== '_')
                    acc[key] = true;
                return acc;
            }, {}));
            const theWrap = getWrap();
            const ui = require(73) /* cliui */({
                width: theWrap,
                wrap: !!theWrap
            });
            // the usage string.
            if (!usageDisabled) {
                if (usages.length) {
                    // user-defined usage.
                    usages.forEach((usage) => {
                        ui.div(`${usage[0].replace(/\$0/g, base$0)}`);
                        if (usage[1]) {
                            ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
                        }
                    });
                    ui.div();
                }
                else if (commands.length) {
                    let u = null;
                    // demonstrate how commands are used.
                    if (demandedCommands._) {
                        u = `${base$0} <${__('command')}>\n`;
                    }
                    else {
                        u = `${base$0} [${__('command')}]\n`;
                    }
                    ui.div(`${u}`);
                }
            }
            // your application's commands, i.e., non-option
            // arguments populated in '_'.
            if (commands.length) {
                ui.div(__('Commands:'));
                const context = yargs.getContext();
                const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : '';
                commands.forEach((command) => {
                    const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; // drop $0 from default commands.
                    ui.span({
                        text: commandString,
                        padding: [0, 2, 0, 2],
                        width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
                    }, { text: command[1] });
                    const hints = [];
                    if (command[2])
                        hints.push(`[${__('default:').slice(0, -1)}]`); // TODO hacking around i18n here
                    if (command[3] && command[3].length) {
                        hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
                    }
                    if (hints.length) {
                        ui.div({ text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right' });
                    }
                    else {
                        ui.div();
                    }
                });
                ui.div();
            }
            // perform some cleanup on the keys array, making it
            // only include top-level keys not their aliases.
            const aliasKeys = (Object.keys(options.alias) || [])
                .concat(Object.keys(yargs.parsed.newAliases) || []);
            keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
            // populate 'Options:' group with any keys that have not
            // explicitly had a group set.
            if (!groups[defaultGroup])
                groups[defaultGroup] = [];
            addUngroupedKeys(keys, options.alias, groups);
            // display 'Options:' table along with any custom tables:
            Object.keys(groups).forEach((groupName) => {
                if (!groups[groupName].length)
                    return;
                ui.div(__(groupName));
                // if we've grouped the key 'f', but 'f' aliases 'foobar',
                // normalizedKeys should contain only 'foobar'.
                const normalizedKeys = groups[groupName].map((key) => {
                    if (~aliasKeys.indexOf(key))
                        return key;
                    for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
                        if (~(options.alias[aliasKey] || []).indexOf(key))
                            return aliasKey;
                    }
                    return key;
                });
                // actually generate the switches string --foo, -f, --bar.
                const switches = normalizedKeys.reduce((acc, key) => {
                    acc[key] = [key].concat(options.alias[key] || [])
                        .map(sw => {
                        // for the special positional group don't
                        // add '--' or '-' prefix.
                        if (groupName === self.getPositionalGroupName())
                            return sw;
                        else
                            return (sw.length > 1 ? '--' : '-') + sw;
                    })
                        .join(', ');
                    return acc;
                }, {});
                normalizedKeys.forEach((key) => {
                    const kswitch = switches[key];
                    let desc = descriptions[key] || '';
                    let type = null;
                    if (~desc.lastIndexOf(deferY18nLookupPrefix))
                        desc = __(desc.substring(deferY18nLookupPrefix.length));
                    if (~options.boolean.indexOf(key))
                        type = `[${__('boolean')}]`;
                    if (~options.count.indexOf(key))
                        type = `[${__('count')}]`;
                    if (~options.string.indexOf(key))
                        type = `[${__('string')}]`;
                    if (~options.normalize.indexOf(key))
                        type = `[${__('string')}]`;
                    if (~options.array.indexOf(key))
                        type = `[${__('array')}]`;
                    if (~options.number.indexOf(key))
                        type = `[${__('number')}]`;
                    const extra = [
                        type,
                        (key in demandedOptions) ? `[${__('required')}]` : null,
                        options.choices && options.choices[key] ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` : null,
                        defaultString(options.default[key], options.defaultDescription[key])
                    ].filter(Boolean).join(' ');
                    ui.span({ text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4 }, desc);
                    if (extra)
                        ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
                    else
                        ui.div();
                });
                ui.div();
            });
            // describe some common use-cases for your application.
            if (examples.length) {
                ui.div(__('Examples:'));
                examples.forEach((example) => {
                    example[0] = example[0].replace(/\$0/g, base$0);
                });
                examples.forEach((example) => {
                    if (example[1] === '') {
                        ui.div({
                            text: example[0],
                            padding: [0, 2, 0, 2]
                        });
                    }
                    else {
                        ui.div({
                            text: example[0],
                            padding: [0, 2, 0, 2],
                            width: maxWidth(examples, theWrap) + 4
                        }, {
                            text: example[1]
                        });
                    }
                });
                ui.div();
            }
            // the usage string.
            if (epilog) {
                const e = epilog.replace(/\$0/g, base$0);
                ui.div(`${e}\n`);
            }
            return ui.toString();
        };
        // return the maximum width of a string
        // in the left-hand column of a table.
        function maxWidth(table, theWrap, modifier) {
            let width = 0;
            // table might be of the form [leftColumn],
            // or {key: leftColumn}
            if (!Array.isArray(table)) {
                table = Object.keys(table).map(key => [table[key]]);
            }
            table.forEach((v) => {
                width = Math.max(stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]), width);
            });
            // if we've enabled 'wrap' we should limit
            // the max-width of the left-column.
            if (theWrap)
                width = Math.min(width, parseInt(theWrap * 0.5, 10));
            return width;
        }
        // make sure any options set for aliases,
        // are copied to the keys being aliased.
        function normalizeAliases() {
            // handle old demanded API
            const demandedOptions = yargs.getDemandedOptions();
            const options = yargs.getOptions();
            (Object.keys(options.alias) || []).forEach((key) => {
                options.alias[key].forEach((alias) => {
                    // copy descriptions.
                    if (descriptions[alias])
                        self.describe(key, descriptions[alias]);
                    // copy demanded.
                    if (alias in demandedOptions)
                        yargs.demandOption(key, demandedOptions[alias]);
                    // type messages.
                    if (~options.boolean.indexOf(alias))
                        yargs.boolean(key);
                    if (~options.count.indexOf(alias))
                        yargs.count(key);
                    if (~options.string.indexOf(alias))
                        yargs.string(key);
                    if (~options.normalize.indexOf(alias))
                        yargs.normalize(key);
                    if (~options.array.indexOf(alias))
                        yargs.array(key);
                    if (~options.number.indexOf(alias))
                        yargs.number(key);
                });
            });
        }
        // given a set of keys, place any keys that are
        // ungrouped under the 'Options:' grouping.
        function addUngroupedKeys(keys, aliases, groups) {
            let groupedKeys = [];
            let toCheck = null;
            Object.keys(groups).forEach((group) => {
                groupedKeys = groupedKeys.concat(groups[group]);
            });
            keys.forEach((key) => {
                toCheck = [key].concat(aliases[key]);
                if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
                    groups[defaultGroup].push(key);
                }
            });
            return groupedKeys;
        }
        self.showHelp = (level) => {
            const logger = yargs._getLoggerInstance();
            if (!level)
                level = 'error';
            const emit = typeof level === 'function' ? level : logger[level];
            emit(self.help());
        };
        self.functionDescription = (fn) => {
            const description = fn.name ? require(98) /* decamelize */(fn.name, '-') : __('generated-value');
            return ['(', description, ')'].join('');
        };
        self.stringifiedValues = function stringifiedValues(values, separator) {
            let string = '';
            const sep = separator || ', ';
            const array = [].concat(values);
            if (!values || !array.length)
                return string;
            array.forEach((value) => {
                if (string.length)
                    string += sep;
                string += JSON.stringify(value);
            });
            return string;
        };
        // format the default-value-string displayed in
        // the right-hand column.
        function defaultString(value, defaultDescription) {
            let string = `[${__('default:')} `;
            if (value === undefined && !defaultDescription)
                return null;
            if (defaultDescription) {
                string += defaultDescription;
            }
            else {
                switch (typeof value) {
                    case 'string':
                        string += `"${value}"`;
                        break;
                    case 'object':
                        string += JSON.stringify(value);
                        break;
                    default:
                        string += value;
                }
            }
            return `${string}]`;
        }
        // guess the width of the console window, max-width 80.
        function windowWidth() {
            const maxWidth = 80;
            if (typeof process === 'object' && process.stdout && process.stdout.columns) {
                return Math.min(maxWidth, process.stdout.columns);
            }
            else {
                return maxWidth;
            }
        }
        // logic for displaying application version.
        let version = null;
        self.version = (ver) => {
            version = ver;
        };
        self.showVersion = () => {
            const logger = yargs._getLoggerInstance();
            logger.log(version);
        };
        self.reset = function reset(localLookup) {
            // do not reset wrap here
            // do not reset fails here
            failMessage = null;
            failureOutput = false;
            usages = [];
            usageDisabled = false;
            epilog = undefined;
            examples = [];
            commands = [];
            descriptions = objFilter(descriptions, (k, v) => !localLookup[k]);
            return self;
        };
        let frozen;
        self.freeze = function freeze() {
            frozen = {};
            frozen.failMessage = failMessage;
            frozen.failureOutput = failureOutput;
            frozen.usages = usages;
            frozen.usageDisabled = usageDisabled;
            frozen.epilog = epilog;
            frozen.examples = examples;
            frozen.commands = commands;
            frozen.descriptions = descriptions;
        };
        self.unfreeze = function unfreeze() {
            failMessage = frozen.failMessage;
            failureOutput = frozen.failureOutput;
            usages = frozen.usages;
            usageDisabled = frozen.usageDisabled;
            epilog = frozen.epilog;
            examples = frozen.examples;
            commands = frozen.commands;
            descriptions = frozen.descriptions;
            frozen = undefined;
        };
        return self;
    };
}
,
/* yargs/lib/validation */ function _(require, module, exports) {
    const argsert = require(381) /* ./argsert */;
    const objFilter = require(385) /* ./obj-filter */;
    const specialKeys = ['$0', '--', '_'];
    // validation-type-stuff, missing params,
    // bad implications, custom checks.
    module.exports = function validation(yargs, usage, y18n) {
        const __ = y18n.__;
        const __n = y18n.__n;
        const self = {};
        // validate appropriate # of non-option
        // arguments were provided, i.e., '_'.
        self.nonOptionCount = function nonOptionCount(argv) {
            const demandedCommands = yargs.getDemandedCommands();
            // don't count currently executing commands
            const _s = argv._.length - yargs.getContext().commands.length;
            if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
                if (_s < demandedCommands._.min) {
                    if (demandedCommands._.minMsg !== undefined) {
                        usage.fail(
                        // replace $0 with observed, $1 with expected.
                        demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.min) : null);
                    }
                    else {
                        usage.fail(__('Not enough non-option arguments: got %s, need at least %s', _s, demandedCommands._.min));
                    }
                }
                else if (_s > demandedCommands._.max) {
                    if (demandedCommands._.maxMsg !== undefined) {
                        usage.fail(
                        // replace $0 with observed, $1 with expected.
                        demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.max) : null);
                    }
                    else {
                        usage.fail(__('Too many non-option arguments: got %s, maximum of %s', _s, demandedCommands._.max));
                    }
                }
            }
        };
        // validate the appropriate # of <required>
        // positional arguments were provided:
        self.positionalCount = function positionalCount(required, observed) {
            if (observed < required) {
                usage.fail(__('Not enough non-option arguments: got %s, need at least %s', observed, required));
            }
        };
        // make sure all the required arguments are present.
        self.requiredArguments = function requiredArguments(argv) {
            const demandedOptions = yargs.getDemandedOptions();
            let missing = null;
            Object.keys(demandedOptions).forEach((key) => {
                if (!argv.hasOwnProperty(key) || typeof argv[key] === 'undefined') {
                    missing = missing || {};
                    missing[key] = demandedOptions[key];
                }
            });
            if (missing) {
                const customMsgs = [];
                Object.keys(missing).forEach((key) => {
                    const msg = missing[key];
                    if (msg && customMsgs.indexOf(msg) < 0) {
                        customMsgs.push(msg);
                    }
                });
                const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
                usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
            }
        };
        // check for unknown arguments (strict-mode).
        self.unknownArguments = function unknownArguments(argv, aliases, positionalMap) {
            const commandKeys = yargs.getCommandInstance().getCommands();
            const unknown = [];
            const currentContext = yargs.getContext();
            Object.keys(argv).forEach((key) => {
                if (specialKeys.indexOf(key) === -1 &&
                    !positionalMap.hasOwnProperty(key) &&
                    !yargs._getParseContext().hasOwnProperty(key) &&
                    !aliases.hasOwnProperty(key)) {
                    unknown.push(key);
                }
            });
            if (commandKeys.length > 0) {
                argv._.slice(currentContext.commands.length).forEach((key) => {
                    if (commandKeys.indexOf(key) === -1) {
                        unknown.push(key);
                    }
                });
            }
            if (unknown.length > 0) {
                usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', ')));
            }
        };
        // validate arguments limited to enumerated choices
        self.limitedChoices = function limitedChoices(argv) {
            const options = yargs.getOptions();
            const invalid = {};
            if (!Object.keys(options.choices).length)
                return;
            Object.keys(argv).forEach((key) => {
                if (specialKeys.indexOf(key) === -1 &&
                    options.choices.hasOwnProperty(key)) {
                    [].concat(argv[key]).forEach((value) => {
                        // TODO case-insensitive configurability
                        if (options.choices[key].indexOf(value) === -1 &&
                            value !== undefined) {
                            invalid[key] = (invalid[key] || []).concat(value);
                        }
                    });
                }
            });
            const invalidKeys = Object.keys(invalid);
            if (!invalidKeys.length)
                return;
            let msg = __('Invalid values:');
            invalidKeys.forEach((key) => {
                msg += `\n  ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
            });
            usage.fail(msg);
        };
        // custom checks, added using the `check` option on yargs.
        let checks = [];
        self.check = function check(f, global) {
            checks.push({
                func: f,
                global
            });
        };
        self.customChecks = function customChecks(argv, aliases) {
            for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
                const func = f.func;
                let result = null;
                try {
                    result = func(argv, aliases);
                }
                catch (err) {
                    usage.fail(err.message ? err.message : err, err);
                    continue;
                }
                if (!result) {
                    usage.fail(__('Argument check failed: %s', func.toString()));
                }
                else if (typeof result === 'string' || result instanceof Error) {
                    usage.fail(result.toString(), result);
                }
            }
        };
        // check implications, argument foo implies => argument bar.
        let implied = {};
        self.implies = function implies(key, value) {
            argsert('<string|object> [array|number|string]', [key, value], arguments.length);
            if (typeof key === 'object') {
                Object.keys(key).forEach((k) => {
                    self.implies(k, key[k]);
                });
            }
            else {
                yargs.global(key);
                if (!implied[key]) {
                    implied[key] = [];
                }
                if (Array.isArray(value)) {
                    value.forEach((i) => self.implies(key, i));
                }
                else {
                    implied[key].push(value);
                }
            }
        };
        self.getImplied = function getImplied() {
            return implied;
        };
        self.implications = function implications(argv) {
            const implyFail = [];
            Object.keys(implied).forEach((key) => {
                const origKey = key;
                (implied[key] || []).forEach((value) => {
                    let num;
                    let key = origKey;
                    const origValue = value;
                    // convert string '1' to number 1
                    num = Number(key);
                    key = isNaN(num) ? key : num;
                    if (typeof key === 'number') {
                        // check length of argv._
                        key = argv._.length >= key;
                    }
                    else if (key.match(/^--no-.+/)) {
                        // check if key doesn't exist
                        key = key.match(/^--no-(.+)/)[1];
                        key = !argv[key];
                    }
                    else {
                        // check if key exists
                        key = argv[key];
                    }
                    num = Number(value);
                    value = isNaN(num) ? value : num;
                    if (typeof value === 'number') {
                        value = argv._.length >= value;
                    }
                    else if (value.match(/^--no-.+/)) {
                        value = value.match(/^--no-(.+)/)[1];
                        value = !argv[value];
                    }
                    else {
                        value = argv[value];
                    }
                    if (key && !value) {
                        implyFail.push(` ${origKey} -> ${origValue}`);
                    }
                });
            });
            if (implyFail.length) {
                let msg = `${__('Implications failed:')}\n`;
                implyFail.forEach((value) => {
                    msg += (value);
                });
                usage.fail(msg);
            }
        };
        let conflicting = {};
        self.conflicts = function conflicts(key, value) {
            argsert('<string|object> [array|string]', [key, value], arguments.length);
            if (typeof key === 'object') {
                Object.keys(key).forEach((k) => {
                    self.conflicts(k, key[k]);
                });
            }
            else {
                yargs.global(key);
                if (!conflicting[key]) {
                    conflicting[key] = [];
                }
                if (Array.isArray(value)) {
                    value.forEach((i) => self.conflicts(key, i));
                }
                else {
                    conflicting[key].push(value);
                }
            }
        };
        self.getConflicting = () => conflicting;
        self.conflicting = function conflictingFn(argv) {
            Object.keys(argv).forEach((key) => {
                if (conflicting[key]) {
                    conflicting[key].forEach((value) => {
                        // we default keys to 'undefined' that have been configured, we should not
                        // apply conflicting check unless they are a value other than 'undefined'.
                        if (value && argv[key] !== undefined && argv[value] !== undefined) {
                            usage.fail(__(`Arguments ${key} and ${value} are mutually exclusive`));
                        }
                    });
                }
            });
        };
        self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
            const distance = require(384) /* ./levenshtein */;
            const threshold = 3; // if it takes more than three edits, let's move on.
            potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
            let recommended = null;
            let bestDistance = Infinity;
            for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
                const d = distance(cmd, candidate);
                if (d <= threshold && d < bestDistance) {
                    bestDistance = d;
                    recommended = candidate;
                }
            }
            if (recommended)
                usage.fail(__('Did you mean %s?', recommended));
        };
        self.reset = function reset(localLookup) {
            implied = objFilter(implied, (k, v) => !localLookup[k]);
            conflicting = objFilter(conflicting, (k, v) => !localLookup[k]);
            checks = checks.filter(c => c.global);
            return self;
        };
        let frozen;
        self.freeze = function freeze() {
            frozen = {};
            frozen.implied = implied;
            frozen.checks = checks;
            frozen.conflicting = conflicting;
        };
        self.unfreeze = function unfreeze() {
            implied = frozen.implied;
            checks = frozen.checks;
            conflicting = frozen.conflicting;
            frozen = undefined;
        };
        return self;
    };
}
,
/* yargs/lib/yerror */ function _(require, module, exports) {
    function YError(msg) {
        this.name = 'YError';
        this.message = msg || 'yargs error';
        Error.captureStackTrace(this, YError);
    }
    YError.prototype = Object.create(Error.prototype);
    YError.prototype.constructor = YError;
    module.exports = YError;
}
,
/* yargs/yargs */ function _(require, module, exports) {
    const argsert = require(381) /* ./lib/argsert */;
    const fs = require('fs');
    const Command = require(382) /* ./lib/command */;
    const Completion = require(383) /* ./lib/completion */;
    const Parser = require(377) /* yargs-parser */;
    const path = require('path');
    const Usage = require(386) /* ./lib/usage */;
    const Validation = require(387) /* ./lib/validation */;
    const Y18n = require(375) /* y18n */;
    const objFilter = require(385) /* ./lib/obj-filter */;
    const setBlocking = require(313) /* set-blocking */;
    const applyExtends = require(380) /* ./lib/apply-extends */;
    const YError = require(388) /* ./lib/yerror */;
    exports = module.exports = Yargs;
    function Yargs(processArgs, cwd, parentRequire) {
        processArgs = processArgs || []; // handle calling yargs().
        const self = {};
        let command = null;
        let completion = null;
        let groups = {};
        let output = '';
        let preservedGroups = {};
        let usage = null;
        let validation = null;
        const y18n = Y18n({
            directory: path.resolve(__dirname, './locales'),
            updateFiles: false
        });
        if (!cwd)
            cwd = process.cwd();
        self.$0 = process.argv
            .slice(0, 2)
            .map((x, i) => {
            // ignore the node bin, specify this in your
            // bin file with #!/usr/bin/env node
            if (i === 0 && /\b(node|iojs)(\.exe)?$/.test(x))
                return;
            const b = rebase(cwd, x);
            return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
        })
            .join(' ').trim();
        if (process.env._ !== undefined && process.argv[1] === process.env._) {
            self.$0 = process.env._.replace(`${path.dirname(process.execPath)}/`, '');
        }
        // use context object to keep track of resets, subcommand execution, etc
        // submodules should modify and check the state of context as necessary
        const context = { resets: -1, commands: [], fullCommands: [], files: [] };
        self.getContext = () => context;
        // puts yargs back into an initial state. any keys
        // that have been set to "global" will not be reset
        // by this action.
        let options;
        self.resetOptions = self.reset = function resetOptions(aliases) {
            context.resets++;
            aliases = aliases || {};
            options = options || {};
            // put yargs back into an initial state, this
            // logic is used to build a nested command
            // hierarchy.
            const tmpOptions = {};
            tmpOptions.local = options.local ? options.local : [];
            tmpOptions.configObjects = options.configObjects ? options.configObjects : [];
            // if a key has been explicitly set as local,
            // we should reset it before passing options to command.
            const localLookup = {};
            tmpOptions.local.forEach((l) => {
                localLookup[l] = true;
                (aliases[l] || []).forEach((a) => {
                    localLookup[a] = true;
                });
            });
            // preserve all groups not set to local.
            preservedGroups = Object.keys(groups).reduce((acc, groupName) => {
                const keys = groups[groupName].filter(key => !(key in localLookup));
                if (keys.length > 0) {
                    acc[groupName] = keys;
                }
                return acc;
            }, {});
            // groups can now be reset
            groups = {};
            const arrayOptions = [
                'array', 'boolean', 'string', 'skipValidation',
                'count', 'normalize', 'number'
            ];
            const objectOptions = [
                'narg', 'key', 'alias', 'default', 'defaultDescription',
                'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
            ];
            arrayOptions.forEach((k) => {
                tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k]);
            });
            objectOptions.forEach((k) => {
                tmpOptions[k] = objFilter(options[k], (k, v) => !localLookup[k]);
            });
            tmpOptions.envPrefix = options.envPrefix;
            options = tmpOptions;
            // if this is the first time being executed, create
            // instances of all our helpers -- otherwise just reset.
            usage = usage ? usage.reset(localLookup) : Usage(self, y18n);
            validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n);
            command = command ? command.reset() : Command(self, usage, validation);
            if (!completion)
                completion = Completion(self, usage, command);
            completionCommand = null;
            output = '';
            exitError = null;
            hasOutput = false;
            self.parsed = false;
            return self;
        };
        self.resetOptions();
        // temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
        let frozen;
        function freeze() {
            frozen = {};
            frozen.options = options;
            frozen.configObjects = options.configObjects.slice(0);
            frozen.exitProcess = exitProcess;
            frozen.groups = groups;
            usage.freeze();
            validation.freeze();
            command.freeze();
            frozen.strict = strict;
            frozen.completionCommand = completionCommand;
            frozen.output = output;
            frozen.exitError = exitError;
            frozen.hasOutput = hasOutput;
            frozen.parsed = self.parsed;
        }
        function unfreeze() {
            options = frozen.options;
            options.configObjects = frozen.configObjects;
            exitProcess = frozen.exitProcess;
            groups = frozen.groups;
            output = frozen.output;
            exitError = frozen.exitError;
            hasOutput = frozen.hasOutput;
            self.parsed = frozen.parsed;
            usage.unfreeze();
            validation.unfreeze();
            command.unfreeze();
            strict = frozen.strict;
            completionCommand = frozen.completionCommand;
            parseFn = null;
            parseContext = null;
            frozen = undefined;
        }
        self.boolean = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintArray('boolean', keys);
            return self;
        };
        self.array = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintArray('array', keys);
            return self;
        };
        self.number = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintArray('number', keys);
            return self;
        };
        self.normalize = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintArray('normalize', keys);
            return self;
        };
        self.count = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintArray('count', keys);
            return self;
        };
        self.string = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintArray('string', keys);
            return self;
        };
        self.requiresArg = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintObject(self.nargs, false, 'narg', keys, 1);
            return self;
        };
        self.skipValidation = function (keys) {
            argsert('<array|string>', [keys], arguments.length);
            populateParserHintArray('skipValidation', keys);
            return self;
        };
        function populateParserHintArray(type, keys, value) {
            keys = [].concat(keys);
            keys.forEach((key) => {
                options[type].push(key);
            });
        }
        self.nargs = function (key, value) {
            argsert('<string|object|array> [number]', [key, value], arguments.length);
            populateParserHintObject(self.nargs, false, 'narg', key, value);
            return self;
        };
        self.choices = function (key, value) {
            argsert('<object|string|array> [string|array]', [key, value], arguments.length);
            populateParserHintObject(self.choices, true, 'choices', key, value);
            return self;
        };
        self.alias = function (key, value) {
            argsert('<object|string|array> [string|array]', [key, value], arguments.length);
            populateParserHintObject(self.alias, true, 'alias', key, value);
            return self;
        };
        // TODO: actually deprecate self.defaults.
        self.default = self.defaults = function (key, value, defaultDescription) {
            argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length);
            if (defaultDescription)
                options.defaultDescription[key] = defaultDescription;
            if (typeof value === 'function') {
                if (!options.defaultDescription[key])
                    options.defaultDescription[key] = usage.functionDescription(value);
                value = value.call();
            }
            populateParserHintObject(self.default, false, 'default', key, value);
            return self;
        };
        self.describe = function (key, desc) {
            argsert('<object|string|array> [string]', [key, desc], arguments.length);
            populateParserHintObject(self.describe, false, 'key', key, true);
            usage.describe(key, desc);
            return self;
        };
        self.demandOption = function (keys, msg) {
            argsert('<object|string|array> [string]', [keys, msg], arguments.length);
            populateParserHintObject(self.demandOption, false, 'demandedOptions', keys, msg);
            return self;
        };
        self.coerce = function (keys, value) {
            argsert('<object|string|array> [function]', [keys, value], arguments.length);
            populateParserHintObject(self.coerce, false, 'coerce', keys, value);
            return self;
        };
        function populateParserHintObject(builder, isArray, type, key, value) {
            if (Array.isArray(key)) {
                // an array of keys with one value ['x', 'y', 'z'], function parse () {}
                const temp = {};
                key.forEach((k) => {
                    temp[k] = value;
                });
                builder(temp);
            }
            else if (typeof key === 'object') {
                // an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
                Object.keys(key).forEach((k) => {
                    builder(k, key[k]);
                });
            }
            else {
                // a single key value pair 'x', parse() {}
                if (isArray) {
                    options[type][key] = (options[type][key] || []).concat(value);
                }
                else {
                    options[type][key] = value;
                }
            }
        }
        function deleteFromParserHintObject(optionKey) {
            // delete from all parsing hints:
            // boolean, array, key, alias, etc.
            Object.keys(options).forEach((hintKey) => {
                const hint = options[hintKey];
                if (Array.isArray(hint)) {
                    if (~hint.indexOf(optionKey))
                        hint.splice(hint.indexOf(optionKey), 1);
                }
                else if (typeof hint === 'object') {
                    delete hint[optionKey];
                }
            });
            // now delete the description from usage.js.
            delete usage.getDescriptions()[optionKey];
        }
        self.config = function config(key, msg, parseFn) {
            argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length);
            // allow a config object to be provided directly.
            if (typeof key === 'object') {
                key = applyExtends(key, cwd);
                options.configObjects = (options.configObjects || []).concat(key);
                return self;
            }
            // allow for a custom parsing function.
            if (typeof msg === 'function') {
                parseFn = msg;
                msg = null;
            }
            key = key || 'config';
            self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'));
            (Array.isArray(key) ? key : [key]).forEach((k) => {
                options.config[k] = parseFn || true;
            });
            return self;
        };
        self.example = function (cmd, description) {
            argsert('<string> [string]', [cmd, description], arguments.length);
            usage.example(cmd, description);
            return self;
        };
        self.command = function (cmd, description, builder, handler, middlewares) {
            argsert('<string|array|object> [string|boolean] [function|object] [function] [array]', [cmd, description, builder, handler, middlewares], arguments.length);
            command.addHandler(cmd, description, builder, handler, middlewares);
            return self;
        };
        self.commandDir = function (dir, opts) {
            argsert('<string> [object]', [dir, opts], arguments.length);
            const req = parentRequire || require;
            command.addDirectory(dir, self.getContext(), req, require(114) /* get-caller-file */(), opts);
            return self;
        };
        // TODO: deprecate self.demand in favor of
        // .demandCommand() .demandOption().
        self.demand = self.required = self.require = function demand(keys, max, msg) {
            // you can optionally provide a 'max' key,
            // which will raise an exception if too many '_'
            // options are provided.
            if (Array.isArray(max)) {
                max.forEach((key) => {
                    self.demandOption(key, msg);
                });
                max = Infinity;
            }
            else if (typeof max !== 'number') {
                msg = max;
                max = Infinity;
            }
            if (typeof keys === 'number') {
                self.demandCommand(keys, max, msg, msg);
            }
            else if (Array.isArray(keys)) {
                keys.forEach((key) => {
                    self.demandOption(key, msg);
                });
            }
            else {
                if (typeof msg === 'string') {
                    self.demandOption(keys, msg);
                }
                else if (msg === true || typeof msg === 'undefined') {
                    self.demandOption(keys);
                }
            }
            return self;
        };
        self.demandCommand = function demandCommand(min, max, minMsg, maxMsg) {
            argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length);
            if (typeof min === 'undefined')
                min = 1;
            if (typeof max !== 'number') {
                minMsg = max;
                max = Infinity;
            }
            self.global('_', false);
            options.demandedCommands._ = {
                min,
                max,
                minMsg,
                maxMsg
            };
            return self;
        };
        self.getDemandedOptions = () => {
            argsert([], 0);
            return options.demandedOptions;
        };
        self.getDemandedCommands = () => {
            argsert([], 0);
            return options.demandedCommands;
        };
        self.implies = function (key, value) {
            argsert('<string|object> [number|string|array]', [key, value], arguments.length);
            validation.implies(key, value);
            return self;
        };
        self.conflicts = function (key1, key2) {
            argsert('<string|object> [string|array]', [key1, key2], arguments.length);
            validation.conflicts(key1, key2);
            return self;
        };
        self.usage = function (msg, description, builder, handler) {
            argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length);
            if (description !== undefined) {
                // .usage() can be used as an alias for defining
                // a default command.
                if ((msg || '').match(/^\$0( |$)/)) {
                    return self.command(msg, description, builder, handler);
                }
                else {
                    throw new YError('.usage() description must start with $0 if being used as alias for .command()');
                }
            }
            else {
                usage.usage(msg);
                return self;
            }
        };
        self.epilogue = self.epilog = function (msg) {
            argsert('<string>', [msg], arguments.length);
            usage.epilog(msg);
            return self;
        };
        self.fail = function (f) {
            argsert('<function>', [f], arguments.length);
            usage.failFn(f);
            return self;
        };
        self.check = function (f, _global) {
            argsert('<function> [boolean]', [f, _global], arguments.length);
            validation.check(f, _global !== false);
            return self;
        };
        self.global = function global(globals, global) {
            argsert('<string|array> [boolean]', [globals, global], arguments.length);
            globals = [].concat(globals);
            if (global !== false) {
                options.local = options.local.filter(l => globals.indexOf(l) === -1);
            }
            else {
                globals.forEach((g) => {
                    if (options.local.indexOf(g) === -1)
                        options.local.push(g);
                });
            }
            return self;
        };
        self.pkgConf = function pkgConf(key, path) {
            argsert('<string> [string]', [key, path], arguments.length);
            let conf = null;
            // prefer cwd to require-main-filename in this method
            // since we're looking for e.g. "nyc" config in nyc consumer
            // rather than "yargs" config in nyc (where nyc is the main filename)
            const obj = pkgUp(path || cwd);
            // If an object exists in the key, add it to options.configObjects
            if (obj[key] && typeof obj[key] === 'object') {
                conf = applyExtends(obj[key], path || cwd);
                options.configObjects = (options.configObjects || []).concat(conf);
            }
            return self;
        };
        const pkgs = {};
        function pkgUp(path) {
            const npath = path || '*';
            if (pkgs[npath])
                return pkgs[npath];
            const findUp = require(110) /* find-up */;
            let obj = {};
            try {
                const pkgJsonPath = findUp.sync('package.json', {
                    cwd: path || require('path').dirname(require(309) /* require-main-filename */(parentRequire || require)),
                    normalize: false
                });
                obj = JSON.parse(fs.readFileSync(pkgJsonPath));
            }
            catch (noop) { }
            pkgs[npath] = obj || {};
            return pkgs[npath];
        }
        let parseFn = null;
        let parseContext = null;
        self.parse = function parse(args, shortCircuit, _parseFn) {
            argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length);
            if (typeof args === 'undefined')
                args = processArgs;
            // a context object can optionally be provided, this allows
            // additional information to be passed to a command handler.
            if (typeof shortCircuit === 'object') {
                parseContext = shortCircuit;
                shortCircuit = _parseFn;
            }
            // by providing a function as a second argument to
            // parse you can capture output that would otherwise
            // default to printing to stdout/stderr.
            if (typeof shortCircuit === 'function') {
                parseFn = shortCircuit;
                shortCircuit = null;
            }
            // completion short-circuits the parsing process,
            // skipping validation, etc.
            if (!shortCircuit)
                processArgs = args;
            freeze();
            if (parseFn)
                exitProcess = false;
            const parsed = self._parseArgs(args, shortCircuit);
            if (parseFn)
                parseFn(exitError, parsed, output);
            unfreeze();
            return parsed;
        };
        self._getParseContext = () => parseContext || {};
        self._hasParseCallback = () => !!parseFn;
        self.option = self.options = function option(key, opt) {
            argsert('<string|object> [object]', [key, opt], arguments.length);
            if (typeof key === 'object') {
                Object.keys(key).forEach((k) => {
                    self.options(k, key[k]);
                });
            }
            else {
                if (typeof opt !== 'object') {
                    opt = {};
                }
                options.key[key] = true; // track manually set keys.
                if (opt.alias)
                    self.alias(key, opt.alias);
                const demand = opt.demand || opt.required || opt.require;
                // deprecated, use 'demandOption' instead
                if (demand) {
                    self.demand(key, demand);
                }
                if (opt.demandOption) {
                    self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined);
                }
                if ('conflicts' in opt) {
                    self.conflicts(key, opt.conflicts);
                }
                if ('default' in opt) {
                    self.default(key, opt.default);
                }
                if ('implies' in opt) {
                    self.implies(key, opt.implies);
                }
                if ('nargs' in opt) {
                    self.nargs(key, opt.nargs);
                }
                if (opt.config) {
                    self.config(key, opt.configParser);
                }
                if (opt.normalize) {
                    self.normalize(key);
                }
                if ('choices' in opt) {
                    self.choices(key, opt.choices);
                }
                if ('coerce' in opt) {
                    self.coerce(key, opt.coerce);
                }
                if ('group' in opt) {
                    self.group(key, opt.group);
                }
                if (opt.boolean || opt.type === 'boolean') {
                    self.boolean(key);
                    if (opt.alias)
                        self.boolean(opt.alias);
                }
                if (opt.array || opt.type === 'array') {
                    self.array(key);
                    if (opt.alias)
                        self.array(opt.alias);
                }
                if (opt.number || opt.type === 'number') {
                    self.number(key);
                    if (opt.alias)
                        self.number(opt.alias);
                }
                if (opt.string || opt.type === 'string') {
                    self.string(key);
                    if (opt.alias)
                        self.string(opt.alias);
                }
                if (opt.count || opt.type === 'count') {
                    self.count(key);
                }
                if (typeof opt.global === 'boolean') {
                    self.global(key, opt.global);
                }
                if (opt.defaultDescription) {
                    options.defaultDescription[key] = opt.defaultDescription;
                }
                if (opt.skipValidation) {
                    self.skipValidation(key);
                }
                const desc = opt.describe || opt.description || opt.desc;
                if (!opt.hidden) {
                    self.describe(key, desc);
                }
                if (opt.requiresArg) {
                    self.requiresArg(key);
                }
            }
            return self;
        };
        self.getOptions = () => options;
        self.positional = function (key, opts) {
            argsert('<string> <object>', [key, opts], arguments.length);
            if (context.resets === 0) {
                throw new YError(".positional() can only be called in a command's builder function");
            }
            // .positional() only supports a subset of the configuration
            // options availble to .option().
            const supportedOpts = ['default', 'implies', 'normalize',
                'choices', 'conflicts', 'coerce', 'type', 'describe',
                'desc', 'description', 'alias'];
            opts = objFilter(opts, (k, v) => {
                let accept = supportedOpts.indexOf(k) !== -1;
                // type can be one of string|number|boolean.
                if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1)
                    accept = false;
                return accept;
            });
            // copy over any settings that can be inferred from the command string.
            const fullCommand = context.fullCommands[context.fullCommands.length - 1];
            const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : {
                array: [],
                alias: {},
                default: {},
                demand: {}
            };
            Object.keys(parseOptions).forEach((pk) => {
                if (Array.isArray(parseOptions[pk])) {
                    if (parseOptions[pk].indexOf(key) !== -1)
                        opts[pk] = true;
                }
                else {
                    if (parseOptions[pk][key] && !(pk in opts))
                        opts[pk] = parseOptions[pk][key];
                }
            });
            self.group(key, usage.getPositionalGroupName());
            return self.option(key, opts);
        };
        self.group = function group(opts, groupName) {
            argsert('<string|array> <string>', [opts, groupName], arguments.length);
            const existing = preservedGroups[groupName] || groups[groupName];
            if (preservedGroups[groupName]) {
                // we now only need to track this group name in groups.
                delete preservedGroups[groupName];
            }
            const seen = {};
            groups[groupName] = (existing || []).concat(opts).filter((key) => {
                if (seen[key])
                    return false;
                return (seen[key] = true);
            });
            return self;
        };
        // combine explicit and preserved groups. explicit groups should be first
        self.getGroups = () => Object.assign({}, groups, preservedGroups);
        // as long as options.envPrefix is not undefined,
        // parser will apply env vars matching prefix to argv
        self.env = function (prefix) {
            argsert('[string|boolean]', [prefix], arguments.length);
            if (prefix === false)
                options.envPrefix = undefined;
            else
                options.envPrefix = prefix || '';
            return self;
        };
        self.wrap = function (cols) {
            argsert('<number|null|undefined>', [cols], arguments.length);
            usage.wrap(cols);
            return self;
        };
        let strict = false;
        self.strict = function (enabled) {
            argsert('[boolean]', [enabled], arguments.length);
            strict = enabled !== false;
            return self;
        };
        self.getStrict = () => strict;
        self.showHelp = function (level) {
            argsert('[string|function]', [level], arguments.length);
            if (!self.parsed)
                self._parseArgs(processArgs); // run parser, if it has not already been executed.
            if (command.hasDefaultCommand()) {
                context.resets++; // override the restriction on top-level positoinals.
                command.runDefaultBuilderOn(self, true);
            }
            usage.showHelp(level);
            return self;
        };
        let versionOpt = null;
        self.version = function version(opt, msg, ver) {
            const defaultVersionOpt = 'version';
            argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length);
            // nuke the key previously configured
            // to return version #.
            if (versionOpt) {
                deleteFromParserHintObject(versionOpt);
                usage.version(undefined);
                versionOpt = null;
            }
            if (arguments.length === 0) {
                ver = guessVersion();
                opt = defaultVersionOpt;
            }
            else if (arguments.length === 1) {
                if (opt === false) { // disable default 'version' key.
                    return self;
                }
                ver = opt;
                opt = defaultVersionOpt;
            }
            else if (arguments.length === 2) {
                ver = msg;
                msg = null;
            }
            versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
            msg = msg || usage.deferY18nLookup('Show version number');
            usage.version(ver || undefined);
            self.boolean(versionOpt);
            self.describe(versionOpt, msg);
            return self;
        };
        function guessVersion() {
            const obj = pkgUp();
            return obj.version || 'unknown';
        }
        let helpOpt = null;
        self.addHelpOpt = self.help = function addHelpOpt(opt, msg) {
            const defaultHelpOpt = 'help';
            argsert('[string|boolean] [string]', [opt, msg], arguments.length);
            // nuke the key previously configured
            // to return help.
            if (helpOpt) {
                deleteFromParserHintObject(helpOpt);
                helpOpt = null;
            }
            if (arguments.length === 1) {
                if (opt === false)
                    return self;
            }
            // use arguments, fallback to defaults for opt and msg
            helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
            self.boolean(helpOpt);
            self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'));
            return self;
        };
        self.showHelpOnFail = function showHelpOnFail(enabled, message) {
            argsert('[boolean|string] [string]', [enabled, message], arguments.length);
            usage.showHelpOnFail(enabled, message);
            return self;
        };
        var exitProcess = true;
        self.exitProcess = function (enabled) {
            argsert('[boolean]', [enabled], arguments.length);
            if (typeof enabled !== 'boolean') {
                enabled = true;
            }
            exitProcess = enabled;
            return self;
        };
        self.getExitProcess = () => exitProcess;
        var completionCommand = null;
        self.completion = function (cmd, desc, fn) {
            argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length);
            // a function to execute when generating
            // completions can be provided as the second
            // or third argument to completion.
            if (typeof desc === 'function') {
                fn = desc;
                desc = null;
            }
            // register the completion command.
            completionCommand = cmd || 'completion';
            if (!desc && desc !== false) {
                desc = 'generate bash completion script';
            }
            self.command(completionCommand, desc);
            // a function can be provided
            if (fn)
                completion.registerFunction(fn);
            return self;
        };
        self.showCompletionScript = function ($0) {
            argsert('[string]', [$0], arguments.length);
            $0 = $0 || self.$0;
            _logger.log(completion.generateCompletionScript($0, completionCommand));
            return self;
        };
        self.getCompletion = function (args, done) {
            argsert('<array> <function>', [args, done], arguments.length);
            completion.getCompletion(args, done);
        };
        self.locale = function (locale) {
            argsert('[string]', [locale], arguments.length);
            if (arguments.length === 0) {
                guessLocale();
                return y18n.getLocale();
            }
            detectLocale = false;
            y18n.setLocale(locale);
            return self;
        };
        self.updateStrings = self.updateLocale = function (obj) {
            argsert('<object>', [obj], arguments.length);
            detectLocale = false;
            y18n.updateLocale(obj);
            return self;
        };
        let detectLocale = true;
        self.detectLocale = function (detect) {
            argsert('<boolean>', [detect], arguments.length);
            detectLocale = detect;
            return self;
        };
        self.getDetectLocale = () => detectLocale;
        var hasOutput = false;
        var exitError = null;
        // maybe exit, always capture
        // context about why we wanted to exit.
        self.exit = (code, err) => {
            hasOutput = true;
            exitError = err;
            if (exitProcess)
                process.exit(code);
        };
        // we use a custom logger that buffers output,
        // so that we can print to non-CLIs, e.g., chat-bots.
        const _logger = {
            log() {
                const args = [];
                for (let i = 0; i < arguments.length; i++)
                    args.push(arguments[i]);
                if (!self._hasParseCallback())
                    console.log.apply(console, args);
                hasOutput = true;
                if (output.length)
                    output += '\n';
                output += args.join(' ');
            },
            error() {
                const args = [];
                for (let i = 0; i < arguments.length; i++)
                    args.push(arguments[i]);
                if (!self._hasParseCallback())
                    console.error.apply(console, args);
                hasOutput = true;
                if (output.length)
                    output += '\n';
                output += args.join(' ');
            }
        };
        self._getLoggerInstance = () => _logger;
        // has yargs output an error our help
        // message in the current execution context.
        self._hasOutput = () => hasOutput;
        self._setHasOutput = () => {
            hasOutput = true;
        };
        let recommendCommands;
        self.recommendCommands = function (recommend) {
            argsert('[boolean]', [recommend], arguments.length);
            recommendCommands = typeof recommend === 'boolean' ? recommend : true;
            return self;
        };
        self.getUsageInstance = () => usage;
        self.getValidationInstance = () => validation;
        self.getCommandInstance = () => command;
        self.terminalWidth = () => {
            argsert([], 0);
            return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null;
        };
        Object.defineProperty(self, 'argv', {
            get: () => self._parseArgs(processArgs),
            enumerable: true
        });
        self._parseArgs = function parseArgs(args, shortCircuit, _skipValidation, commandIndex) {
            let skipValidation = !!_skipValidation;
            args = args || processArgs;
            options.__ = y18n.__;
            options.configuration = pkgUp()['yargs'] || {};
            const parsed = Parser.detailed(args, options);
            let argv = parsed.argv;
            if (parseContext)
                argv = Object.assign({}, argv, parseContext);
            const aliases = parsed.aliases;
            argv.$0 = self.$0;
            self.parsed = parsed;
            try {
                guessLocale(); // guess locale lazily, so that it can be turned off in chain.
                // while building up the argv object, there
                // are two passes through the parser. If completion
                // is being performed short-circuit on the first pass.
                if (shortCircuit) {
                    return argv;
                }
                // if there's a handler associated with a
                // command defer processing to it.
                if (helpOpt) {
                    // consider any multi-char helpOpt alias as a valid help command
                    // unless all helpOpt aliases are single-char
                    // note that parsed.aliases is a normalized bidirectional map :)
                    const helpCmds = [helpOpt]
                        .concat(aliases[helpOpt] || [])
                        .filter(k => k.length > 1);
                    // check if help should trigger and strip it from _.
                    if (~helpCmds.indexOf(argv._[argv._.length - 1])) {
                        argv._.pop();
                        argv[helpOpt] = true;
                    }
                }
                const handlerKeys = command.getCommands();
                const skipDefaultCommand = argv[helpOpt] && (handlerKeys.length > 1 || handlerKeys[0] !== '$0');
                if (argv._.length) {
                    if (handlerKeys.length) {
                        let firstUnknownCommand;
                        for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) {
                            cmd = String(argv._[i]);
                            if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
                                setPlaceholderKeys(argv);
                                // commands are executed using a recursive algorithm that executes
                                // the deepest command first; we keep track of the position in the
                                // argv._ array that is currently being executed.
                                return command.runCommand(cmd, self, parsed, i + 1);
                            }
                            else if (!firstUnknownCommand && cmd !== completionCommand) {
                                firstUnknownCommand = cmd;
                                break;
                            }
                        }
                        // run the default command, if defined
                        if (command.hasDefaultCommand() && !skipDefaultCommand) {
                            setPlaceholderKeys(argv);
                            return command.runCommand(null, self, parsed);
                        }
                        // recommend a command if recommendCommands() has
                        // been enabled, and no commands were found to execute
                        if (recommendCommands && firstUnknownCommand && !argv[helpOpt]) {
                            validation.recommendCommands(firstUnknownCommand, handlerKeys);
                        }
                    }
                    // generate a completion script for adding to ~/.bashrc.
                    if (completionCommand && ~argv._.indexOf(completionCommand) && !argv[completion.completionKey]) {
                        if (exitProcess)
                            setBlocking(true);
                        self.showCompletionScript();
                        self.exit(0);
                    }
                }
                else if (command.hasDefaultCommand() && !skipDefaultCommand) {
                    setPlaceholderKeys(argv);
                    return command.runCommand(null, self, parsed);
                }
                // we must run completions first, a user might
                // want to complete the --help or --version option.
                if (completion.completionKey in argv) {
                    if (exitProcess)
                        setBlocking(true);
                    // we allow for asynchronous completions,
                    // e.g., loading in a list of commands from an API.
                    const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1);
                    completion.getCompletion(completionArgs, (completions) => {
                        ;
                        (completions || []).forEach((completion) => {
                            _logger.log(completion);
                        });
                        self.exit(0);
                    });
                    return setPlaceholderKeys(argv);
                }
                // Handle 'help' and 'version' options
                // if we haven't already output help!
                if (!hasOutput) {
                    Object.keys(argv).forEach((key) => {
                        if (key === helpOpt && argv[key]) {
                            if (exitProcess)
                                setBlocking(true);
                            skipValidation = true;
                            self.showHelp('log');
                            self.exit(0);
                        }
                        else if (key === versionOpt && argv[key]) {
                            if (exitProcess)
                                setBlocking(true);
                            skipValidation = true;
                            usage.showVersion();
                            self.exit(0);
                        }
                    });
                }
                // Check if any of the options to skip validation were provided
                if (!skipValidation && options.skipValidation.length > 0) {
                    skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true);
                }
                // If the help or version options where used and exitProcess is false,
                // or if explicitly skipped, we won't run validations.
                if (!skipValidation) {
                    if (parsed.error)
                        throw new YError(parsed.error.message);
                    // if we're executed via bash completion, don't
                    // bother with validation.
                    if (!argv[completion.completionKey]) {
                        self._runValidation(argv, aliases, {}, parsed.error);
                    }
                }
            }
            catch (err) {
                if (err instanceof YError)
                    usage.fail(err.message, err);
                else
                    throw err;
            }
            return setPlaceholderKeys(argv);
        };
        self._runValidation = function runValidation(argv, aliases, positionalMap, parseErrors) {
            if (parseErrors)
                throw new YError(parseErrors.message);
            validation.nonOptionCount(argv);
            validation.requiredArguments(argv);
            if (strict)
                validation.unknownArguments(argv, aliases, positionalMap);
            validation.customChecks(argv, aliases);
            validation.limitedChoices(argv);
            validation.implications(argv);
            validation.conflicting(argv);
        };
        function guessLocale() {
            if (!detectLocale)
                return;
            try {
                const osLocale = require(271) /* os-locale */;
                self.locale(osLocale.sync({ spawn: false }));
            }
            catch (err) {
                // if we explode looking up locale just noop
                // we'll keep using the default language 'en'.
            }
        }
        function setPlaceholderKeys(argv) {
            Object.keys(options.key).forEach((key) => {
                // don't set placeholder keys for dot
                // notation options 'foo.bar'.
                if (~key.indexOf('.'))
                    return;
                if (typeof argv[key] === 'undefined')
                    argv[key] = undefined;
            });
            return argv;
        }
        // an app should almost always have --version and --help,
        // if you *really* want to disable this use .help(false)/.version(false).
        self.help();
        self.version();
        return self;
    }
    // rebase an absolute path to a relative one with respect to a base directory
    // exported for tests
    exports.rebase = rebase;
    function rebase(base, dir) {
        return path.relative(base, dir);
    }
}

], {"compile":0,"dependencies":1}, 0, typeof "require" !== "undefined" && require);
})

//# sourceMappingURL=compiler.js.map
